canvas电子签名和画板(源码)

<!DOCTYPE html>
<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>
    canvas {
      border: 1px solid #333;
    }
  </style>
</head>

<body>
  <label for="">颜色:</label>
  <input type="color" id="colors">
  <label for="">粗细:</label>
  <select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
  <button>清除</button>
  <hr>
  <canvas id="p" width="600" height="400"></canvas>
</body>
<script>
  const canvas = document.querySelector('#p');
  context = canvas.getContext('2d');
  //3.声明一个控制鼠标down和up的状态
  let status = false;
  // 4.接下来  我们改变一下笔的颜色
  let color = '#000';
  document.querySelector('#colors').addEventListener('change', e => {
    // console.log(e.target.value);
    color = e.target.value
  });
  //5.接下来 我们改变一下画笔的粗细、
  let lineWidth = 1
  document.querySelector('#select').onchange = function (e) {
    lineWidth = e.target.value
  }
  //6.我们来清除一下画板
  document.querySelector('button').onclick = function () {
    canvas.width = 600
    canvas.height = 400
  }
  //接下来 进行具体的操作
  //1.先设置起始点
  canvas.addEventListener('mousedown', (e) => {
    context.beginPath();
    context.moveTo(e.offsetX, e.offsetY);
    status = true
  })
  //2.设置鼠标移动时  折线的拐点
  canvas.addEventListener('mousemove', (e) => {
    if (status) {
      context.lineTo(e.offsetX, e.offsetY);
      context.strokeStyle = color;
      context.lineWidth = lineWidth;
      context.stroke();
    }
  })
  //4.当鼠标up时  我们重新把状态给改变一下
  canvas.addEventListener('mouseup', (e) => {
    status = false;
  })

</script>

</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值