DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Closest Circle Point //JavaScript Function

09.09.2005
| 7197 views |
  • submit to reddit
        <a href="http://jsfromhell.com/math/closest-circle-point">
Given a dot and a circle, it returns the nearest dot over the circle.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-circle-point [v1.0]

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 };
};