1.在src下得到utils里新建一个文件watermark.js
/** 水印添加方法 */let setWatermark = (str1, str2) => {let id = '1.23452384164.123412415'if (document.getElementById(id) !== null) {document.body.removeChild(document.getElementById(id))}let can = document.createElement('canvas')// 设置canvas画布大小can.width = 300can.height = 300let cans = can.getContext('2d')cans.rotate(-20 * Math.PI / 180) // 水印旋转角度cans.font = '18px Vedana'cans.fillStyle = '#666666'cans.textAlign = 'left'cans.textBaseline = 'top'cans.fillText(str1, 0, 40) // 水印在画布的位置x,y轴cans.fillText(str2, 90, 230)let div = document.createElement('div')div.id = iddiv.style.pointerEvents = 'none'div.style.top = '0px'div.style.left = '0px'div.style.opacity = '0.1'div.style.position = 'fixed'div.style.zIndex = '100000'div.style.width = document.documentElement.clientWidth + 'px'div.style.height = document.documentElement.clientHeight + 'px'div.style.background = 'url(' + can.toDataURL('image/png') + ') left repeat'document.body.appendChild(div)return id
}// 添加水印方法
export const setWaterMark = (str1, str2) => {let id = setWatermark(str1, str2)if (document.getElementById(id) === null) {id = setWatermark(str1, str2)}
}// 移除水印方法
export const removeWatermark = () => {let id = '1.23452384164.123412415'if (document.getElementById(id) !== null) {document.body.removeChild(document.getElementById(id))}
}
2.在vue页面里直接引入使用
import { removeWatermark, setWaterMark } from '@/utils/watermark'
mounted () {// 添加水印setWaterMark('宋江','及时雨')
},
beforeDestroy () {removeWatermark()
}
3.最后效果