Skip to content

Instantly share code, notes, and snippets.

@ameliemaia
Created September 8, 2017 15:26
Show Gist options
  • Save ameliemaia/0540e700a6ec2b965e5d0ebf45f5464b to your computer and use it in GitHub Desktop.
Save ameliemaia/0540e700a6ec2b965e5d0ebf45f5464b to your computer and use it in GitHub Desktop.
Util =
calculate_resize: (image_width, image_height, win_width, win_height) ->
window_ratio = win_width / win_height
image_ratio1 = image_width / image_height
image_ratio2 = image_height / image_width
if window_ratio < image_ratio1
new_height = win_height
new_width = Math.round( new_height * image_ratio1 )
new_top = 0
new_left = (win_width * .5) - (new_width * .5)
else
new_width = win_width
new_height = Math.round( new_width * image_ratio2 );
new_top = (win_height * .5) - (new_height * .5)
new_left = 0
return {
x : new_left
y : new_top
width : new_width
height : new_height
}
###
Resize image(s) to the browser size retaining aspect ratio
@param [jQuery] $images
@param [Number] image_width
@param [Number] image_height
@param [Number] win_width
@param [Number] win_width
@param [Boolean] backgroundsize
###
resize: (image, image_width, image_height, win_width, win_height) ->
data = @calculate_resize image_width, image_height, win_width, win_height
image.style.marginTop = "#{data.y}px"
image.style.marginLeft = "#{data.x}px"
image.style.width = "#{data.width}px"
image.style.height = "#{data.height}px"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment