vue实现水印组件
Vue 水印组件实现方法
基础实现
创建一个名为Watermark.vue的组件文件,使用Canvas绘制水印:

<template>
<div class="watermark-container" ref="container"></div>
</template>
<script>
export default {
props: {
text: {
type: String,
default: 'Watermark'
},
fontSize: {
type: Number,
default: 16
},
color: {
type: String,
default: 'rgba(0, 0, 0, 0.1)'
},
angle: {
type: Number,
default: -20
}
},
mounted() {
this.drawWatermark()
},
methods: {
drawWatermark() {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const width = 200
const height = 100
canvas.width = width
canvas.height = height
ctx.font = `${this.fontSize}px Arial`
ctx.fillStyle = this.color
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.translate(width / 2, height / 2)
ctx.rotate(this.angle * Math.PI / 180)
ctx.fillText(this.text, 0, 0)
const dataURL = canvas.toDataURL('image/png')
this.$refs.container.style.backgroundImage = `url(${dataURL})`
}
}
}
</script>
<style>
.watermark-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 9999;
background-repeat: repeat;
}
</style>
动态更新水印
添加响应式更新功能,当props变化时重新绘制水印:

watch: {
text() {
this.drawWatermark()
},
fontSize() {
this.drawWatermark()
},
color() {
this.drawWatermark()
},
angle() {
this.drawWatermark()
}
}
防止水印被删除
添加MutationObserver防止DOM被篡改:
mounted() {
this.drawWatermark()
this.initMutationObserver()
},
methods: {
initMutationObserver() {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.removedNodes.length > 0) {
mutation.removedNodes.forEach((node) => {
if (node === this.$el) {
document.body.appendChild(this.$el)
}
})
}
})
})
observer.observe(document.body, {
childList: true,
subtree: true
})
}
}
使用示例
在父组件中使用水印组件:
<template>
<div>
<Watermark
text="Confidential"
:fontSize="20"
color="rgba(0, 0, 0, 0.15)"
:angle="-15"
/>
<!-- 页面其他内容 -->
</div>
</template>
<script>
import Watermark from './Watermark.vue'
export default {
components: {
Watermark
}
}
</script>
优化建议
- 对于大量重复水印,可以考虑使用CSS repeating-linear-gradient替代Canvas绘制
- 添加水印密度控制参数,调整水印之间的间距
- 考虑支持多行文本水印
- 添加水印位置控制,可以固定在页面四角或中心
- 对于动态内容页面,考虑使用IntersectionObserver检测可视区域变化






