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:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.