页面水印定义和使用

水印使用:

1、引入定义的watermark.js文件

let watermark = new Watermark({
    contend: "水印内容",
    fontSize: 16,
    ……
});

2、离开页面要主动销毁

watermark  && watermark.removeWatermark();

 

水印定义,定义watermark.js文件,内容如下

export default class Watermark {
  constructor({
    fontSize = 18, width = 300, height = 300, opacity = 100, content = ""
  }) {
    this.fontSize = fontSize;
    this.width = width;
    this.height = height;
    this.opacity = opacity;
    this.content = content;
    this.divId = "watermark";
  }

  // 绘制水印
  draw() {
    if (document.getElementById(this.divId) !== null) {
      document.body.removeChild(document.getElementById(this.divId));
    }

    const canvas = document.createElement("canvas");
    // 设置canvas画布大小
    canvas.width = this.width;
    canvas.height = this.height;

    const ctx = canvas.getContext("2d");
    ctx.rotate(-(20 * Math.PI) / 180); // 水印旋转角度
    ctx.font = `${this.fontSize}px Vedana`;
    ctx.fillStyle = "#666666";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    this.content.split("/n").forEach((item, index) => {
      ctx.fillText(item, canvas.width / 2, canvas.height / 2 + (index * this.fontSize + 10)); // 水印在画布的位置x,y轴
    });
    const div = document.createElement("div");
    div.id = this.divId;
    div.style.pointerEvents = "none";
    div.style.top = "40px";
    div.style.left = "0px";
    div.style.opacity = this.opacity / 100;
    div.style.position = "fixed";
    div.style.zIndex = "100000";
    div.style.width = `${document.documentElement.clientWidth}px`;
    div.style.height = `${document.documentElement.clientHeight}px`;
    div.style.background = `url(${canvas.toDataURL("image/png")}) left top repeat`;
    document.body.appendChild(div);
  }

  // 初始化水印数据
  setOptions({
    fontSize = 18, width = 300, height = 300, opacity = 100, content = ""
  }) {
    this.fontSize = fontSize;
    this.width = width;
    this.height = height;
    this.opacity = opacity;
    this.content = content;
    this.draw();
  }

  // 绘制
  render() {
    this.draw();
    window.onresize = () => {
      this.draw();
    };
  }

  // 移除水印
  removeWatermark() {
    if (document.getElementById(this.divId) !== null) {
      document.body.removeChild(document.getElementById(this.divId));
    }
  }
}

 

posted on 2024-08-09 17:35  紫藤萝yu  阅读(43)  评论(0编辑  收藏  举报