A few weeks ago I wrote a quick script to resize images in the browser, and the first version made every photo look slightly squashed. The bug was one line. Here's what I learned about canvas sizes, aspect ratios and image quality, so you can skip the squashed photos.

Aspect ratio in one minute

The aspect ratio is just width divided by height. A 1920 × 1080 image is 1920 / 1080 = 1.777..., which is the familiar 16:9.

To resize without distortion, both sides must change by the same scale factor:

newWidth = width × scale newHeight = height × scale 

If you set width and height independently, you get stretched faces and oval logos. If you only have one target number (say, "make it 800 px wide"), you calculate the other:

const newHeight = Math.round(newWidth * (height / width)); 

Canvas size is not CSS size

This tripped me up first. A canvas has two sizes:

  • canvas.width and canvas.height are the real pixel dimensions of the output.
  • CSS width and height only change how it's displayed on the page.

If you resize with CSS, nothing about the exported file changes. To get real pixels, set the attributes and draw into them:

canvas.width = newWidth; canvas.height = newHeight; ctx.drawImage(bitmap, 0, 0, newWidth, newHeight); 

A function that fits an image inside a box

Most of the time you don't want exact numbers. You want "no bigger than 1200 × 800, keep the shape". Pick the smaller of the two scale factors:

function fitWithin(srcW, srcH, maxW, maxH, allowUpscale = false) { let scale = Math.min(maxW / srcW, maxH / srcH); if (!allowUpscale) scale = Math.min(scale, 1); return { width: Math.max(1, Math.round(srcW * scale)), height: Math.max(1, Math.round(srcH * scale)), }; } 

Two small details matter here. Math.round avoids fractional pixels (which can produce blurry edges), and Math.max(1, ...) stops a very thin image from rounding down to zero.

The full resize

async function resizeImage(file, maxW, maxH, type = 'image/jpeg', quality = 0.9) { const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }); const { width, height } = fitWithin(bitmap.width, bitmap.height, maxW, maxH); const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; if (type === 'image/jpeg') { ctx.fillStyle = '#fff'; // JPEG has no transparency ctx.fillRect(0, 0, width, height); } ctx.drawImage(bitmap, 0, 0, width, height); bitmap.close(); return new Promise(resolve => canvas.toBlob(resolve, type, quality)); } 

Usage with a file input:

input.addEventListener('change', async () => { const blob = await resizeImage(input.files[0], 1200, 800); const url = URL.createObjectURL(blob); preview.src = url; }); 

Everything runs locally, so the image never leaves the device.

Image quality: what actually matters

1. Shrinking a lot in one step looks rough. If you go from 4000 px to 400 px in one draw, the result can look jagged. Halving repeatedly keeps it smoother:

async function stepDown(bitmap, targetW, targetH) { let current = bitmap; let w = bitmap.width; let h = bitmap.height; while (w / 2 > targetW) { w = Math.round(w / 2); h = Math.round(h / 2); const c = document.createElement('canvas'); c.width = w; c.height = h; const cctx = c.getContext('2d'); cctx.imageSmoothingQuality = 'high'; cctx.drawImage(current, 0, 0, w, h); current = c; } return current; // then draw this into the final canvas } 

2. Upscaling can't add detail. Making a small image bigger only invents pixels. If you can, start from a larger source.

3. Pick the right format. JPEG is smaller for photos, PNG keeps sharp edges and transparency, and WebP is often smaller than both. The quality argument only applies to JPEG and WebP, not PNG.

4. Phone photos have rotation metadata. That's what imageOrientation: 'from-image' handles. Without it, some photos come out sideways.

5. Memory. A 40-megapixel image decoded into a canvas uses a lot of RAM, and mobile browsers may fail on very large files. Limit the input size and show a clear message.

The mistake that squashed my photos

I had set canvas.width = 800 and canvas.height = 600 for every image, regardless of the original shape. Anything that wasn't 4:3 got stretched. Calculating one side from the other, or using fitWithin, fixed it.

If you just want to try it

I put these ideas into a small, free tool: the Image Resize Calculator. You pick an image, lock the aspect ratio, set the size by pixels or percentage, and export as PNG, JPEG or WebP. It runs in your browser and doesn't upload the file. If you only need the ratio math (like what 1920 × 1080 scales to at 50%), the 16:9 aspect ratio calculator shows common sizes.

Recap

  • Keep the same scale factor on width and height.
  • Set canvas.width and canvas.height, not just CSS.
  • Round to whole pixels and guard against zero.
  • Step down for big reductions, and don't expect upscaling to add detail.
  • Handle orientation, transparency and memory limits.

If you've found a better approach, tell me in the comments.