Last active
May 15, 2020 08:53
-
-
Save andion/06dea5e617440049b706c5782f8b627d to your computer and use it in GitHub Desktop.
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
// Function that gets the drawImage required parameters to | |
// crop a square of the 50% of the image from its center | |
const getDrawImageParams = image => { | |
const {naturalWidth: imageWidth, naturalHeight: imageHeight} = image; | |
return { | |
sx: imageWidth / 4, | |
sy: imageHeight / 4, | |
sWidth: imageWidth / 2, | |
sHeight: imageHeight / 2, | |
dx: 0, | |
dy: 0, | |
dWidth: imageWidth / 2, | |
dHeight: imageHeight / 2, | |
}; | |
}; | |
// Get our canvas and image | |
const canvas = document.getElementById("canvas"); | |
const image = document.getElementById("source"); | |
const ctx = canvas.getContext("2d"); | |
// Get the params for this crop transformation | |
const {sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight} = getDrawImageParams(image); | |
// Set the canvas to the desired final size: the full destination size. | |
canvas.width = dWidth; | |
canvas.height = dHeight; | |
// Paste our cropped image using the params | |
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment