签名、刮刮卡示例

374#1f8c38b0

1. 刮刮卡

ts 复制代码
(() => {
  canvas = document.createElement('canvas');
  canvas.width = 700;
  canvas.height = 400;
  document.body.appendChild(canvas);
  
  const cxt = canvas.getContext('2d');

  canvas.style.background = 'url(https://imzbf.github.io/md-editor-v3/imgs/preview-light.png)';
  canvas.style.backgroundSize = '100% 100%';

  // 绘制灰色蒙板
  cxt.fillStyle = 'gray';
  cxt.fillRect(0, 0, canvas.width, canvas.height);

  // 设置为之后绘图不显示图,并且擦掉之前的这部分图
  cxt.globalCompositeOperation = 'destination-out';

  const state = {
    mousedown: false,
  };

  document.addEventListener('mousedown', () => {
    state.mousedown = true;
  });

  document.addEventListener('mouseup', () => {
    state.mousedown = false;
  });

  document.addEventListener('mousemove', (e) => {
    if (state.mousedown) {
      cxt.beginPath();
      // x,y,半径,圆开始弧度,结束弧度(1倍PI是半圆)
      cxt.arc(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, 20, 0, 2 * Math.PI);
      cxt.fill();
      cxt.closePath();
    }
  });
})();

2. 签名

js 复制代码
(() => {
  canvas = document.createElement('canvas');
  canvas.width = 700;
  canvas.height = 400;
  document.body.appendChild(canvas);
  
  const cxt = canvas.getContext('2d');

  // 绘制灰色蒙板
  cxt.fillStyle = 'gray';
  cxt.fillRect(0, 0, canvas.width, canvas.height);

  document.addEventListener('mousedown', (ed) => {
    cxt.moveTo(ed.pageX - canvas.offsetLeft, ed.pageY - canvas.offsetTop);

    document.onmousemove = (e) => {
      cxt.lineTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
      cxt.strokeStyle = 'red';
      cxt.stroke();
    };
  });

  document.addEventListener('mouseup', () => {
    document.onmousemove = () => {};
  });
})();

参与本文讨论

请先登录 GitHub 后留言

0/500

本文留言

0

这篇文章还没有留言,来写第一条吧。

1 / 1