赞
踩
- import html2canvas from 'html2canvas'; // npm install --save html2canvas (官网:https://html2canvas.hertzen.com)
- export default {
- addWatermark({
- container = document.body, // 水印添加到的容器
- innerHTML = "水印文字内容", // 水印文字的内容
- rotate = -30,//默认文字旋转角度
- cssText = `
- box-sizing: border-box;
- width: max-content;
- height: max-content;
- padding: 30px;
- font-size: 12px;
- font-family: 'Microsoft YaHei';
- color: #00000022;
- transform-origin:center;
- transform: rotate(-30deg);
- z-index: 999999;
- pointer-events: none;
- display: flex;
- justify-content: center;
- align-items: center;
- `,//水印模板文本的默认样式
- className = '__sgWatermark__',//水印类名
- } = {}) {
- let dom = document.createElement("div");
- dom.innerHTML = innerHTML;
- dom.style.cssText = cssText;//默认样式
- dom.style.transform = `rotate(${rotate}deg)`;//旋转角度
- container.appendChild(dom);//添加模板文本
- // ----------------------------------------
- html2canvas(dom, { backgroundColor: 'transparent', logging: false, }).then(canvas => {
- dom.parentNode.removeChild(dom);//移除模板文本
- let base64Url = canvas.toDataURL('image/png', 1.0);
- const __sgWatermark__ = document.querySelector(`.${className}`);
- const watermarkDiv = __sgWatermark__ || document.createElement("div");
- watermarkDiv.style.cssText = `transition: .618s ease;opacity: 0;position: fixed; top: 0; left: 0; bottom: 0; right: 0; pointer-events: none; z-index: 999999999; background: url(${base64Url}); `;
- setTimeout(() => {
- watermarkDiv.style.opacity = 1;//缓慢出现
- }, 0);
- watermarkDiv.className = className;
- __sgWatermark__ || container.insertBefore(watermarkDiv, container.firstChild);
- });
- },
- removeWatermark(
- className = '__sgWatermark__',//水印类名
- ) {
- const dom = document.querySelector(`.${className}`);
- dom.parentNode.removeChild(dom);
- },
- };
- <template>
- <div :class="$options.name">
- <el-button type="primary" style="width: 300px; height: 100px">主要按钮</el-button>
- <div
- ref="div"
- style="
- width: 600px;
- height: 300px;
- background-color: #00000011;
- display: flex;
- justify-content: center;
- align-items: center;
- "
- >
- 局部div
- </div>
- </div>
- </template>
- <script>
- import sgWatermark from "@/js/sgWatermark";
- export default {
- mounted() {
- // 示例1
- sgWatermark.addWatermark();
- // 示例2
- // sgWatermark.addWatermark({ container: this.$el, innerHTML: `高启强(No:201314)` });
- // 示例3
- // sgWatermark.addWatermark({ container: this.$refs.div, innerHTML: `<b style="color: #F56C6C88;font-weight: bold;font-size: 24px;" >你挚爱的强哥</b>` });
- },
- };
- </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。