简体   繁体   English

D3js在圆上找到最近的点

[英]D3js find closest point on circle

what I'm trying to achieve is to take the current coordinates of a mousemove event and match them with the coordinates of the closest location on a circle. 我想要实现的是获取mousemove事件的当前坐标,并将它们与圆上最近位置的坐标相匹配。 I've managed to get this partially working using a for loop which iterates over each possible point in the circle and compares the coordinates in order to find the closest point: 我设法使用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;
                }

            }

the trouble is that this solution will often return the wrong coordinates and I'm not sure why. 麻烦的是,这种解决方案通常会返回错误的坐标,我不确定为什么。

jsfiddle to see what I mean: jsfiddle明白我的意思:

https://jsfiddle.net/eLn4jsue/ https://jsfiddle.net/eLn4jsue/

No need to loop, just compute the point between the center of the circle and the mouse that is on the circle. 无需循环,只需计算圆心和圆上鼠标之间的点即可。

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/ https://jsfiddle.net/3n0dv5v8/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM