在utils文件夾中建立 wartermark.ts 文件(位置看本身的組件放那,這都行),內容以下:css
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;
二、在API.vue文件中引用 wartermark.ts vue
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>