キャンバスは署名の小さなデモを実現します

現在、Webページを使って署名するビジネスシーンは数多くありますが、私が使っているものの中では、銀行や携帯電話とのやり取りで電子署名を使用しています。実際、web ページに電子署名を実装するのは非常に簡単です. canvas タグは実装が非常に簡単で、さらに署名画像をエクスポートする機能は、数十行のコードで実現できます.

<body>
    <canvas></canvas>
    <div>
        <button onclick="cancel()">取消</button>
        <button onclick="save()">保存</button>
    </div>
</body>
<script>
    const canvas = document.querySelector('canvas');
    canvas.width = 500;
    canvas.height = 300;
    canvas.style.border = '1px solid #000';
    const ctx = canvas.getContext('2d');

    ctx.lineWidth = 3;//线宽
    ctx.strokeStyle = 'red';//线颜色
    ctx.lineCap = 'round';//线条的结束端点样式
    ctx.lineJoin = 'round';//两条线相交时,所创建的拐角类型

    const mobileStatus = (/Mobile|Android|iPhone/i.test(navigator.userAgent));

    const start = event => {
      const { offsetX, offsetY, pageX, pageY } = mobileStatus ? event.changedTouches[0] : event;
      ctx.beginPath();//起始一条路径,或重置当前路径
      ctx.moveTo(pageX, pageY);//把路径移动到画布中的指定点,不创建线条
      window.addEventListener(mobileStatus ? "touchmove" : "mousemove", draw);
    }

    const draw = event => {
      const { pageX, pageY } = mobileStatus ? event.changedTouches[0] : event;
      ctx.lineTo(pageX , pageY );//添加一个新点,然后在画布中创建从该点到最后指定点的线条
      ctx.stroke();//绘制已定义的路径
    }
    const cloaseDraw = () => {
      window.removeEventListener("mousemove", draw);
    }

    window.addEventListener(mobileStatus ? "touchstart" : "mousedown", start);
    window.addEventListener(mobileStatus ? "touchend" :"mouseup", cloaseDraw);

    const cancel = () => {
      ctx.clearRect(0, 0,500, 300);//在给定的矩形内清除指定的像素
    }

    const save = () => {
      canvas.toBlob(blob => {
          const date = Date.now().toString();
          const a = document.createElement('a');
          a.download = `${date}.png`;
          a.href = URL.createObjectURL(blob);
          a.click();
          a.remove();
      })
    }
</script>

toBlob は w3cschool では利用できません。MDN に詳細な紹介があります。モバイル端末との互換性は、実際には、タッチ イベントまたはマウス イベントのリッスンの違いです。

このファイルは、GitHub https://github.com/wade3po/demoCode からダウンロードすることもできます。

個人的なメモをコーディングするサブスクリプション番号に注意を払うことを歓迎します

おすすめ

転載: blog.csdn.net/wade3po/article/details/129669829