Created
November 26, 2019 15:14
-
-
Save codeBelt/8849ccf37cef2935d0be0ace49852e9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} url - The source image | |
* @param {number} aspectRatio - The aspect ratio | |
* @return {Promise<HTMLCanvasElement>} A Promise that resolves with the resulting image as a canvas element | |
*/ | |
function crop(url, aspectRatio) { | |
// we return a Promise that gets resolved with our canvas element | |
return new Promise(resolve => { | |
// this image will hold our source image data | |
const inputImage = new Image(); | |
// we want to wait for our image to load | |
inputImage.onload = () => { | |
// let's store the width and height of our image | |
const inputWidth = inputImage.naturalWidth; | |
const inputHeight = inputImage.naturalHeight; | |
// get the aspect ratio of the input image | |
const inputImageAspectRatio = inputWidth / inputHeight; | |
// if it's bigger than our target aspect ratio | |
let outputWidth = inputWidth; | |
let outputHeight = inputHeight; | |
if (inputImageAspectRatio > aspectRatio) { | |
outputWidth = inputHeight * aspectRatio; | |
} else if (inputImageAspectRatio < aspectRatio) { | |
outputHeight = inputHeight / aspectRatio; | |
} | |
// calculate the position to draw the image at | |
const outputX = (outputWidth - inputWidth) * .5; | |
const outputY = (outputHeight - inputHeight) * .5; | |
// create a canvas that will present the output image | |
const outputImage = document.createElement('canvas'); | |
// set it to the same size as the image | |
outputImage.width = outputWidth; | |
outputImage.height = outputHeight; | |
// draw our image at position 0, 0 on the canvas | |
const ctx = outputImage.getContext('2d'); | |
ctx.drawImage(inputImage, outputX, outputY); | |
resolve(outputImage); | |
}; | |
// start loading our image | |
inputImage.src = url; | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment