Crop images to any aspect ratio in the browser with Canvas (no upload)
Cropping an image to 1:1, 4:5 or 16:9 sounds like a job for a server, but the browser can do it on its own. Here's a small, dependency-free way to crop an image to any aspect ratio with the Canvas API. The file never lea
Cropping an image to 1:1, 4:5 or 16:9 sounds like a job for a server, but the browser can do it on its own. Here's a small, dependency-free way to crop an image to any aspect ratio with the Canvas API. The file never leaves the user's device.
The idea
- Compare the image's ratio with the target ratio.
- If the image is too wide, trim the sides. If it's too tall, trim the top and bottom.
- Draw the cropped area onto a canvas and export it.
The Code
async function cropToRatio(file, ratioW, ratioH, maxWidth = 1080) {
const bitmap = await createImageBitmap(file);
const targetRatio = ratioW / ratioH;
const srcRatio = bitmap.width / bitmap.height;
let sx = 0, sy = 0, sw = bitmap.width, sh = bitmap.height;
if (srcRatio > targetRatio) {
// too wide: trim left and right
sw = Math.round(bitmap.height * targetRatio);
sx = Math.round((bitmap.width - sw) / 2);
} else {
// too tall: trim top and bottom
sh = Math.round(bitmap.width / targetRatio);
sy = Math.round((bitmap.height - sh) / 2);
}
const outW = Math.min(sw, maxWidth);
const outH = Math.round(outW / targetRatio);
const canvas = document.createElement('canvas');
canvas.width = outW;
canvas.height = outH;
canvas.getContext('2d').drawImage(bitmap, sx, sy, sw, sh, 0, 0, outW, outH);
return new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.92));
}
Using it
const input = document.querySelector('input[type="file"]');
const preview = document.querySelector('img');
input.addEventListener('change', async () => {
const blob = await cropToRatio(input.files[0], 4, 5); // 4:5 → 1080×1350
preview.src = URL.createObjectURL(blob);
});
Bonus: work out a ratio from pixel sizes
const gcd = (a, b) => (b ? gcd(b, a % b) : a);
const ratio = (w, h) => {
const g = gcd(w, h);
return `${w / g}:${h / g}`;
};
ratio(1080, 1350); // "4:5"
ratio(1920, 1080); // "16:9"
A few gotchas
- Center crop isn't always right. If faces or text sit off-center, let the user drag the crop box instead of cropping automatically.
- Phone photos can be rotated by EXIF data. Test with real photos from a phone in the browsers you support.
- Watch the JPEG quality. 0.92 is a good default. Lower it if you need a smaller file, for example when a form portal limits uploads to 50 KB.
- Huge images eat memory. Downscale first if you expect 20+ megapixel photos.
Why do it client-side?
No upload means no server cost, no waiting on a network, and nothing private ever leaves the device. You can check it yourself: open DevTools → Network tab and watch while the code runs.
I put this into a free tool if you want to see it working: GetTaskCraft image cropper. I also wrote a longer reference on common sizes: aspect ratios explained.
What would you add? Drag-to-crop, a ratio presets list, or EXIF handling? Let me know in the comments.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.