Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

arrays - JavaScript Closest point from mouse

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...