实现代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas实现手写板</title>
<style>
html,body{
margin: 0;
padding: 0;
}
#signatureCanvas{
background-color: #999;
}
</style>
</head>
<body>
<canvas id="signatureCanvas"></canvas>
<script>
let canvas = document.getElementById("signatureCanvas");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
let ctx = canvas.getContext("2d");
let isDrawing = false;
let lastX = 0;
let lastY = 0;
const startDrawing=(e)=> {
isDrawing = true;
lastX = e.pageX;
lastY = e.pageY;
}
const draw=(e)=> {
if (!isDrawing) return;
let currentX = e.pageX;
let currentY = e.pageY ;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(currentX, currentY);
ctx.strokeStyle = "#000";
ctx.lineWidth = 3;
ctx.stroke();
lastX = currentX;
lastY = currentY;
}
const stopDrawing=()=> {
isDrawing = false;
}
// 监听PC端鼠标移动事件
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
// 监听移动端touch事件
canvas.addEventListener("touchstart", startDrawing);
canvas.addEventListener("touchmove", draw);
canvas.addEventListener("touchend", stopDrawing);
</script>
</body>
</html>