Skip to content

Instantly share code, notes, and snippets.

@ethyde
Last active August 29, 2015 14:16
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 ethyde/55e2d1ca1393dd34d2a7 to your computer and use it in GitHub Desktop.
Save ethyde/55e2d1ca1393dd34d2a7 to your computer and use it in GitHub Desktop.
/**
* Resize arbitary width x height region to fit inside another region.
*
* Conserve aspect ratio of the orignal region. Useful when shrinking/enlarging
* images to fit into a certain area.
*
* @param {Number} srcWidth Source area width
*
* @param {Number} srcHeight Source area height
*
* @param {Number} maxWidth Fittable area maximum available width
*
* @param {Number} srcWidth Fittable area maximum available height
*
* @return {Object} { width, heigth }
*
*/
calculateAspectRatioFit : function(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = [maxWidth / srcWidth, maxHeight / srcHeight ];
ratio = Math.min(ratio[0], ratio[1]);
return { width:srcWidth*ratio, height:srcHeight*ratio };
},
jQuery.fn.fitToParent = function(){
this.each(function(){
var width = $(this).width(),
height = $(this).height(),
parentWidth = $(this).parent().width(),
parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight){
newWidth = parentWidth;
newHeight = newWidth/width*height;
} else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
margin_top = (parentHeight - newHeight) / 2;
margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment