我有2个圆圈和一条线。圆圈有一个移动选项(你可以按它们移动)。 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();
答案 0 :(得分:1)