采用canvas绘制图片,observe监听页面元素改变重新添加。
实现一个这种水印:
<template>
<div id="water_mater" ref="Watermakr"></div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
createWaterMark() {
const { loginIp = '', userName = '' } = this.userProfile
const angle = -22
const txt = `水印内容`
const canvas = document.createElement('canvas')
canvas.width = 500
canvas.height = 240
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, 500, 240)
ctx.fillStyle = '#000'
ctx.globalAlpha = 0.3
ctx.font = `14px serif`
ctx.rotate((Math.PI / 180) * angle)
ctx.fillText(txt, 90, 150)
return canvas.toDataURL()
},
watchRemove() {
const Watermakr = this.$refs.Watermakr
// 观察器的配置(需要观察什么变动)
const config = { attributes: true, childList: true, subtree: true }
// 当观察到变动时执行的回调函数
const callback = function(mutationsList, observer) {
// 获取父组件 ID
const parentDom = document.getElementById('mainBox')
// Use traditional 'for loops' for IE 11
for (const mutation of mutationsList) {
mutation.removedNodes.forEach(function(item) {
if (item === Watermakr) {
if (!document.getElementById('water_mater')) {
parentDom.appendChild(Watermakr)
}
}
})
}
}
// 监听元素
const targetNode = document.getElementById('mainBox')
// 创建一个观察器实例并传入回调函数
const observer = new MutationObserver(callback)
// 以上述配置开始观察目标节点
observer.observe(targetNode, config)
}
},
mounted() {
const Watermakr = this.$refs.Watermakr
Watermakr.style.background= `url(${this.createWaterMark()}) center top`
this.watchRemove()
}
}
</script>
<style lang="scss" scoped>
#water_mater {
width: 100%;
height: 100%;
position: absolute; // 父组件要用相对定位 或者直接子组件固定定位,看需求
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
pointer-events: none;
background-repeat: repeat;
z-index: 10;
}
</style>
更多请参考:
从破解某设计网站谈前端水印(详细教程)