Nearest Point To Line //JavaScript Repository

Description

Nearest point to a line, given a point out of the limits.
Created: 2005.08.20

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-line-point [rev. #1]

closestLinePoint = function(px, py, x, y, angle){
    var tg = ((angle %= 360) < 0 && (angle += 180), Math.tan(-angle * Math.PI / 180));
    return angle < 45 || angle > 135 ? {x: px, y: (px - x) * tg + y} : {x: (py - y) / tg + x, y: py};
};

Example (Example)

<div id="linha" style="position: absolute; background: #eef; width: 200px; height: 200px; left:200px; top: 200px;">Mova o mouse fora da ?rea do ret?ngulo, o ?ngulo foi setado randomicamente.</div>
<div id="dot" style="position: absolute; border:1px solid #000; background: #fee; width: 20px; height: 20px;"></div>

<script type="text/javascript">
//<![CDATA[

var angulo = Math.random() * 256, line = document.getElementById("linha"), box = document.getElementById("dot");

//http://www.jsfromhell.com/geral/event-listener
addEvent(document, "mousemove", function(e){
    var p = closestLinePoint(e.clientX, e.clientY, line.offsetLeft + line.offsetWidth / 2, line.offsetTop + line.offsetHeight / 2, angulo);
    box.style.left = (p.x - box.offsetWidth / 2) + "px";
    box.style.top = (p.y - box.offsetHeight / 2) + "px";
});

//]]>
</script>

Help

closestLinePoint( px: Integer, py: Integer, x: Integer, y: Integer, angle: Double ): Object
Retorna um objeto contendo duas propriedades (x e y), que especificam o ponto limítrofe de um círculo em relação a um ponto.
px
point's x coord
py
point's y coord
x
x coord of the line's center point
y
y coord of the line's center point
ray
line's angle in degrees

Rank (Votes: 5)

2.60