2012-12-10 3 views
0

2 개의 원과 1 개의 선이 있습니다. 서클에는 이동 옵션이 ​​있습니다 (u를 눌러 이동시킬 수 있음). Mousemove 이벤트에는 마우스와 원 간의 거리를 계산하는 변수 distance이 있습니다.캔버스 마우스 이벤트 및 포커스

문제는 하나의 원을 다른 원으로 충분히 가까이 이동할 때 결합된다는 것입니다. 어떻게 피하는거야? 초점을 맞추는 등의 옵션이 있습니까? 그 문제를 해결하는 방법에 어떤 아이디어 (그것이 가능합니까?)

My code : 어떤 지점을 저장하는

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(); 

답변

1

시도는 mousedown 이벤트에 눌렀습니다. 그와 마찬가지로

: http://jsfiddle.net/cs5Sg/9/

또한, 그것은 각 지점에 너무 마우스 움직임이 빨라집니다마다 거리를 계산하지 않습니다.

+0

나는 한 가지 질문이 있습니다 - 왜 움직이는 것이 거짓입니까? 왜 null이 아닌가? 어떤 차이가 있습니까? – Amay

+0

그것은 습관이지만, null은 작동합니다. 나는 거짓이 조금 더 명백하다고 생각하지만 그것은 나의 의견 일 뿐이다. –