2012-12-10 226 views
0

我有2個圓圈和一行。圓圈有一個移動選項(你可以按下它們並移動)。 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

這是一種習慣,但空效果真實。我認爲虛假更明確一些,但這只是我的看法。 –