鼠标的JavaScript最近点 [英] 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
(在100 * 100的网格上) x/y 92/81 82/47 81/03
(on a grid of 100*100) x /y 92/81 82/47 81/03
现在我有了mouseX和mouseY. 有谁知道如何创建一个函数来为您提供JavaScript中最接近的x和y值?
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?
提前谢谢!
推荐答案
只需做一些vecor数学.给定图像和触摸位置:
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;
只需遍历它们并计算距离vecors长度:
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;
}
}
这篇关于鼠标的JavaScript最近点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!