[英]Finding the closest grid coordinate to the mouse position with javascript/jQuery
在计算哪个网格点最接近 - 例如,每个块是10x10像素 - 以获得网格索引时,您只需将它们分开 -
如果需要存储数据,可以在点击时将网格坐标推送到数组,以便稍后引用。
我可以做一些事情,比如找出哪个坐标是我的间距最接近onclick坐标的倍数?
当然。 网格的整个点是可以通过简单的算术计算出来的,而不是必须围绕一大堆任意点。
我从哪里开始计算哪个网格点坐标最接近?
这是一个简单的划分,每个轴都有圆角。
#canvas { position: relative; width: 100px; height: 100px; border: solid red 1px; }
#nearest { position: absolute; width: 10px; height: 10px; background: yellow; }
<div id="canvas"><div id="nearest"></div></div>
var gridspacing= 10;
$('#canvas').mousemove(function(event) {
var pos= $(this).offset();
var gridx= Math.round((event.pageX-pos.left)/gridspacing);
var gridy= Math.round((event.pageY-pos.top)/gridspacing);
$('#nearest').css('left', (gridx-0.5)*gridspacing+'px').css('top', (gridy-0.5)*gridspacing+'px');
});
我最初写的答案类似于bobince,但他在我之前到达那里。 我喜欢这种方式,但他的版本有一些楼层(虽然它仍然是一个非常好的答案)。
我认为你想要的是一个没有HTML的网格(也就是说,没有像表一样的标记),bobince提供了一个解决方案。 在这种情况下,可以针对跨浏览器兼容性,可读性,错误和速度显着优化代码。
所以,我建议代码应该更像这样:
#canvas { position: relative; width: 100px; height: 100px; border: solid red 1px; }
#nearest { position: absolute; width: 10px; height: 10px; background: yellow; }
<div id="canvas"><div id="nearest"></div></div>
var
canvasOffset = $("div#canvas").offset(),
// Assuming that the space between the points is 10 pixels. Correct this if necessary.
cellSpacing = 10;
$("div#canvas").mousemove(function(event) {
event = event || window.event;
$("div#nearest").css({
top: Math.round((mouseCoordinate(event, "X") - canvasOffset.left) / cellSpacing) * cellSpacing + "px",
left: Math.round((mouseCoordinate(event, "Y") - canvasOffset.top) / cellSpacing) * cellSpacing + "px"
});
});
// Returns the one half of the current mouse coordinates relative to the browser window.
// Assumes the axis parameter to be uppercase: Either "X" or "Y".
function mouseCoordinate(event, axis) {
var property = (axis == "X") ? "scrollLeft" : "scrollTop";
if (event.pageX) {
return event["page"+axis];
} else {
return event["client"+axis] + (document.documentElement[property] ? document.documentElement[property] : document.body[property]);;
}
};
mouseCoordinate()函数是这两个函数的简化版本:
function mouseAxisX(event) {
if (event.pageX) {
return event.pageX;
} else if (event.clientX) {
return event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
}
};
function mouseAxisY(event) {
if (event.pageY) {
return event.pageY;
} else if (event.clientY) {
return event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
};
我非常喜欢你的项目的想法,也许我会自己做类似的东西:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.