基于canvas通过鼠标在浏览器图像上画线条自动吸附到画的线条附近的灰色区域 完整的代码
时间: 2023-05-30 08:01:23 浏览: 241
以下是一个基于canvas实现鼠标画线条自动吸附到灰色区域的完整代码:
HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>Canvas自动吸附线条</title>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
```
JavaScript:
```
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// 画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 灰色区域的坐标和大小
const grayRect = { x: 300, y: 200, width: 200, height: 200 };
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function draw(e) {
if (!isDrawing) return;
// 当前鼠标的位置
const mouseX = e.clientX;
const mouseY = e.clientY;
// 将线条自动吸附到灰色区域
if (mouseX > grayRect.x && mouseX < grayRect.x + grayRect.width && mouseY > grayRect.y && mouseY < grayRect.y + grayRect.height) {
ctx.strokeStyle = 'gray';
} else {
ctx.strokeStyle = 'black';
}
drawLine(lastX, lastY, mouseX, mouseY);
lastX = mouseX;
lastY = mouseY;
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
lastX = e.clientX;
lastY = e.clientY;
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
```
以上代码实现了基于canvas通过鼠标在浏览器图像上画线条自动吸附到画的线条附近的灰色区域。当鼠标移动到灰色区域内时,画出的线条颜色变为灰色,移出灰色区域时变为黑色。
阅读全文