【问题标题】:JavaScript Closest point from mouseJavaScript 离鼠标最近的点
【发布时间】:2018-03-12 17:16:31
【问题描述】:

在您发表评论之前,是的,我还检查了其他问题... 比如this article,或者this one,或者甚至可能是this one。但是,我找不到如何设置原点。所以,假设我有一个数组图片 X 坐标和图片 Y 坐标

(在 100*100 的网格上) x /y 92/81 82/47 81/03

现在我有了mouseX 和mouseY。 有谁知道如何在 JavaScript 中创建一个函数来为您提供最接近的点 x 和 y 值?

提前致谢!

【问题讨论】:

    标签: javascript arrays mouse distance closest


    【解决方案1】:

    只需做一些矢量数学运算。给定图像和触摸位置:

     const coords = [[92, 81],  [82, 47], [81, 03]];
     const touchX = 57, touchY = 84;
    

    只需遍历它们并计算距离向量长度:

    let closest = [null, null];
    let distance = Infinity;
    
    for(const [x, y] of coords){
      let d = Math.sqrt((touchX - x) ** 2 + (touchY - y) ** 2);
      if(d < distance){
        closest = [x, y];
        distance = d;
      }
    }
    

    Vectors

    Calculating the length

    【讨论】:

      猜你喜欢
      • 2011-02-02
      • 1970-01-01
      • 2012-09-12
      • 2012-01-03
      • 1970-01-01
      • 2023-03-19
      • 2011-01-28
      • 2014-09-07
      • 2017-06-21
      相关资源
      最近更新 更多