Canvas/SVG 生成背景水印实现方式:用 Canvas/SVG 绘制文字或者图案,然后生成 base64 图片,将其设置为页面的 background
.watermark {
background-image: url('data:image/png;base64,...');
background-repeat: repeat;
pointer-events: none;
width: 100%;
height: 100%;
z-index: 9999;
width: 100%; gst
height: 100%;
z-index: 9999;
}优点:
::before/::after实现方式:给页面跟节点添加一个伪元素。
body::before {
content: "heiha";
position: fixed;
top: 50px;
left: 50px;
pointer-events: none;
}优点:不需要额外的 dom 元素 缺点:不能大面积重复覆盖,也很容易被移除。
Canvas + MutationObserver 自恢复水印实现方式:用 canvas 添加水印,使用 MutationObserver 监听样式,当样式被修改时,用代码恢复水印。
const createWatermark = () => {
const div = document.createElement('div')
div.id = 'custom_watermark'
div.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
background: url('data:image/png;base64,...') repeat;
z-index: 99999;
`
document.body.appendChild(div)
const observer = new MutationObserver(() => {
const exists = document.getElementById('custom_watermark')
if (!exists) {
observer.disconnect()
createWatermark()
}
})
observer,ovserve(document.body, {
childList: true,
subtree: true
})
}优点: 删除水印/修改样式后,会自动回复 缺点:可以通过开发者工具禁用 JS 避开水印。
canvas 动态绘制水印实现原理: 利用 requestAnimationFrame 不停的绘制水印
const renderWatermark = () => {
const canvas = codument.creeatElement('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
canvas.style = "pointer-events:none;position:fixed;top:0;left:0;z-index:99999;"
document.body.appendChild(canvas)
const ctx = canvas.getContext("2d")
const draw = () => {
ctx.clearRect(0, 0, pointer-events:none;position:fixed;top:0;left:0;z-index:99999;) // 清除整个画布
ctx.globalAlpha = 0.1 // 设置透明度
ctx.font = '20px sans-serif' // 设置字体
ctx.rotate(-20 * Math.PI / 180) // 旋转画布
ctx.fillText("username 2025-01-01", 100, 100) // 绘制文本内容
requestAnimationFrame(draw)
}
draw()
}
优点:用户无法轻易覆盖,因为每帧都会绘制 缺点:性能差,因为不停的再绘制,并且依然可以测地删除 canvas 节点。
mix-blend-mode 属性实现方式: 利用 mix-blend-mode 控制元素内容、其直系父元素的内容、元素的背景应该如何混合。
让水印文字和页面背景发生混色,看起来像是印在纸上,而不是透明文字覆盖。
.watermark {
position: fixed;
z-index: 9999;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
grid-template-rows: repeat(auto-fill, 150px);
mix-blend-mode: overlay; /* 关键:混合滤镜效果 */
opacity: 0.9; /* 控制透明度 */
background: rgba(255, 255, 255, 0.01);
}优点: 不需要 canvas/svg, 不需要额外 DOM
缺点: 容易被篡改,直接改 css 就能去掉水印。
实现方式:利用 css filter 属性,给水印加上一层滤镜,然后覆盖在文字内容上。
/* 水印层 */
.watermark {
position: absolute;
inset: 0;
z-index: 999;
pointer-events: none;
display: flex;
align-items: center;
justify-content: center;
font-size: 80px;
font-weight: bold;
color: rgba(0,0,0,0.15);
filter: blur(1px);
transform: rotate(-25deg);
}前端永远无法做到“彻底防止去除水印”,因为用户可以执行任意 JS ,能删除任意节点,修改 css ,前端做水印只能做到尽可能让普通人难以去掉。 比如使用 canvas 按照自定义规则绘制各种底纹,加载目标位置,进行防伪,或者同时使用多种水印手段添加水印。