最近vue项目需要做一个水印功能,通过网上多种方式的的对比选择了下面的方式:
在utils.js方法封装如下:
// 前端水印
(function() {
function waterMark({
container = document.body,
width = "150px",
height = "100px",
textAlign = "center",
textBaseline = "top",
font = "14px Microsoft Yahei",
fillStyle = "rgba(0,0,0,0.07)",
text = "测试水印",
rotate = "-30",
zIndex = 1000
} = {}) {
const args = arguments[0];
const canvas = document.createElement("canvas");
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
const ctx = canvas.getContext("2d");
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.font = font;
(ctx.fillStyle = fillStyle), ctx.rotate((Math.PI / 180) * rotate);
ctx.fillText(text, parseFloat(width) * 0.2, parseFloat(height) * 0.9);
const base64Url = canvas.toDataURL();
const __wm = document.querySelector(".__wm");
const watermarkDiv = __wm || document.createElement("div");
const styleStr = `
position:absolute;
top:120px;
left:200px;
width:100%;
height:100%;
z-index:${zIndex};
pointer-events:none;
background-repeat:repeat;
background-image:url('${base64Url}')
`;
watermarkDiv.setAttribute("style", styleStr);
watermarkDiv.classList.add("__wm");
if (!__wm) {
container.style.position = "relative";
container.insertBefore(watermarkDiv, container.firstChild);
}
const MutationObserver =
window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver) {
let mo = new MutationObserver(() => {
const __wm = document.querySelector(".__wm");
if ((__wm && __wm.getAttribute("style") !== styleStr) || !__wm) {
mo.disconnect();
mo = null;
waterMark(JSON.parse(JSON.stringify(args)));
}
});
mo.observe(container, {
attributes: true,
subtree: true,
childList: true
});
}
}
if (typeof module != "undefined" && module.exports) {
module.exports = waterMark;
} else if (typeof define == "function" && define.amd) {
define(() => {
return waterMark;
});
} else {
window.waterMark = waterMark; //配置为window变量
}
})();
用法如下:
window.waterMark({ text: "水印内容" });