关于canvas:canvas添加水印

7次阅读

共计 1483 个字符,预计需要花费 4 分钟才能阅读完成。

// 动静尺寸
const dynamicDateSize = function (size) {//return (document.body.offsetWidth / 375) * size;
    return (getClientW() / 375) * size
}
export function addWaterBack(text) {
  const width = window.screen.width || document.body.offsetWidth;
  const height = window.screen.height || document.body.clientHeight;
  let selector = document.querySelector("body");
  let section = document.createElement("section");
  const styleStr = `
        position: fixed;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        pointer-events: none;
        z-index: 199999999;`;
  section.setAttribute('style', styleStr);
  section.style.background = `url(${_canvasToimg(width, height, text)})`;
  //section.classList.add("warter-back");
  selector.appendChild(section);
  //selector.style.background = `url(${_canvasToimg(width, height, text)})`;
}

function _canvasToimg(width, height, text) {
  const width2 = width / 2;
  const height3 = height / 5;
  // 单个水印
  let sCanvas = document.createElement("canvas"); // 创立 canvas 标签
  sCanvas.width = width2; // 设置画布大小
  sCanvas.height = height3;

  let ctx = sCanvas.getContext("2d");

  ctx.fillStyle = "rgba(35,24,21,0.1)";
  const fontSize = Math.min(Number(CommonJs.dynamicDateSize(12)).toFixed(0) || 12, 24);
  ctx.font = `${fontSize}px Arial`;
  ctx.rotate((-25 * Math.PI) / 180);
  ctx.fillText(text, 0, height3 / 1.5);
  ctx.rotate((25 * Math.PI) / 180);

  // 大的 canvas
  let bCanvas = document.createElement("canvas");
  bCanvas.width = width;
  bCanvas.height = height;
  let ctx1 = bCanvas.getContext("2d");
  ctx1.clearRect(0, 0, width, height);
  let pat = ctx1.createPattern(sCanvas, "repeat"); // 在指定的方向上反复指定的元素
  ctx1.fillStyle = pat;
  ctx1.fillRect(0, 0, width, width);

  return sCanvas.toDataURL("image/png");
}
正文完
 0