首页 > 技术文章 > 最新vue项目添加水印

dupenghui 2020-06-10 14:20 原文

在utils文件夹中创建 wartermark.ts 文件(位置看自己的组件放那,这都行),内容如下:

 1 "use strict";
 2 
 3 const setWatermark = (str: any) => {
 4   const id = "1.23452384164.123412416";
 5 
 6   if (document.getElementById(id) !== null) {
 7     document.body.removeChild(document.getElementById(id) as any);
 8   }
 9 
10   //创建一个画布
11   const can = document.createElement("canvas");
12   //设置画布的长宽
13   can.width = 250;
14   can.height = 120;
15 
16   const cans: any = can.getContext("2d");
17   //旋转角度
18   cans.rotate((-15 * Math.PI) / 150);
19   cans.font = "18px Vedana";
20   //设置填充绘画的颜色、渐变或者模式
21   cans.fillStyle = "rgba(200, 200, 200, 0.30)";
22   //设置文本内容的当前对齐方式
23   cans.textAlign = "left";
24   //设置在绘制文本时使用的当前文本基线
25   cans.textBaseline = "Middle";
26   //在画布上绘制填色的文本(输出的文本,开始绘制文本的X坐标位置,开始绘制文本的Y坐标位置)
27   cans.fillText(str, can.width / 8, can.height / 2);
28 
29   const div = document.createElement("div");
30   div.id = id;
31   div.style.pointerEvents = "none";
32   div.style.top = "35px";
33   div.style.left = "0px";
34   div.style.position = "fixed";
35   div.style.zIndex = "100000";
36   div.style.width = document.documentElement.clientWidth + "px";
37   div.style.height = document.documentElement.clientHeight + "px";
38   div.style.background =
39     "url(" + can.toDataURL("image/png") + ") left top repeat";
40   document.body.appendChild(div);
41   return id;
42 };
43 const watermark = {
44   // 该方法只允许调用一次
45   set: (str: any) => {
46     let id = setWatermark(str);
47     setInterval(() => {
48       if (document.getElementById(id) === null) {
49         id = setWatermark(str);
50       }
51     }, 500);
52     window.onresize = () => {
53       setWatermark(str);
54     };
55   }
56 }
57 export default watermark;

2、在API.vue文件中引用 wartermark.ts 

 1 <script lang="ts">
 2 import './assets/styles/base.scss'
 3 import { Component, Vue } from 'vue-property-decorator'
 4 import { theme, getQueryString } from '@/utils/util'
 5 import logoutUrl from '@/utils/api/logoutUrl'
 6 
 7 import Watermark from '@/utils/main/wartermark';
 8 
 9 export default class App extends Vue {
10   mounted () {
11     Watermark.set("水印内容")
12   }
13   
14 }
15 </script>

 

推荐阅读