JavaScript Closest point from mouse

纵饮孤独 提交于 2019-12-13 09:54:02

问题


Before you comment, yes i have checked other questions aswell... like this article, or this one, or maybe even this one. However, i couldn't find how to set the point of origin. So, let's say i have an array picture X coords and picture Y coords

(on a grid of 100*100) x /y 92/81 82/47 81/03

Now i have the mouseX and mouseY. Does anyone know how to make a function that gives you the closest point x and y values in JavaScript?

Thanks in advance!


回答1:


Just do some vecor math. Given the images and the touch position:

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

Just go over them and calculate the distance vecors length:

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



来源:https://stackoverflow.com/questions/49199156/javascript-closest-point-from-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!