评论

页面添加动态水印

为了防止信息泄露或者对知识产权的保护,常常需要在页面添加水印

页面添加动态水印的三种方法

  1. 使用 js 动态创建水印节点,平铺在页面最顶层同时设置水印节点属性 pointerEvents 为 none。兼容性可以但是性能较差,详细例子可参考用 JavaScript 实现网页动态水印
  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;

到此 动态水印添加完成,且修改或删除水印节点依然无法去掉水印

最后一次编辑于  2024-01-19  
点赞 1
收藏
评论
登录 后发表内容