Over a million developers have joined DZone.

Closest Circle Point //JavaScript Function

·

Given a dot and a circle, it returns the nearest dot over the circle.

[UPDATED CODE AND HELP CAN BE FOUND HERE]




//+ 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 };
};
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}