Skip to content

Instantly share code, notes, and snippets.

@grandsilence
Last active February 5, 2019 23:44
Show Gist options
  • Save grandsilence/daad7261276155049776835b021c0b43 to your computer and use it in GitHub Desktop.
Save grandsilence/daad7261276155049776835b021c0b43 to your computer and use it in GitHub Desktop.
Conserve aspect ratio image
/**
* 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