Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save bolerap/a7fe3241f2ede28faf62c94052abafef to your computer and use it in GitHub Desktop.

Select an option

Save bolerap/a7fe3241f2ede28faf62c94052abafef to your computer and use it in GitHub Desktop.
// helper functions
private resizeImage(img, maxWidth, maxHeight, callback) {
return img.onload = () => {
// get image dimension
let width = img.width;
let height = img.height;
// set width and height to the max values
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
// create canvas object
let canvas = document.createElement('canvas');
// set canvas to the new calculated dimension values
canvas.width = maxWidth;
canvas.height = maxHeight;
// create canvas context 2d and align image to center
let startX = maxWidth / 2 - width / 2;
let startY = maxHeight / 2 - height / 2;
let ctx = canvas.getContext('2d', {alpha: false});
// draw image to canvas
ctx.drawImage(img, startX, startY, width, height);
// convert canvas to image
let dataUrl = canvas.toDataURL('image/jpeg');
// run callback with result
callback(dataUrl);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment