• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

canvas 实现签名

武飞扬头像
阿叶同志
帮助1

canvas 实现签名。实现的思路是:

  1. 当鼠标指针按下的时候,记录点击的位置,并作为绘制的起点。
  2. 当鼠标移动的时候,进行路径的绘制。
  3. 当鼠标指针抬起的时候,取消鼠标移动的事件,结束路径的绘制。

使用 clearRect 方法清除画布,通过传入参数 ctx.clearRect(0, 0, canvas.width, canvas.height) 可以清除全部的画布区域。

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
      }
      canvas {
        box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
      }
      .clear {
        width: 600px;
        height: 50px;
        border-radius: 10px;
        background-color: #E4E7ED;
        margin-top: 10px;
        font-size: 24px;
        text-align: center;
        line-height: 50px;
        cursor: pointer;
      }
      .clear:hover {
        background-color: #C0C4CC;
      }
    </style>
  </head>
  <body>
    <canvas width="600" height="400" tabindex="0"> </canvas>
    <div class="clear">
      清除画布
    </div>
    <script>
      const canvas = document.querySelector("canvas");
      const ctx = canvas.getContext("2d");
      const clear = document.querySelector(".clear")
      // 监听鼠标进入 canvas, 监听鼠标指针按下和抬起
      canvas.addEventListener('mouseenter', () => {
        // 监听鼠标指针按下
        canvas.addEventListener('mousedown', (e) => {
          // 开始绘制路径
          ctx.beginPath()
          // 设置绘制的起点为当前点击的位置
          ctx.moveTo(e.offsetX, e.offsetY)
          // 监听键盘移动事件
          canvas.addEventListener('mousemove', draw)
        })
        canvas.addEventListener('mouseup', () => {
          // 移除鼠标移动事件
          canvas.removeEventListener('mousemove', draw)
        })
      })
      function draw(e) {
        // 绘制线
        ctx.lineTo(e.offsetX, e.offsetY)
        // 描边路径
        ctx.stroke()
      }
      clear.addEventListener('click', () => {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
      })
    </script>
  </body>
</html>
学新通

实现效果如下:

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbckbg
系列文章
更多 icon
同类精品
更多 icon
继续加载