html画板橡皮擦代码
时间: 2023-11-29 11:45:18 浏览: 30
以下是一个HTML5 Canvas画板橡皮擦的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas画板橡皮擦</title>
<style type="text/css">
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// 设置画笔属性
context.lineWidth = 5;
context.lineCap = "round";
context.lineJoin = "round";
context.strokeStyle = "#000";
// 绘制线条
var isDrawing = false;
var lastX = 0;
var lastY = 0;
function draw(e) {
if (!isDrawing) return;
context.beginPath();
context.moveTo(lastX, lastY);
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
}
canvas.addEventListener("mousedown", function(e) {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", function() {
isDrawing = false;
});
// 设置橡皮擦属性
var eraser = document.getElementById("eraser");
eraser.addEventListener("click", function() {
context.lineWidth = 20;
context.strokeStyle = "#fff";
});
// 清空画布
var clearBtn = document.getElementById("clear");
clearBtn.addEventListener("click", function() {
context.clearRect(0, 0, canvas.width, canvas.height);
});
</script>
<button id="eraser">橡皮擦</button>
<button id="clear">清空</button>
</body>
</html>
```
该代码实现了一个基本的Canvas画板,包括绘制线条、清空画布、使用橡皮擦等功能。当点击“橡皮擦”按钮时,画笔的粗细会变为20,颜色会变为白色,从而实现了橡皮擦的功能。