js 实现水印功能
基础水印实现
使用Canvas绘制文本水印并覆盖在页面上:
function createWatermark(text) {
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
const ctx = canvas.getContext('2d');
ctx.font = '16px Arial';
ctx.fillStyle = 'rgba(200, 200, 200, 0.5)';
ctx.rotate(-0.2);
ctx.fillText(text, 20, 60);
return canvas.toDataURL();
}
const watermarkDiv = document.createElement('div');
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.top = '0';
watermarkDiv.style.left = '0';
watermarkDiv.style.width = '100%';
watermarkDiv.style.height = '100%';
watermarkDiv.style.pointerEvents = 'none';
watermarkDiv.style.backgroundImage = `url(${createWatermark('机密文件')})`;
watermarkDiv.style.backgroundRepeat = 'repeat';
document.body.appendChild(watermarkDiv);
防篡改水印方案
通过MutationObserver监听DOM变化,防止水印被删除:

const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (!document.body.contains(watermarkDiv)) {
document.body.appendChild(watermarkDiv);
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
动态水印方案
结合用户信息生成个性化水印:

function generateDynamicWatermark(userInfo) {
const text = `${userInfo.name} ${userInfo.id} ${new Date().toLocaleString()}`;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
ctx.font = '14px Arial';
ctx.fillStyle = 'rgba(100, 100, 100, 0.1)';
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 5; j++) {
ctx.save();
ctx.translate(i * 150, j * 100);
ctx.rotate(-0.2);
ctx.fillText(text, 0, 50);
ctx.restore();
}
}
return canvas.toDataURL();
}
SVG水印方案
使用SVG实现高清水印:
function createSvgWatermark(text) {
const svg = `
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<text x="50" y="100"
font-family="Arial"
font-size="20"
fill="rgba(150,150,150,0.5)"
transform="rotate(-15)">
${text}
</text>
</svg>`;
return `data:image/svg+xml;base64,${btoa(svg)}`;
}
水印性能优化
对于大量水印的情况,使用CSS重复背景替代多个DOM元素:
const watermarkStyle = document.createElement('style');
watermarkStyle.innerHTML = `
body {
position: relative;
}
body::after {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
background-image: url(${createWatermark('禁止复制')});
background-repeat: repeat;
opacity: 0.5;
z-index: 9999;
}
`;
document.head.appendChild(watermarkStyle);






