当前位置:网站首页>Use canvas to add text watermark to the page

Use canvas to add text watermark to the page

2022-06-11 18:50:00 Summer

Reference resources :

vue Add watermark to the page - Simple books

Code : I made some changes according to our needs

let watermark = {};

let setWatermark = (str, targetDom) => {
  let id = 'watermark';

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id));
  }

  let can = document.createElement("canvas");
  can.width = 200;
  can.height = 100;

  let cans = can.getContext("2d");
  cans.rotate((-20 * Math.PI) / 180);
  cans.font = "15px Vedana";
  cans.fillStyle = "rgba(0, 0, 0, 0.30)";
  cans.textAlign = "left";
  cans.textBaseline = "Middle";
  cans.fillText(str, can.width / 20, can.height);

  let div = document.createElement("div");
  div.id = id;
  div.style.pointerEvents = "none";
  div.style.top = targetDom.offsetTop + "px";
  div.style.left = targetDom.offsetLeft + "px";
  div.style.position = "fixed";
  div.style.zIndex = "100000";
  div.style.width = targetDom.clientWidth + "px";
  div.style.height = targetDom.clientHeight + "px";
  div.style.background =
    "url(" + can.toDataURL("image/png") + ") left top repeat";
  document.body.appendChild(div);
  return id;
};

//  If the watermark exists   Show watermark   If it doesn't exist   Show after creation  
// targetDom  Is the element to be covered by the watermark 
watermark.set = (str, targetDom) => {
  if (document.getElementById('watermark')) {
    document.getElementById('watermark').style.display = 'block'
  } else {
    let id = setWatermark(str, targetDom);
    let timer = setInterval(() => {
      if (document.getElementById(id) === null) {
        id = setWatermark(str, targetDom);
      } else {
        clearInterval(timer)
      }
    }, 2000);
    window.onresize = () => {
      setWatermark(str, targetDom);
    };
  }
};
// Show watermarks when switching pages   Because the project component is keep-alive Of   So in beforeRouteEnter Adjust this when 
watermark.show = () => {
  if (document.getElementById('watermark')) {
    document.getElementById('watermark').style.display = 'block'
  }

}
//beforeRouteLeave You may need to hide the watermark when switching other pages 
watermark.hide = () => {
  document.getElementById('watermark').style.display = 'none'
}
export default watermark

原网站

版权声明
本文为[Summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111847322413.html