Last active
May 15, 2020 08:43
-
-
Save andion/dd805d0ce288cdea187b7cf8df020063 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 | |
// resize an image by a scale | |
const getDrawImageParams = (image, scale) => { | |
const {naturalWidth: imageWidth, naturalHeight: imageHeight} = image; | |
return { | |
sx: 0, | |
sy: 0, | |
sWidth: imageWidth, | |
sHeight: imageHeight, | |
dx: 0, | |
dy: 0, | |
dWidth: imageWidth * scale, | |
dHeight: imageHeight * scale, | |
}; | |
}; | |
// 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 resize transformation, we try to get an image half the size | |
const scale = 0.5; | |
const {sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight} = getDrawImageParams(image, scale); | |
// Set the canvas to the resulting "destination" size | |
canvas.width = dWidth; | |
canvas.height = dHeight; | |
// Paste our resized 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