水印图例
![](https://i-blog.csdnimg.cn/direct/df8e14347ea6422b88189d12ccf04f89.png)
1.新建Watermark.js 文件
const watermark = {}
const setWatermark = (text, sourceBody) => {
const id =
Math.random() * 10000 +
'-' +
Math.random() * 10000 +
'/' +
Math.random() * 10000
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
const can = document.createElement('canvas')
can.width = 200 // 设置水印之间的左右间距
can.height = 150 // 设置水印之间的上下间距
const cans = can.getContext('2d')
cans.rotate((-20 * Math.PI) / 180)
cans.font = '15px Vedana'
cans.fillStyle = 'rgba(0, 0, 0, .3)' //水印颜色
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(text, can.width / 20, can.height)
const wateDiv = document.createElement('div')
wateDiv.id = id
wateDiv.className = 'watermarkClass'
wateDiv.style.pointerEvents = 'none'
wateDiv.style.background =
'url(' + can.toDataURL('image/png') + ') left top repeat'
if (sourceBody) {
wateDiv.style.width = '100%'
wateDiv.style.height = '100%'
sourceBody.appendChild(wateDiv)
} else {
wateDiv.style.top = '3px'
wateDiv.style.left = '0px'
wateDiv.style.position = 'fixed'
wateDiv.style.zIndex = '100000'
wateDiv.style.width = document.documentElement.clientWidth + 'px'
wateDiv.style.height = document.documentElement.clientHeight + 'px'
document.body.appendChild(wateDiv)
}
return id
}
/**
* 该方法只允许调用一次
* @param:
* @text == 水印内容
* @sourceBody == 水印添加的位置,不传就是body
* */
watermark.set = (text, sourceBody) => {
const domArr = Array.from(document.getElementsByClassName('watermarkClass'))
for (let i = 0; i < domArr.length; i++) {
const element = domArr[i]
// element.parentNode.removeChild(element);
element.remove()
}
if (text === '') {
return
}
setWatermark(text, sourceBody)
// let id = setWatermark(text, sourceBody);
// setInterval(() => {
// if (document.getElementById(id) === null) {
// id = setWatermark(text, sourceBody);
// }
// }, 2000);
// window.onresize = () => {
// setWatermark(text, sourceBody);
// };
}
export default watermark
2. 在vue 文件使用
<script>
import Watermark from './Watermark' //引入水印文件
export default {
name: 'app',
mounted () {
Watermark.set(水印名称)// 添加水印名称
}
}
</script>
<style>
</style>