Last active
August 29, 2015 14:16
-
-
Save ethyde/55e2d1ca1393dd34d2a7 to your computer and use it in GitHub Desktop.
jQuery plugin keep image ratio
source : http://stackoverflow.com/a/1682739
https://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
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
/** | |
* 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 }; | |
}, |
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
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