Skip to content

Instantly share code, notes, and snippets.

@andion
Last active May 15, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andion/773ae15087885cfd6935dc1287993af2 to your computer and use it in GitHub Desktop.
Save andion/773ae15087885cfd6935dc1287993af2 to your computer and use it in GitHub Desktop.
// Function that gets the area of the original image to crop
// depending on the aspect ratio to transform it toratioWidth:H
const getAspectRatioParams = (sourceWidth, sourceHeight, destinationWidth, destinationHeight) => {
let width = sourceWidth;
let height = sourceHeight;
let x = 0;
let y = 0;
const imageRatio = sourceWidth / sourceHeight;
const cropRatio = destinationWidth / destinationHeight;
if (imageRatio > cropRatio) {
width = (sourceHeight * destinationWidth) / destinationHeight;
x = (sourceWidth - width) / 2;
}
if (imageRatio < cropRatio) {
height = (sourceWidth * destinationHeight) / destinationWidth;
y = (sourceHeight - height) / 2;
}
return {
x,
y,
width,
height,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment