我有 2 个圆圈和 1 条线。圆圈有一个移动选项(你可以按下它们并移动)。Mousemove 事件有一个变量distance
来计算鼠标和圆之间的距离。
问题是,当你将一个圆圈移到另一个圆圈足够近时,它们会加入。如何避免这种情况?有没有选择让一些焦点或类似的东西?任何想法如何解决这个问题(有可能吗?)
我的代码:
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
radius = 12,
p = null,
start = false;
point = {
p1: { x:100, y:250 },
p2: { x:400, y:100 }
}
function init() {
return setInterval(draw, 10);
}
canvas.addEventListener('mousedown', function(e) {
start = true;
});
canvas.addEventListener('mouseup', function(e) {
start = false;
});
canvas.addEventListener('mousemove', function(e) {
for (p in point) {
if(start) {
var
mouseX = e.clientX -10,
mouseY = e.clientY -10,
distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));
if (distance -10<= radius) {
point[p].x = e.clientX -10 ;
point[p].y = e.clientY -10 ;
}
}
}
});
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(point.p1.x,point.p1.y);
context.lineTo(point.p2.x,point.p2.y);
context.closePath();
context.fillStyle = '#8ED6FF';
context.fill();
context.stroke();
for (p in point) {
context.beginPath();
context.arc(point[p].x,point[p].y,radius,0,2*Math.PI);
context.fillStyle = 'red';
context.fill();
context.stroke();
}
context.closePath();
}
init();
</p>