javascript - D3js 找到圆上最近的点

标签 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)*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 看看我的意思:

https://jsfiddle.net/eLn4jsue/

最佳答案

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

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/

关于javascript - D3js 找到圆上最近的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30531474/

相关文章:

javascript - 通用Ajax错误处理-Angular JS中的拦截器

d3.js - 将 slider 添加到条形图以进行过滤

javascript - 从最小日期开始添加一个月的填充

javascript - unicode 中没有 Pi 上标?

javascript - Chrome 中没有在 ENTER 键上生成按键事件?

带有回调函数的 Javascript 数组

javascript - 密码字段问题

jquery - 无法使用 Wicked PDF 渲染图表

r - 如何根据R中的U和V风分量计算风向

loops - 为什么我的变量在循环中没有递增?