用 canvas 实现签名。实现的思路是:
- 当鼠标指针按下的时候,记录点击的位置,并作为绘制的起点。
- 当鼠标移动的时候,进行路径的绘制。
- 当鼠标指针抬起的时候,取消鼠标移动的事件,结束路径的绘制。
使用 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>
实现效果如下: