canvas签名

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .wrap {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;

        canvas {
          border: 1px solid #008c8c;
        }

        img {
          width: 600px;
          height: 400px;
          background: pink;
        }
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <canvas width="600" height="400"></canvas>
      <img src="" alt="" />
    </div>

    <div>
      <button id="clearCvs">清空画布</button>
      <span>画笔颜色:</span>
      <input type="color" id="penColor" />
      <span>画笔粗细:</span>
      <input type="range" min="1" max="10" id="penWidth" />
      <button id="saveCvs">保存图片</button>
    </div>

    <script>
      /* 
        1. 实现签名效果,转换为图片
        2. 通过canvas.toDataURL() 转换为图片
        3. 监听鼠标mousedown、mousemove、mouseup事件
      */
      const doms = {
        img: document.querySelector('img'),
        clearCvs: document.querySelector('#clearCvs'),
        penColor: document.querySelector('#penColor'),
        penWidth: document.querySelector('#penWidth'),
        saveCvs: document.querySelector('#saveCvs'),
      };

      // 控制是否正在画
      let isDrawing = false;

      class CanvasEvent {
        constructor(cvs) {
          this.cvs = cvs;
          this.ctx = cvs.getContext('2d');
          this.cvs.addEventListener('mousedown', this.mousedown.bind(this));
          this.cvs.addEventListener('mousemove', this.mousemove.bind(this));
          this.cvs.addEventListener('mouseup', this.mouseup.bind(this));
        }
        mousedown(e) {
          isDrawing = true;
          this.ctx.beginPath();
          this.ctx.moveTo(e.offsetX, e.offsetY);
        }
        mousemove(e) {
          if (isDrawing) {
            this.ctx.lineTo(e.offsetX, e.offsetY);
            this.ctx.stroke();
          }
        }
        mouseup(e) {
          isDrawing = false;
        }
      }

      const cvs = document.querySelector('canvas');
      const c1 = new CanvasEvent(cvs);

      // 清空画布
      doms.clearCvs.onclick = function () {
        c1.ctx.clearRect(0, 0, cvs.width, cvs.height);
      };

      // 画笔颜色
      doms.penColor.onchange = function () {
        c1.ctx.strokeStyle = this.value;
      };

      // 画笔粗细
      doms.penWidth.onchange = function () {
        c1.ctx.lineWidth = this.value;
      };

      // 保存图片
      doms.saveCvs.onclick = function () {
        const img = cvs.toDataURL('image/png');
        doms.img.src = img;

        // 清空画布
        c1.ctx.clearRect(0, 0, cvs.width, cvs.height);
      };
    </script>
  </body>
</html>

移动端监听touch事件即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值