Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created November 3, 2023 11:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattdesl/1486f656745d1a96db71542a33cd218b to your computer and use it in GitHub Desktop.
Save mattdesl/1486f656745d1a96db71542a33cd218b to your computer and use it in GitHub Desktop.
/**
* Conserve aspect ratio of the original region. Useful when shrinking/enlarging
* images to fit into a certain area.
*
* @param {Number} srcWidth width of source image
* @param {Number} srcHeight height of source image
* @param {Number} maxWidth maximum available width
* @param {Number} maxHeight maximum available height
* @return {Object} { width, height }
*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
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