Javascript D3js查找圆上最近的点

Javascript D3js查找圆上最近的点,javascript,d3.js,pi,trigonometry,Javascript,D3.js,Pi,Trigonometry,我试图实现的是获取mousemove事件的当前坐标,并将它们与圆上最近位置的坐标相匹配。我使用for循环成功地实现了部分功能,该循环迭代圆中的每个可能点,并比较坐标以找到最近的点: 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)*

我试图实现的是获取mousemove事件的当前坐标,并将它们与圆上最近位置的坐标相匹配。我使用for循环成功地实现了部分功能,该循环迭代圆中的每个可能点,并比较坐标以找到最近的点:

        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;
                }

            }
for(var i=Math.PI;i>-Math.PI;i-=0.01){
//圆中当前点的坐标:
var curX=数学sin(i+Math.PI/2)*半径+200,
curY=数学sin(i)*半径+200;
//尝试查找最靠近光标的点的坐标的条件。。。
if(Math.abs((x-curX))
问题是这个解决方案经常会返回错误的坐标,我不知道为什么

我想知道我的意思:


无需循环,只需计算圆心和鼠标在圆上的点

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

无需循环,只需计算圆心和鼠标在圆上的点

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