Skip to content

Instantly share code, notes, and snippets.

@andion
Last active May 17, 2020 07:53
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/4fc2cd20b5947ae007e58e363428100d to your computer and use it in GitHub Desktop.
Save andion/4fc2cd20b5947ae007e58e363428100d to your computer and use it in GitHub Desktop.
// Function that returns `drawImage`'s params and the canvas size
// to change an image from its original aspect ratio to a new one
// filling the excess or cropping it.
//
// It needs the image's `originalWidth` and `originalHeight`
// and the desired resulting `transformedRatio`
//
// It returns the parameters that `drawImage` needs:
// * To get the portion of the image from the original (`sx`, `sy`, `sWidth`, `sHeight`)
// * To "paste" that portion of the image on the new format (`dx`, `dy`, `dWidth`, `dHeight`)
//
// And the size of the resulting canvas (`canvasWidth`, `canvasHeight`)
//
const getAspectRatioCropParams = (originalWidth, originalHeight, transformedRatio, fill = false) => {
// Initial data, if the image does not change aspect it stays like this.
let sx = 0;
let sy = 0;
let sWidth = originalWidth;
let sHeight = originalHeight;
let dx = 0;
let dy = 0;
let dWidth = originalWidth;
let dHeight = originalHeight;
let canvasWidth = originalWidth;
let canvasHeight = originalHeight;
const originalRatio = originalWidth / originalHeight;
if (originalRatio > transformedRatio) {
if(fill) {
canvasHeight = originalWidth / transformedRatio;
dy = Math.abs(canvasHeight - originalHeight) / 2;
} else {
sWidth = originalWidth * transformedRatio;
canvasWidth = sWidth;
dWidth = sWidth;
sx = Math.abs(originalWidth - sWidth) / 2;
}
}
if (originalRatio < transformedRatio) {
if(fill) {
canvasWidth = originalHeight * transformedRatio;
dx = Math.abs(canvasWidth - originalWidth) / 2;
} else {
sHeight = originalWidth / transformedRatio;
canvasHeight = sHeight;
dHeight = sHeight;
sy = Math.abs(originalHeight - sHeight) / 2;
}
}
return {
sx,
sy,
sWidth,
sHeight,
dx,
dy,
dWidth,
dHeight,
canvasWidth,
canvasHeight
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment