使用 javascript/jQuery 查找距离鼠标位置最近的网格坐标
我想做的是在页面上等距地创建一个不可见坐标网格。然后,我希望在触发 onclick 时将
放置在最接近指针的网格坐标处。大概的想法是:我对鼠标坐标的跟踪和
的放置效果很好。我所困扰的是如何解决坐标网格的问题。首先,我是否应该将所有坐标放在一个数组中,然后将其与 onclick 坐标进行比较?
或者看到我的网格坐标遵循规则,我可以做一些事情,例如找出哪个坐标是无论我的间距的倍数最接近onclick坐标吗?
然后,我从哪里开始计算哪个网格点坐标最接近?最好的方法是什么?
谢谢!
What I'm trying to do is make a grid of invisible coordinates on the page equally spaced. I then want a <div>
to be placed at whatever grid coordinate is closest to the pointer when onclick is triggered. Here's the rough idea:
I have the tracking of the mouse coordinates and the placing of the <div>
worked out fine. What I'm stuck with is how to approach the problem of the grid of coordinates.
First of all, should I have all my coordinates in an array which I then compare my onclick coordinate to?
Or seeing as my grid coordinates follow a rule, could I do something like finding out which coordinate that is a multiple of whatever my spacing is is closest to the onclick coordinate?
And then, where do I start with working out which grid point coordinate is closest? What's the best way of going about it?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在计算哪个网格点最接近时 - 例如,每个块都是 10x10 像素 - 要获得网格索引,您只需将它们分开 -
如果您需要存储数据,您可以在单击时将网格坐标推送到数组,以供稍后参考。
In terms of working out which grid point is closest - say, for example, each block is 10x10 pixels - to get the grid index you would just divide them out -
If you need to store the data, you could push the grid co-ordinates to an array on click, to reference later.
当然。网格的全部要点在于它可以通过简单的算术进行计算,而不是必须围绕一大堆任意点进行计算。
这是一个简单的除法,每个轴都进行舍入。
Sure. The whole point of a grid it's it's calculable with simple arithmetic, rather than having to cart around a big array of arbitrary points.
It's a simple division with rounding for each axis.
我最初写的是与鲍宾斯类似的答案,但他比我先到达那里。我喜欢这种方式,但他的版本有一些楼层(尽管它仍然是一个非常好的答案)。
我认为您想要的是一个无 HTML 的网格(即没有像表格这样的标记),bobince 提供了一个解决方案。在这种情况下,代码可能会针对跨浏览器兼容性、可读性、错误和速度进行显着优化。
所以,我建议代码应该更像这样:
mouseCooperative() 函数是这两个函数的简化版本:
我真的很喜欢你项目的想法,也许我会自己做一些类似的东西:D
I was initially writing an answer similar to bobince's, but he got there before me. I like that way of doing it, but his version has got some floors (though it's still a very good answer).
I presume that what you want is a HTML-less grid (that is, without markup like a table), which bobince supplies a solution for. In that case, the code may be optimised significantly for cross browser compatibility, readability, errors and speed.
So, I suggest the code should be more like this:
The mouseCoordinate() function is a boiled down version of these two functions:
I really like the idea of your project, perhaps I'll make something similar myself :D