Skip to content

Instantly share code, notes, and snippets.

@wilkerlucio
Created March 5, 2014 21:22
Show Gist options
  • Select an option

  • Save wilkerlucio/9376869 to your computer and use it in GitHub Desktop.

Select an option

Save wilkerlucio/9376869 to your computer and use it in GitHub Desktop.
class @Rectangle
@fromClientRect: (clientRect) ->
new Rectangle(
clientRect.left
clientRect.top
clientRect.right - clientRect.left
clientRect.bottom - clientRect.top)
@fromNode: (node) ->
{left, top} = node.offset()
left += parseInt(node.css("marginLeft") || 0)
top += parseInt(node.css("marginTop") || 0)
width = node.outerWidth()
height = node.outerHeight()
new Rectangle(left, top, width, height)
@surround: (rectangles) ->
return new Rectangle(0, 0, 0, 0) unless rectangles.length > 0
_.tap rectangles.shift(), (rect) ->
for r in rectangles
if r.left < rect.left
rect.width += rect.left - r.left
rect.left = r.left
if r.top < rect.top
rect.height += rect.top - r.top
rect.top = r.top
rect.width = Math.max(rect.left + rect.width, r.left + r.width) - rect.left
rect.height = Math.max(rect.top + rect.height, r.top + r.height) - rect.top
constructor: (@left, @top, @width, @height) ->
expand: (amount) ->
yamount = amount / @width * @height
new Rectangle(
@left - amount
@top - yamount
@width + amount * 2
@height + yamount * 2
)
fitIn: (rectangle) ->
newRectangle = new Rectangle(@left, @top, @width, @height)
factor = rectangle.width / rectangle.height
boundsFactor = @width / @height
if factor > boundsFactor
newWidth = @height * factor
newRectangle.left -= (newWidth - @width) / 2
newRectangle.width = newWidth
else
factor = rectangle.height / rectangle.width
newHeight = @width * factor
newRectangle.top -= (newHeight - @height) / 2
newRectangle.height = @width * factor
newRectangle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment