This is one way to do it. As a bonus no ifs needed.
/**
* 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 };
},
Subscribe to this blog in a reader
Follow me on Twitter
Follow me on Facebook
Follow me Google+