我想在JavaScript中计算到矩形的最小距离:
--------
| | <- Rectangle
--------
* <- Point
但我只找到一个脚本来获取distance to the center of a rectangle。请尽量避免使用JQuery,因为我不想在我的代码中使用它。
示例:(到中心的距离)
var distance = Infinity,
rect,
out;
document.mouse = {
x: Infinity,
y: Infinity
}
window.addEventListener("load", function(e) { // set vars
rect = document.getElementById("rect");
out = document.getElementById("out");
}, false);
window.addEventListener("mousemove", function(e) {
document.mouse = {
x: e.pageX,
y: e.pageY
} // get mouse position
distance = elementDistanceToCursor(rect) // get distance to element
out.innerHTML = ["distance: ", distance].join(""); // show result
}, false);
function elementDistanceToCursor(elem) { // get distance to element center
var b = elem.getBoundingClientRect();
return Math.floor(
Math.sqrt(
Math.pow(document.mouse.x - (b.left + (elem.offsetWidth / 2)), 2)
+Math.pow(document.mouse.y - (b.top + (elem.offsetHeight / 2)), 2)
)
);
}
&#13;
div#rect {
width: 200px;
height: 100px;
border: 1px solid black;
background-color: aqua;
margin: auto;
margin-top: 50px;
}
out {
margin: auto;
vertical-align: middle;
text-align: center;
display: block;
height: 20px;
margin-top: 30px;
}
&#13;
<div id="rect">
<out id="out"></out>
</div>
&#13;
答案 0 :(得分:0)
要计算从矩形到点的最小距离,请在每个维上使用有符号距离,然后计算平方和的sqrt。
var distance = Infinity,
rect,
out;
document.mouse = {
x: Infinity,
y: Infinity
}
window.addEventListener("load", function(e) { // set vars
rect = document.getElementById("rect");
out = document.getElementById("out");
}, false);
window.addEventListener("mousemove", function(e) {
document.mouse = {
x: e.pageX,
y: e.pageY
} // get mouse position
distance = elementDistanceToCursor(rect) // get distance to element
out.innerHTML = ["distance: ", distance].join(""); // show result
}, false);
function elementDistanceToCursor(elem) { // get distance to element
var b = elem.getBoundingClientRect();
var dx = 0;
var dy = 0;
//Compute distance to elem in X
if (document.mouse.x < b.left)
dx = b.left - document.mouse.x;
else if (document.mouse.x > b.right)
dx = b.right - document.mouse.x;
//Compute distance to elem in Y
if (document.mouse.y < b.top)
dy = b.top - document.mouse.y;
else if (document.mouse.y > b.bottom)
dy = b.bottom - document.mouse.y;
return Math.floor(Math.sqrt(dx * dx + dy * dy));
}
&#13;
div#rect {
width: 200px;
height: 100px;
border: 1px solid black;
background-color: aqua;
margin: auto;
margin-top: 50px;
}
out {
margin: auto;
vertical-align: middle;
text-align: center;
display: block;
height: 20px;
margin-top: 30px;
}
&#13;
<div id="rect">
<out id="out"></out>
</div>
&#13;