鼠标的JavaScript最近点 [英] JavaScript Closest point from mouse

查看:96
本文介绍了鼠标的JavaScript最近点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在您发表评论之前,是的,我也检查了其他问题... 像这篇文章,甚至

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆