完成上述的需求的同时,我还需要改动画布的初始状态,希望画布可以初始出现在程序较中间的位置,同时画布的网格线应该更细一点,请给出一个示例代码
时间: 2024-03-16 20:47:27 浏览: 67
微信小程序之Canvas.zip
好的,以下是一个示例代码,实现了您的需求:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置画布初始位置和网格线样式
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.lineWidth = 0.5;
ctx.strokeStyle = '#ddd';
// 绘制网格线
for (let i = -canvas.width / 2; i <= canvas.width / 2; i += 10) {
ctx.beginPath();
ctx.moveTo(i, -canvas.height / 2);
ctx.lineTo(i, canvas.height / 2);
ctx.stroke();
}
for (let i = -canvas.height / 2; i <= canvas.height / 2; i += 10) {
ctx.beginPath();
ctx.moveTo(-canvas.width / 2, i);
ctx.lineTo(canvas.width / 2, i);
ctx.stroke();
}
let isDragging = false;
let rect = {
x: 0,
y: 0,
width: 100,
height: 100,
angle: 0
};
// 绘制矩形
function drawRect() {
ctx.clearRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
ctx.save();
ctx.translate(rect.x, rect.y);
ctx.rotate(rect.angle);
ctx.fillRect(-rect.width / 2, -rect.height / 2, rect.width, rect.height);
ctx.restore();
}
// 鼠标事件处理
canvas.addEventListener('mousedown', function (e) {
const x = e.clientX - canvas.offsetLeft - canvas.width / 2;
const y = e.clientY - canvas.offsetTop - canvas.height / 2;
if (x > rect.x - rect.width / 2 && x < rect.x + rect.width / 2 && y > rect.y - rect.height / 2 && y < rect.y + rect.height / 2) {
isDragging = true;
}
});
canvas.addEventListener('mousemove', function (e) {
if (isDragging) {
const x = e.clientX - canvas.offsetLeft - canvas.width / 2;
const y = e.clientY - canvas.offsetTop - canvas.height / 2;
rect.x = x;
rect.y = y;
drawRect();
}
});
canvas.addEventListener('mouseup', function () {
isDragging = false;
});
canvas.addEventListener('wheel', function (e) {
const zoom = e.deltaY > 0 ? 0.9 : 1.1;
rect.width *= zoom;
rect.height *= zoom;
drawRect();
});
canvas.addEventListener('contextmenu', function (e) {
e.preventDefault();
rect.angle += Math.PI / 4;
drawRect();
});
drawRect();
</script>
</body>
</html>
```
这段代码中,我们使用了`translate()`方法将画布移动到程序的中心位置,并使用`lineWidth`和`strokeStyle`属性来设置网格线的样式。然后我们循环绘制网格线,使用`rect()`方法绘制矩形,并使用鼠标事件来实现矩形的拖动和缩放,使用鼠标右键来旋转矩形。
阅读全文