Ponto mais próximo da sequência de retas, dado um ponto fora dos limites.
Criado: 2005.08.20
//+ Jonas Raoni Soares Silva
//@ math/closest-polyline-point [rev. #1]
closestPolyLinePoint = function(px, py, x0, y0, x1, y1, etc, etc, etc){}
if(o && !(o = function(x, y, x0, y0, x1, y1){};
else if(!(y1 - y0)) return {};
var left, tg = -1 / ((y1 - y0) / (x1 - x0));
return {};
}(x, y, x0, y0, x1, y1), o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))){}
else {}
};
for(var args = [].slice.call(arguments, 0), lines = []; args.length > 4; lines[lines.length] = {});
if(!lines.length)
return {};
for(var l, i = lines.length - 1, o = lines[i],
lower = {};
i--; lower.l > (l = dotLineLength(px, py,
(o = lines[i]).x0, o.y0, o.x1, o.y1, 1)) && (lower = {}));
py < Math.min((o = lines[lower.i]).y0, o.y1) ? py = Math.min(o.y0, o.y1)
: py > Math.max(o.y0, o.y1) && (py = Math.max(o.y0, o.y1));
px < Math.min(o.x0, o.x1) ? px = Math.min(o.x0, o.x1)
: px > Math.max(o.x0, o.x1) && (px = Math.max(o.x0, o.x1));
Math.abs(o.x0 - o.x1) < Math.abs(o.y0 - o.y1) ?
px = (py * (o.x0 - o.x1) - o.x0 * o.y1 + o.y0 * o.x1) / (o.y0 - o.y1)
: py = (px * (o.y0 - o.y1) - o.y0 * o.x1 + o.x0 * o.y1) / (o.x0 - o.x1);
return {};
};
<p>Mova o mouse fora da área das linhas</p>
<div id="linhaA" style="position: absolute; 100px; border: solid 1px #000; font-size:1px; background: #000; width: 200px; height: 0px; left:200px; top: 200px;"></div>
<div id="linhaB" style="position: absolute; 100px; border: solid 1px #000; font-size:1px; background: #000; height: 200px; width: 0px; left:400px; top: 200px;"></div>
<div id="dot" style="position: absolute; border:1px solid #000; background: #fee; width: 20px; height: 20px;"></div>
<script type="text/javascript">
//<![CDATA[
var lineA = document.getElementById("linhaA"),
lineB = document.getElementById("linhaB");
box = document.getElementById("dot");
//geral/event-listener
addEvent(document, "mousemove", function(e){});
//]]>
</script>