用js写一个手写签名的canvas画板
时间: 2023-04-01 19:01:23 浏览: 160
好的,我可以回答这个问题。以下是用 JavaScript 编写手写签名的 Canvas 画板的代码:
HTML 代码:
```
<canvas id="canvas" width="400" height="300"></canvas>
<button id="clearBtn">清除</button>
```
JavaScript 代码:
```
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
let isDrawing = false;
let lastX = ;
let lastY = ;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
context.beginPath();
context.moveTo(lastX, lastY);
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseout', () => {
isDrawing = false;
});
const clearBtn = document.getElementById('clearBtn');
clearBtn.addEventListener('click', () => {
context.clearRect(, , canvas.width, canvas.height);
});
```
这段代码创建了一个 Canvas 画板,当鼠标按下时,开始绘制线条,当鼠标移动时,不断绘制线条,当鼠标松开时,停止绘制。同时,还提供了一个清除按钮,可以清除画板上的所有内容。
阅读全文