Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created April 14, 2012 00:48
Show Gist options
  • Save duncanbeevers/2381216 to your computer and use it in GitHub Desktop.
Save duncanbeevers/2381216 to your computer and use it in GitHub Desktop.
Find the angle between the center of an element and a coordinate pair, or the center of another element
(($) ->
# Finds the angle between the center of the first element
# and the provided point, or the center of another element
degreesPerRadian = 180 / Math.PI
$.fn.angleTo = () ->
args = arguments
if 1 == args.length
target = $ args[0]
position = target.offset()
targetX = position.left + target.outerWidth() / 2
targetY = position.top + target.outerHeight() / 2
else
targetX = args[0]
targetY = args[1]
position = this.offset()
Math.atan2(
targetY - (position.top + this.outerHeight() / 2),
targetX - (position.left + this.outerWidth() / 2)
) * degreesPerRadian
$.fn.placeAtAngleTo = (element, angle, radius) ->
centerY = (element.outerHeight() - this.outerHeight()) / 2
centerX = (element.outerWidth() - this.outerWidth()) / 2
offsetX = centerX + Math.cos(angle / degreesPerRadian) * radius
offsetY = centerY + Math.sin(angle / degreesPerRadian) * radius
css = {
left: offsetX + "px",
top: offsetY + "px"
}
this.css(css)
)(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment