Nearest Point To Circle //JavaScript Repository

Description

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

Code (Download)

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

closestCirclePoint = function(px, py, x, y, ray){
    var tg = (x += ray, y += ray, 0);
    return function(x, y, x0, y0){return Math.sqrt((x -= x0) * x + (y -= y0) * y);}(px, py, x, y) > ray ?
        {x: Math.cos(tg = Math.atan2(py - y, px - x)) * ray + x, y: Math.sin(tg) * ray + y}
        //{x: (px - x) / (length / ray) + x, y: (py - y) / (length / ray) + y}
        : {x: px, y: py};
};

Example (Example)

<div id="circulo" style="position: absolute; -moz-border-radius: 100px; background: #eef; width: 200px; height: 200px; left:200px; top: 200px;">Mova o mouse fora da ?rea do c?rculo</div>
<div id="dot" style="position: absolute; border:1px solid #000; background: #fee; width: 20px; height: 20px;"></div>

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

var circle = document.getElementById("circulo"), box = document.getElementById("dot");

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

//]]>
</script>

Help

closestCirclePoint( px: Integer, py: Integer, x: Integer, y: Integer, ray: 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
circle's x coord origin
y
circle's y coord origin
ray
circle's ray (length divided by 2)

Rank (Votes: 23)

4.22