前端页面水印

352 阅读1分钟

前端真是个大杂烩,有些需求又不能反驳,后端不做水印处理(官方吐槽:因为后端要走了,很是懈怠。),故前端来做,那就做吧。毕竟我们要励志做一个全名boy。奉行拿来主义,小伙伴们,下面的直接引用就可以使用了

 export function __waterDocument({
  container = document.body,
  width = '200px',
  height = '150px',
  textAlign = 'center',
  textBaseline = 'middle',
  font = "10px Microsoft Yahei",
  fillStyle = 'rgba(220,20,60, 0.2)',
  // fillStyle = 'rgba(230, 230, 230, 0.2)',
  content = '保密水印',
  rotate = 45,
  zIndex = 1000
} = {}) {
  const args = arguments[0];
  const canvas = document.createElement('canvas');
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  const ctx = canvas.getContext("2d");
  if (ctx === null) {
    console.error("this browser is not support canvas.");
    return;
  }
  ctx.textAlign = textAlign; // 文本对齐设置。可能的值:start,end,left,right或center。默认值为start。
  ctx.textBaseline = textBaseline; // 基线对齐设置。可能的值:top、hanging、middle、alphabetic、ideographic、bottom。默认值为alphabetic
  ctx.font = font; // 绘制文本时使用的当前文本样式。此字符串使用与CSS font属性相同的语法。默认字体为 10px sans-serif。
  ctx.fillStyle = fillStyle;
  ctx.rotate((Math.PI / 180) * rotate);
  // ctx.rotate(`${rotate}deg`);
  // ctx.fillText(content, 0, 0);
  ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2);
  const base64Url = canvas.toDataURL();
  const __wm = document.querySelector('.__wm');
  const watermarkDiv = __wm || document.createElement("div");
  const styleStr = `
      position:absolute;
      top:0;
      left:0;
      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(function () {
      const __wm = document.querySelector('.__wm');
      // 只在__wm元素变动才重新调用 __canvasWM
      if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) {
        // 避免一直触发
        mo.disconnect();
        mo = null;
        /*eslint no-undef-init: "error"*/
        __canvasWM(JSON.parse(JSON.stringify(args)));
      }
    });
    mo.observe(container, {
      attributes: true,
      subtree: true,
      childList: true
    });
  }
}
import { __waterDocument} from '../utils/watermark_canvas';
__waterDocument({content: radData.doctorName}); // 看你们在业务里哪里需要,就在哪里用,我这因为在页面出来时使用。我使用的是vue,所以就在mounted生命周期里调用了,
结束语:关注我,少走弯路!

image.png