vue2实现水印
Vue2 实现水印的方法
使用 canvas 生成水印
在 Vue2 中可以通过 canvas 动态生成水印背景图,并将其设置为页面或指定元素的背景。
// 在 methods 中定义生成水印的方法
generateWatermark(text, options = {}) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 设置 canvas 尺寸
canvas.width = options.width || 300
canvas.height = options.height || 200
// 设置水印样式
ctx.font = options.font || '16px Arial'
ctx.fillStyle = options.color || 'rgba(180, 180, 180, 0.3)'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
// 旋转文字
ctx.translate(canvas.width / 2, canvas.height / 2)
ctx.rotate(options.rotate || -20 * Math.PI / 180)
// 绘制水印文字
ctx.fillText(text, 0, 0)
return canvas.toDataURL('image/png')
}
将水印应用到元素
在 mounted 钩子中调用生成水印的方法,并将其设置为背景:
mounted() {
const watermark = this.generateWatermark('保密资料', {
width: 200,
height: 150,
color: 'rgba(150, 150, 150, 0.2)'
})
// 应用到整个页面
document.body.style.backgroundImage = `url(${watermark})`
document.body.style.backgroundRepeat = 'repeat'
// 或者应用到特定元素
// this.$refs.watermarkElement.style.backgroundImage = `url(${watermark})`
}
防止水印被删除
为了防止用户通过开发者工具删除水印,可以添加 MutationObserver 监听 DOM 变化:
protectWatermark() {
const targetNode = document.body
const config = { attributes: true, childList: true, subtree: true }
const callback = function(mutationsList) {
for(let mutation of mutationsList) {
if (mutation.type === 'attributes' &&
mutation.attributeName === 'style') {
targetNode.style.backgroundImage = `url(${watermark})`
targetNode.style.backgroundRepeat = 'repeat'
}
}
}
const observer = new MutationObserver(callback)
observer.observe(targetNode, config)
}
作为指令实现
可以封装为 Vue 指令,方便全局使用:
// 注册全局指令
Vue.directive('watermark', {
bind(el, binding) {
const text = binding.value.text || '水印'
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = 200
canvas.height = 150
ctx.font = '16px Arial'
ctx.fillStyle = 'rgba(180, 180, 180, 0.3)'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.rotate(-20 * Math.PI / 180)
ctx.fillText(text, 100, 75)
el.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`
el.style.backgroundRepeat = 'repeat'
}
})
使用方式:
<div v-watermark="{ text: '内部资料' }"></div>
注意事项
- 水印颜色建议使用半透明效果,避免影响内容阅读
- 旋转角度可以增加去除水印的难度
- 对于重要场景,建议配合后端也添加水印
- 在移动端需要注意 canvas 的兼容性问题
- 水印密度可以根据需要调整 canvas 尺寸和重复频率
以上方法可以根据实际需求进行调整,例如增加多行水印、动态水印内容等功能。







