canvas画直线可以拖动
时间: 2023-08-03 20:25:26 浏览: 53
是的,可以通过添加鼠标事件来实现拖动直线的功能。具体实现方式如下:
1. 定义一个变量保存当前是否正在拖动直线的状态,比如 `isDragging`;
2. 给 canvas 添加 `mousedown` 事件监听器,当用户点击鼠标时,如果鼠标位置在直线上,就将 `isDragging` 设置为 `true`;
3. 给 canvas 添加 `mousemove` 事件监听器,当用户拖动鼠标时,如果当前正在拖动直线,就更新直线的位置;
4. 给 canvas 添加 `mouseup` 事件监听器,当用户松开鼠标时,将 `isDragging` 设置为 `false`。
下面是一个简单的示例代码:
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let startX, startY, isDragging = false;
// 画一条直线
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// 判断点是否在直线上
function isPointOnLine(x, y, x1, y1, x2, y2) {
const dx = x - x1;
const dy = y - y1;
const length = Math.sqrt(dx*dx + dy*dy);
const angle = Math.atan2(dy, dx);
const x3 = x1 + length * Math.cos(angle);
const y3 = y1 + length * Math.sin(angle);
return x3 > Math.min(x1, x2) && x3 < Math.max(x1, x2) && y3 > Math.min(y1, y2) && y3 < Math.max(y1, y2);
}
// 给 canvas 添加鼠标事件监听器
canvas.addEventListener('mousedown', (e) => {
const x = e.clientX - canvas.offsetLeft;
const y = e.clientY - canvas.offsetTop;
startX = x;
startY = y;
if (isPointOnLine(x, y, 100, 100, 300, 300)) {
isDragging = true;
}
});
canvas.addEventListener('mousemove', (e) => {
const x = e.clientX - canvas.offsetLeft;
const y = e.clientY - canvas.offsetTop;
if (isDragging) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawLine(100, 100, x, y);
}
});
canvas.addEventListener('mouseup', () => {
isDragging = false;
});
```
在这个示例中,我们画了一条从 (100, 100) 到 (300, 300) 的直线。当用户点击鼠标时,如果鼠标位置在直线上,就将 `isDragging` 设置为 `true`。当用户拖动鼠标时,如果当前正在拖动直线,就更新直线的位置。当用户松开鼠标时,将 `isDragging` 设置为 `false`。