Skip to content

Instantly share code, notes, and snippets.

@fortunefox
Created January 16, 2023 00:48
Show Gist options
  • Save fortunefox/ff2bf3e8f1c83361c976c1da739186c0 to your computer and use it in GitHub Desktop.
Save fortunefox/ff2bf3e8f1c83361c976c1da739186c0 to your computer and use it in GitHub Desktop.
Code to automatically resize and crop a picture in your browser using canvas and javascript.
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', handleImage);
function handleImage(event) {
const file = event.target.files[0];
const img = new Image();
img.src = URL.createObjectURL(file);
img.addEventListener('load', () => {
const { width, height } = img;
const size = Math.min(width, height);
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, (width - size) / 2, (height - size) / 2, size, size, 0, 0, size, size);
const resizedCanvas = document.createElement('canvas');
resizedCanvas.width = 100;
resizedCanvas.height = 100;
const resizedCtx = resizedCanvas.getContext('2d');
resizedCtx.drawImage(canvas, 0, 0, 100, 100);
const dataUrl = resizedCanvas.toDataURL();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment