[英]D3js find closest point on circle
我想要實現的是獲取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;
}
}
麻煩的是,這種解決方案通常會返回錯誤的坐標,我不確定為什么。
jsfiddle明白我的意思:
無需循環,只需計算圓心和圓上鼠標之間的點即可。
var dx = x - 200,
dy = y - 200,
dist = Math.sqrt(dx*dx + dy*dy),
newX = 200 + dx * radius / dist,
newY = 200 + dy * radius / dist;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.