Canvas如何实现画板功能。
<!DOCTYPE html>
<html>
<head><title>Canvas 画板</title><style>canvas {border: 1px solid black;}</style>
</head>
<body><canvas id="canvas" width="800" height="600"></canvas><button id="clear-button">clear-button</button><script>// 获取 Canvas 元素和上下文var canvas = document.getElementById('canvas');var context = canvas.getContext('2d');// 设置画笔初始状态var isDrawing = false; // 是否正在画线var isErasing = false; // 是否正在擦除var lastX = 0; // 上一个点的 X 坐标var lastY = 0; // 上一个点的 Y 坐标// 监听鼠标按下事件canvas.addEventListener('mousedown', startDrawing);// 监听鼠标移动事件canvas.addEventListener('mousemove', draw);// 监听鼠标松开事件canvas.addEventListener('mouseup', stopDrawing);// 监听鼠标离开画布事件canvas.addEventListener('mouseleave', stopDrawing);// 监听触摸屏按下事件canvas.addEventListener('touchstart', startDrawing);// 监听触摸屏移动事件canvas.addEventListener('touchmove', draw);// 监听触摸屏松开事件canvas.addEventListener('touchend', stopDrawing);// 开始绘制function startDrawing(e) {isDrawing = true;[lastX, lastY] = [e.clientX || e.touches[0].clientX, e.clientY || e.touches[0].clientY];}// 绘制线条或擦除function draw(e) {if (!isDrawing) return;var newX = e.clientX || e.touches[0].clientX;var newY = e.clientY || e.touches[0].clientY;if (isErasing) {context.clearRect(newX - 10, newY - 10, 20, 20); // 使用橡皮擦大小为 20x20 的矩形来清除画布上的内容} else {context.beginPath();context.moveTo(lastX, lastY);context.lineTo(newX, newY);context.stroke();[lastX, lastY] = [newX, newY];}}// 停止绘制function stopDrawing() {isDrawing = false;}// 监听清除按钮点击事件var clearButton = document.getElementById('clear-button');clearButton.addEventListener('click', clearCanvas);// 清除画布function clearCanvas() {context.clearRect(0, 0, canvas.width, canvas.height);}</script>
</body>
</html>