Skip to content

Instantly share code, notes, and snippets.

@hyeonseok
Created January 20, 2016 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyeonseok/6c2ea82af60a313a5c5e to your computer and use it in GitHub Desktop.
Save hyeonseok/6c2ea82af60a313a5c5e to your computer and use it in GitHub Desktop.
Fit image to the container while cropping given ratio.
_setPhotoSize: function($image) {
var cropPortion = 1.2,
imageWidth = $image.width(),
imageHeight = $image.height(),
imageRatio = imageWidth / imageHeight,
windowWidth = LayoutManager().getScreenWidth(),
windowHeight = LayoutManager().getScreenHeight(),
windowRatio = windowWidth / windowHeight,
width, height, top = 0, left = 0;
if (windowRatio / imageRatio > cropPortion) {
height = windowHeight * cropPortion;
width = height * imageRatio;
top = (height - windowHeight) / -2;
} else if (windowRatio / imageRatio > 1) {
width = windowWidth;
height = width / imageRatio;
top = (height - windowHeight) / -2;
} else if (windowRatio / imageRatio > 1 / cropPortion) {
height = windowHeight;
width = height * imageRatio;
left = (width - windowWidth) / -2;
} else {
width = windowWidth * cropPortion;
height = width / imageRatio;
top = (windowHeight - height) / 2;
left = (windowWidth - width) / 2;
}
$image.css({
width: width + 'px',
height: height + 'px',
top: top + 'px',
left: left + 'px'
}).addClass('on');
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment