Skip to content
Advertisement

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. 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 (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:

https://jsfiddle.net/eLn4jsue/

Advertisement

Answer

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/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement