用js实现鼠标绘制矩形图
时间: 2023-12-13 07:06:02 浏览: 65
以下是用JavaScript实现鼠标绘制矩形图的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Mouse Drawing</title>
<style>
#canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var x, y, width, height;
var isDrawing = false;
canvas.addEventListener("mousedown", function(event) {
x = event.offsetX;
y = event.offsetY;
isDrawing = true;
});
canvas.addEventListener("mousemove", function(event) {
if (!isDrawing) {
return;
}
width = event.offsetX - x;
height = event.offsetY - y;
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeRect(x, y, width, height);
});
canvas.addEventListener("mouseup", function(event) {
isDrawing = false;
});
</script>
</body>
</html>
```
这段代码会创建一个HTML5 Canvas元素,并在鼠标按下、移动和松开事件上添加监听器。当鼠标按下时,记录起始点的坐标,并将isDrawing标记为true。当鼠标移动时,如果isDrawing为true,则计算矩形的宽度和高度,并使用clearRect方法清除画布上的矩形,再使用strokeRect方法绘制新的矩形。当鼠标松开时,将isDrawing标记为false。
阅读全文