用canvas实现一个画板
时间: 2023-06-07 18:07:48 浏览: 147
好的,下面是实现一个画板的代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas 画板</title>
<style>
#canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var isDrawing = false;
var lastX = 0;
var lastY = 0;
canvas.addEventListener('mousedown', function(e) {
isDrawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
canvas.addEventListener('mousemove', function(e) {
if (isDrawing === true) {
drawLine(lastX, lastY, e.offsetX, e.offsetY);
lastX = e.offsetX;
lastY = e.offsetY;
}
});
window.addEventListener('mouseup', function(e) {
isDrawing = false;
});
function drawLine(startX, startY, endX, endY) {
context.beginPath();
context.moveTo(startX, startY);
context.lineTo(endX, endY);
context.stroke();
context.closePath();
}
</script>
</body>
</html>
```
这个画板使用canvas来绘制线条,当鼠标按下时,开始绘制线条,在鼠标移动时,持续地绘制线条,直到鼠标松开为止。
阅读全文
相关推荐


















