canvas手機簽名

<!doctype html>
<html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas手機簽名</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        background: #e7e7e7;
      }
      canvas {
        display: block;
        margin: 50px auto;
        background: #fff;
      }
      button {
        display: block;
        width: 100px;
        height: 40px;
        margin: 20px auto 0;
        border: 0;
        border-radius: 5px;
        background: #2ca2dd;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <canvas width="300" height="200">您當前瀏覽器不支持canvas,建議更換瀏覽器!</canvas>
    <button>保存</button>
    <button>清空畫布</button>
    <script>
      var canvas = document.querySelector('canvas'),
        oBtn = document.querySelectorAll('button'),
        ctx = canvas.getContext('2d');
      var _x = 0,
        _y = 0,
        x = 0,
        y = 0;
      // 設置畫布大小
      canvas.width = 300;
      canvas.height = 200;
      // 開始繪製
      canvas.addEventListener('touchstart', function (e) {
        e.preventDefault();
        _x = e.touches[0].pageX,
        _y = e.touches[0].pageY;
        // 路徑開始
        ctx.beginPath();
        ctx.moveTo(_x - canvas.offsetTop, _y - canvas.offsetLeft);

        // 路徑移動
        this.addEventListener('touchmove', function (e) {
          x = e.touches[0].pageX,
          y = e.touches[0].pageY;
          ctx.lineTo(x - canvas.offsetTop, y - canvas.offsetLeft);
          ctx.stroke();
        });
      });
      // 導出圖片
      oBtn[0].onclick = function () {
        var oImg = new Image();
        ctx.drawImage(oImg, 0, 0);
        console.log(canvas.toDataURL('image/png').length)
        oImg.src = canvas.toDataURL('image/png');
        document.body.appendChild(oImg);
      }
      // 清空畫布
      oBtn[1].onclick = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
    </script>
  </body></html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章