Skip to content

Instantly share code, notes, and snippets.

@andion
Last active May 15, 2020 08:43
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/dd805d0ce288cdea187b7cf8df020063 to your computer and use it in GitHub Desktop.
Save andion/dd805d0ce288cdea187b7cf8df020063 to your computer and use it in GitHub Desktop.
// 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