最近vue項(xiàng)目需要做一個(gè)水印功能,通過網(wǎng)上多種方式的的對比選擇了下面的方式:
在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: "水印內(nèi)容" });