Skip to content

Instantly share code, notes, and snippets.

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