2015-05-29 176 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/