canvas添加水印

Posted freeman_Tian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas添加水印相关的知识,希望对你有一定的参考价值。

// 动态尺寸
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");
}

以上是关于canvas添加水印的主要内容,如果未能解决你的问题,请参考以下文章

canvas添加水印

前端小程序——js+canvas 给图片添加水印

离线合成联想到的--canvas合成水印

小程序--------------处理canvas导出图片模糊问题-------------劉

Android给图片添加文字和水印

android图像处理系列之七--图片涂鸦,水印-图片叠加