2015-05-29 88 views
1

我想要實現的是取mousemove事件的當前座標,並將它們與圓上最近位置的座標進行匹配。我已經成功地得到這個使用for循環,其在中圈每個可能的迭代點和座標,以便進行比較找到的最近點部分工作:D3js找到圓上最近的點

 for (var i = Math.PI; i > -Math.PI; i -= 0.01) { 

      // coords of current point in circle: 

      var curX = Math.sin(i+Math.PI/2)*radius + 200, 
      curY = Math.sin(i)*radius + 200; 

      // conditional which attempts to find the coords of the point closest to the cursor... 

       if (Math.abs((x - curX)) < distanceX && Math.abs((y - curY)) < distanceY) { 
        distanceX = Math.abs((x - curX)); 
        distanceY = Math.abs((y - curY)); 

        // and then assigns the values to the newX/newY variables 

        newX = curX; 
        newY = curY; 
       } 

      } 

麻煩的是,這種解決方案會經常回錯誤的座標,我不知道爲什麼。

的jsfiddle,看看我的意思是:

https://jsfiddle.net/eLn4jsue/

回答

2

無需環路,只計算圓的中心和鼠標是圓上的點。

var dx = x - 200, 
    dy = y - 200, 
    dist = Math.sqrt(dx*dx + dy*dy), 
    newX = 200 + dx * radius/dist, 
    newY = 200 + dy * radius/dist; 

https://jsfiddle.net/3n0dv5v8/1/