Last active
December 21, 2015 16:37
-
-
Save willbroderick/83b753147565d3a9927c to your computer and use it in GitHub Desktop.
Wraps an image with a fixed-ratio div and scales/translates the image to fill. Uses % CSS so no resize events needed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Crop and scale images to a specific ratio | |
$.fn.cropImageToRatio = function(params){ | |
//params | |
var params = $.extend({ | |
ratio: 4/3, | |
wrapper: '<div/>' | |
}, params); | |
//loop all images | |
return $(this).each(function(){ | |
//only allow init once | |
if(typeof $(this).data('imgratio') == 'undefined') { | |
//save ratios | |
var imgRatio = $(this).width() / $(this).height(), | |
viewRatio = params.ratio; | |
//padding-top is calculated from container width | |
var padScalar = $(this).width() / $(this).parent().width(); | |
$(this).data('imgratio', imgRatio); | |
$(this).css({ //img css | |
position: 'absolute', | |
maxWidth: 'none', | |
maxHeight: 'none' | |
}).wrap(params.wrapper).parent().css({ //viewport css | |
height: 0, | |
paddingTop: 100 / params.ratio * padScalar + '%', | |
overflow: 'hidden', | |
position: 'relative' | |
}); | |
//set image size and offset | |
if(imgRatio < viewRatio) { | |
$(this).css({ | |
top: - (viewRatio / (imgRatio * 2) - 0.5) * 100 + '%', | |
left: 0, | |
width: '100%', | |
height: 'auto' | |
}); | |
} else { | |
$(this).css({ | |
top: 0, | |
left: - (imgRatio / (viewRatio * 2) - 0.5) * 100 + '%', | |
width: 'auto', | |
height: '100%' | |
}); | |
} | |
} | |
}); | |
}; | |
//Example use. | |
//note: images must be loaded first, and it must be called directly on img tags | |
$(window).on('load', function(){ | |
$('.article .header-image img').cropImageToRatio({ ratio: 16/9 }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment