在常见的后台管理系统项目开发中,为了防止信息泄露或者对知识产权的保护,常常需要在页面添加水印。水印内容一般是个人信息或者版权标识等。最近项目中就遇到需要添加水印的问题,尽管已经开发完了,这里还是想记录一下解决过程。
页面添加动态水印的几种方法
1、用 js 动态创建水印节点,平铺在页面最顶层同时设置水印节点属性 pointerEvents 为 none。该方法兼容性好 但性能较差,这里就不展开了。
2、通过在 canvas 上绘制好水印,以 base64 格式输出图片用作水印层的背景图
3、通过 svg 绘制水印, base64 格式输出图片用作水印层的背景图
canvas 绘制水印
interface params {
container?: HTMLElement;
content?: string;
width?: string;
height?: string;
font?: string;
textAlign?: CanvasTextAlign;
textBaseline?: CanvasTextBaseline;
rotate?: number;
color?: string;
zIndex?: number;
}
const createWatermark = ({
content = "水印内容",
container = document.body,
width = "200px",
height = "150px",
font = "20px Microsoft YaHei",
textAlign = "center",
textBaseline = "middle",
rotate = -15,
color = "rgba(144,147,153,0.1)",
zIndex = 9999,
}: params) => {
// 创建canvas
const canvas = document.createElement("canvas");
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
const ctx = canvas.getContext("2d");
if (!ctx) return;
// 绘制水印
ctx.font = font;
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.fillStyle = color;
ctx.rotate((Math.PI / 180) * rotate);
ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2);
// 输出水印图片地址
const base64Url = canvas.toDataURL();
const watermark = document.createElement("div");
watermark.setAttribute(
"style",
`position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:${zIndex};
pointer-events:none;
background-image:url('${base64Url}')` // 默认平铺重复显示
);
container.style.position = "relative";
container.insertBefore(watermark, container.firstChild);
};
export default createWatermark;
svg 绘制水印
interface params {
container?: HTMLElement;
content?: string;
width?: string;
height?: string;
fontSize?: string;
rotate?: number;
opacity?: string;
color?: string;
zIndex?: number;
}
const createWatermark = ({
content = "水印内容",
container = document.body,
width = "200px",
height = "150px",
fontSize = "16px",
opacity = "0.3",
rotate = -14,
color = "#000",
zIndex = 9999,
}: params) => {
// 创建水印svg
const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
<text x="50%" y="50%" dy="12px"
text-anchor="middle"
stroke="${color}"
stroke-width="1"
stroke-opacity="${opacity}"
fill="none"
transform="rotate(${rotate}, ${parseFloat(width) / 2}, ${
parseFloat(height) / 2
})"
style="font-size: ${fontSize};">
${content}
</text>
</svg>`;
// 利用window.btoa创建base64编码的字符串
const base64Url = `data:image/svg+xml;base64,${window.btoa(
unescape(encodeURIComponent(svgStr))
)}`;
const watermark = document.createElement("div");
watermark.setAttribute(
"style",
`position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:${zIndex};
pointer-events:none;
background-image:url('${base64Url}')`
);
container.style.position = "relative";
container.insertBefore(watermark, container.firstChild);
};
export default createWatermark;
页面水印防删除解决办法
用以上方式创建的水印很容易在页面上通过删除水印节点的方式避开水印信息,所以我们应该添加措施防止用户删除或修改水印节点,这里推荐使用MutationObserver,它提供了监视对 DOM 树所做更改的能力
加入 MutationObserver 监听后最终代码如下
interface params {
container?: HTMLElement;
content?: string;
width?: string;
height?: string;
font?: string;
textAlign?: CanvasTextAlign;
textBaseline?: CanvasTextBaseline;
rotate?: number;
color?: string;
zIndex?: number;
}
function createWatermark({
content = "水印内容",
container = document.body,
width = "200px",
height = "150px",
font = "20px Microsoft YaHei",
textAlign = "center",
textBaseline = "middle",
rotate = -15,
color = "rgba(144,147,153,0.1)",
zIndex = 9999,
}: params) {
const args = arguments[0];
// 创建canvas
const canvas = document.createElement("canvas");
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
const ctx = canvas.getContext("2d");
if (!ctx) return;
// 绘制水印
ctx.font = font;
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.fillStyle = color;
ctx.rotate((Math.PI / 180) * rotate);
ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2);
// 输出水印图片地址
const base64Url = canvas.toDataURL();
const watermarkNode = document.querySelector(".watermarkNode");
const watermark = watermarkNode || document.createElement("div");
const styleStr = `position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:${zIndex};
pointer-events:none;
background-image:url('${base64Url}')`;
watermark.setAttribute("style", styleStr);
watermark.classList.add("watermarkNode");
if (!watermarkNode) {
// 只有当watermarkNode不存在时才插入水印节点
container.style.position = "relative";
container.insertBefore(watermark, container.firstChild);
}
if (MutationObserver) {
let MOInstance = new MutationObserver(function () {
const watermarkNode = document.querySelector(".watermarkNode");
// 只在watermarkNode元素变动才重新调用 createWatermark
if (
!watermarkNode ||
(watermarkNode && watermarkNode.getAttribute("style") !== styleStr)
) {
// 避免一直触发
MOInstance.disconnect();
// 重新创建水印
createWatermark(JSON.parse(JSON.stringify(args)));
}
});
MOInstance.observe(container, {
attributes: true,
subtree: true,
childList: true,
});
}
}
export default createWatermark;
至此 动态水印添加完成,且修改或删除水印节点依然无法去掉水印
参考文章: