//僅學習記錄使用
頁面使用
import watermark from '@/utils/watermark.js'
export default {
name: 'App',
data() {
return {
str: {
name: this.$store.getters.userName, //
phone: (this.$store.getters.mobile || '').substr(-4),
company: '公司'
}
}
},
mounted() {
watermark.set(this.str)
},
created() {
},
updated() {
console.log('更新了', '更新了')
},
destroyed() {
watermark.out(this.str)
}
}
js核心代碼
const id = '1.23452384164.123412416'
const setWatermark = (str) => {
const existingWatermark = document.getElementById(id)
if (existingWatermark !== null) {
document.body.removeChild(existingWatermark)
}
// 創(chuàng)建一個畫布
const canvas = document.createElement('canvas')
// 設置畫布的長寬
canvas.width = 220
canvas.height = 220
const context = canvas.getContext('2d')
// 控制文字的旋轉角度和上下位置
context.rotate(-20 * Math.PI / 180)
context.translate(-50, 20)
// 文字顏色
context.fillStyle = 'rgba(0,0,0,0.07)'
context.textBaseline = 'Middle'
context.font = '14px Arial,"PingFang SC","Microsoft YaHei","Helvetica Neue",Helvetica,"Hiragino Sans GB",sans-serif'
// 在畫布上繪制填色的文本(輸出的文本隙券,開始繪制文本的X坐標位置,開始繪制文本的Y坐標位置)
const text = `${str.name} ${str.phone}`
context.fillText(text, canvas.width / 4, canvas.height / 2.5)
context.fillText(text, canvas.width / 3, canvas.height)
//
const div = document.createElement('div')
div.id = id
div.style.pointerEvents = 'none'
div.style.top = '0vw'
div.style.left = '0vw'
div.style.position = 'fixed'
div.style.zIndex = '99'
div.style.display = 'block'
div.style.width = '100vw'
div.style.height = '100vw'
div.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat'
document.body.appendChild(div)
}
let observer = null
let timer = null
// 添加水印該方法只允許調(diào)用一次
const watermark = {
set: (str) => {
setWatermark(str)
clearInterval(timer)
timer = setInterval(() => {
if (!document.getElementById(id)) setWatermark(str)
}, 500)
window.onresize = () => {
setWatermark(str)
}
if (!observer) {
observer = new MutationObserver((mutationsList) => {
mutationsList.forEach(mutation => {
if (mutation.type === 'childList' || mutation.type === 'attributes') {
const target = mutation.target
if (target.id === id) {
setWatermark(str) // 重新添加水印
}
}
})
})
const body = document.getElementsByTagName('body')[0]
// 監(jiān)聽body節(jié)點
observer.observe(body, {
childList: true,
attributes: true,
characterData: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
})
}
},
out: () => {
// 去除水印
const watermarkElement = document.getElementById(id)
if (watermarkElement !== null) {
watermarkElement.style.display = 'none'
observer && observer.disconnect()
}
clearInterval(timer)
}
}
export default watermark