canvas电子签(pc+mobile)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="signatureCanvas" style="border:1px solid #ccc;"></canvas>
  <button id="saveButton">保存签名</button>
  <script>
    const canvas = document.getElementById('signatureCanvas');
    const saveButton = document.getElementById('saveButton');
    const ctx = canvas.getContext('2d');
    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;

    // 设置 Canvas 的宽高
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    function startDrawing(e) {
      isDrawing = true;

      // 根据设备类型获取坐标
      const coordinates = getCoordinates(e);
      [lastX, lastY] = coordinates;
    }

    function draw(e) {
      if (!isDrawing) return;

      // 根据设备类型获取坐标
      const coordinates = getCoordinates(e);
      const [clientX, clientY] = coordinates;

      ctx.lineWidth = 2;
      ctx.lineCap = 'round';
      ctx.strokeStyle = 'black';

      ctx.beginPath();
      ctx.moveTo(lastX, lastY);
      ctx.lineTo(clientX, clientY);
      ctx.stroke();

      [lastX, lastY] = coordinates;
    }

    function stopDrawing() {
      isDrawing = false;
    }

    function saveSignature() {
      const signatureData = canvas.toDataURL();

      console.log(signatureData);
    }

    function getCoordinates(e) {
      let clientX, clientY;

      // 检测设备类型
      if (e.touches) {
        // 触摸设备,取第一个触摸点的坐标
        clientX = e.touches[0].clientX;
        clientY = e.touches[0].clientY;
      } else {
        // 鼠标事件
        clientX = e.clientX;
        clientY = e.clientY;
      }

      return [clientX, clientY];
    }

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);

    canvas.addEventListener('touchstart', startDrawing);
    canvas.addEventListener('touchmove', draw);
    canvas.addEventListener('touchend', stopDrawing);

    saveButton.addEventListener('click', saveSignature);
  </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值