Last active
May 3, 2023 10:31
-
-
Save denyherianto/8ac00d3f598c8594883e6d789c72a3b0 to your computer and use it in GitHub Desktop.
Crop Image using Canvas Javascript
This file contains hidden or 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
| type TCropImageParams = { | |
| url: string | |
| width: number | |
| height: number | |
| mime?: string | |
| quality?: number | |
| aspectRatio?: number | |
| } | |
| export const cropImage = async ({ | |
| url, | |
| width, | |
| height, | |
| mime = 'image/jpeg', | |
| quality = 0.8, | |
| aspectRatio = 1, | |
| }: TCropImageParams): Promise<Partial<Blob>> => { | |
| const inputImage = document.createElement('img') | |
| const promise = new Promise((resolve, reject) => { | |
| 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 = inputWidth / aspectRatio | |
| } | |
| // calculate the position to draw the image at | |
| const outputX = (inputWidth - outputWidth) * 0.5 | |
| const outputY = (inputHeight - outputHeight) * 0.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 = width | |
| outputImage.height = height | |
| // draw our image at position 0, 0 on the canvas | |
| const ctx = outputImage.getContext('2d') | |
| ctx.drawImage( | |
| inputImage, | |
| outputX, | |
| outputY, | |
| outputWidth, | |
| outputHeight, | |
| 0, | |
| 0, | |
| width, | |
| height | |
| ) | |
| outputImage.toBlob(resolve, mime, quality) | |
| } | |
| // Reject promise on error | |
| inputImage.onerror = reject | |
| }) | |
| inputImage.src = url | |
| return promise | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment