Every "put your photo into this scene" feature starts with the same small lie: the user uploads a 4032x3024 phone photo, and you quietly promise it will fit a 540x960 vertical frame. Nothing about those two rectangles is compatible. Something has to give.

CSS solves this with one line. Canvas — which is where you end up if you need to overlay a caption, animate the result, or export a video — gives you no such line. Here is the arithmetic I use, plus the four bugs that show up right after you get the arithmetic right.

1. cover is one scale and two offsets

object-fit: cover means: scale until the source covers the destination on both axes, then crop the overflow. The scale factor is the larger of the two ratios:

function coverRect(sw, sh, dw, dh, fx = 0.5, fy = 0.5) { const s = Math.max(dw / sw, dh / sh); const w = sw * s; const h = sh * s; return { sx: 0, sy: 0, sw, sh, // source rectangle dx: fx * (dw - w), // negative: cropped off the left/top dy: fy * (dh - h), dw: w, dh: h // destination rectangle }; } 

The offsets are negative by construction, which is exactly what you want: part of the scaled image sits outside the frame. fx = fy = 0.5 centers the crop. Move fx toward 0 or 1 to bias toward an edge — useful when the subject is off-center.

object-fit cover illustrated as a scale factor and two offsets

The diagram links to a browser tool that applies this same math to photo-based meme videos.

Using Math.min here is the classic mistake. That gives you contain, not cover, and you get letterbox bars where a photo should be.

2. Decode with the EXIF orientation respected

Phone photos carry an orientation tag. The raw pixels may be stored rotated 90 degrees, with the tag telling the viewer how to turn them back. createImageBitmap lets you apply that at decode time instead of discovering it after export:

const blob = await fetch(url).then(r => r.blob()); const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image', resizeQuality: 'high' }); const { width, height } = bitmap; // already in display orientation 

If you skip this, your landscape photo renders sideways in the canvas but looks fine in an <img> tag — a particularly confusing bug because the two paths disagree.

3. Separate CSS pixels from output pixels

A canvas has two sizes: its attribute size (real pixels) and its style size (layout pixels). For a 540x960 export on a retina display, set the backing store to the output resolution and scale the context once:

const OUT = { w: 540, h: 960 }; canvas.width = OUT.w * 2; canvas.height = OUT.h * 2; ctx.setTransform(2, 0, 0, 2, 0, 0); // draw in CSS pixels, render at 2x 

Do not use window.devicePixelRatio for an export. It makes the output size depend on which machine renders it, so the same project produces different files on a laptop and a phone. Export dimensions should be an explicit parameter.

4. Mask by clipping, not by painting over

To fit the photo into a rounded or shaped scene, clip before drawing. Painting a mask-colored shape after the photo only works if the background is flat:

ctx.save(); ctx.beginPath(); ctx.roundRect(0, 0, dw, dh, 24); ctx.clip(); ctx.drawImage(bitmap, dx, dy, scaledW, scaledH); ctx.restore(); 

One detail people miss: ctx.clip() is cumulative within a save/restore block. Every extra layer — caption, stickers — needs its own save()/restore(), or the previous clip will silently cut it off too.

5. Decode once, not once per frame

If this ends up in an animated scene, decoding the upload inside the render loop will tank framerate. Decode to an ImageBitmap once, reuse it for every frame, and close it when the project changes:

let bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }); // ... render many frames ... bitmap.close(); // release decoded pixels 

Also revoke any object URLs you created with URL.revokeObjectURL; otherwise every new upload leaks the previous one.

6. Export at a fixed frame rate

When you encode the result, drive frames by index rather than by elapsed wall-clock time:

const fps = 30; for (let f = 0; f < totalFrames; f++) { const t = f / fps; // deterministic, reproducible renderFrame(t); await nextFrame(); encoder.add(frameFrom(canvas)); } 

This matters more than it sounds: timestamp-driven loops produce different frame counts on different machines and subtly uneven motion. Index-driven ones are reproducible, which also makes debugging a specific frame possible.

When the scene is the point

None of the above is hard, but it is a lot of plumbing before you get to the part you actually care about — the scene and the joke. TokMeme is a browser tool for exactly this: pick a scene, upload a photo, and get a short meme video without writing the cover math, orientation fixes, or encoder yourself.

The code here is still worth knowing even if you never ship it. Once you see a "photo in a frame" feature as scale plus two offsets, most of the canvas layout problems behind it stop being mysterious.

Disclosure: I work on TokMeme. The code above is plain Canvas/Web API and does not depend on the tool.