Skip to content

Instantly share code, notes, and snippets.

@dggodfrey
Last active December 26, 2015 19:19
Show Gist options
  • Save dggodfrey/7200280 to your computer and use it in GitHub Desktop.
Save dggodfrey/7200280 to your computer and use it in GitHub Desktop.
Simple way to determine the correct dimensions of an image taking into account a max height/width
/**
* 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} maxHeight Fittable area maximum available height
* @return {Object} { width, heigth }
*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = [maxWidth / srcWidth, maxHeight / srcHeight ];
ratio = Math.min(ratio[0], ratio[1]);
return { width:srcWidth*ratio, height:srcHeight*ratio };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment