Building a photo editor in the browser that stays smooth
How to build a fast in-browser photo editor: working copies, layers, accurate cropping, a custom crop box, filters, rendering and full-quality export.
Most chat apps let you touch up a photo before you send it: crop it, rotate it, add a filter, write on it, stick an emoji on it. It looks like a small feature. In the browser it's one of the easiest to get wrong. Editors lag on big photos, crops come out blurry or slightly off, text turns fuzzy when the image is saved, and phones run out of memory.
I went through three crop libraries and a canvas library before mine felt smooth. What fixed it in the end wasn't another library. It was understanding a few ideas and owning those parts myself. This post walks through them.
Three sizes of the same photo
The most useful idea in this whole post: an editor works with the same photo at three different sizes, and every number in your code belongs to one of them.
- The original comes from the camera. Phones take 12 to 48 megapixel photos, so 8000 × 6000 isn't unusual.
- The working copy is a smaller version the editor actually uses, capped at something like 4096 pixels on the long side. Every edit is applied to this.
- The on-screen version is the working copy drawn to fit the editor, maybe 800 pixels wide.
When the user drags a crop box or places a sticker, they do it in on-screen pixels. When you cut or save, you need working-copy pixels. Most "the crop is slightly off" and "the export is blurry" bugs are a number from one size used as if it were from another.
Shrink the photo before editing it
A canvas holds every pixel in memory, four bytes each. A 48 megapixel photo is about 190 MB as a canvas, before you've done anything to it. Phones struggle with that, and Safari on iPhone has long limited a canvas to about 16.7 million pixels (4096 × 4096). Go over it and drawing can fail without an error.
So make the working copy once, as soon as the photo is picked:
const MAX_EDGE = 4096;
async function makeWorkingCopy(file) {
const bitmap = await createImageBitmap(file); // decodes the image
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
const canvas = document.createElement("canvas");
canvas.width = Math.round(bitmap.width * scale);
canvas.height = Math.round(bitmap.height * scale);
const ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high"; // smoother downscaling
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
bitmap.close(); // free the full-size pixels right away
return canvas;
}
4096 is still plenty for a chat photo. Most chat apps compress images further when sending anyway.
Two related gotchas:
- Photos from other websites need
crossOrigin. If you load an image from another domain withoutimg.crossOrigin = "anonymous"(and the server allowing it), the canvas becomes "tainted" and saving it throws a security error. - Don't rotate phone photos yourself. Phones store photos sideways with a note saying which way is up. Modern browsers read that note and draw the photo the right way round, so older code that rotates it manually now rotates it twice.
Keep edits on layers
The tempting approach is to paint every edit straight onto the photo: draw the text into the pixels, then the sticker, then the scribble. It works until the user wants to move the text, change its colour or undo the sticker. Once something is painted into the pixels, it can't be taken back out.
Keep each edit as its own object instead, stacked on top of the photo. The photo stays untouched underneath, and filters are stored as settings ("brightness +10") rather than applied for good.
Canvas libraries such as Fabric.js and Konva are built around this idea. They give you objects you can select, drag, resize and rotate, and they redraw the scene for you. That's the part worth taking from a library. Writing selection handles and hit-testing for rotated text yourself is a lot of work.
Undo also gets easier with layers. Save a snapshot of the objects and settings after each change, not the pixels, and undo becomes "go back to the previous snapshot".
Cropping in the photo's own pixels
The crop box is drawn on screen, so its numbers are screen pixels. If you cut using those numbers directly, you get a tiny, blurry image, or the wrong part of the photo.
Convert first. Divide the photo's real width by its width on screen, and multiply the crop box by that:
function cropToPhotoPixels(crop, shownWidth, photo) {
const scale = photo.width / shownWidth; // e.g. 4000 / 400 = 10
return {
x: Math.round(crop.x * scale),
y: Math.round(crop.y * scale),
width: Math.round(crop.width * scale),
height: Math.round(crop.height * scale),
};
}
// Cut from the full-size photo, not from the canvas on screen.
const r = cropToPhotoPixels(crop, shownWidth, photo);
const out = document.createElement("canvas");
out.width = r.width;
out.height = r.height;
out.getContext("2d").drawImage(photo, r.x, r.y, r.width, r.height, 0, 0, r.width, r.height);
Round the numbers and keep them inside the photo, so a box dragged to the very edge doesn't ask for a pixel that isn't there.
Building the crop box yourself
This is where the libraries let me down the most. Crop components each bring their own idea of layout, sizing and touch handling, and inside a modal, next to a canvas library, on a phone, they kept fighting the rest of the editor. A crop box is a rectangle with eight handles, and building one yourself is less code than working around one that doesn't fit.
The rules that make it feel right:
- Use pointer events (
pointerdown,pointermove,pointerup). They cover mouse, touch and pen in one place. CallsetPointerCaptureonpointerdown, so the drag keeps working when the finger slides off the handle. - Set
touch-action: noneon the crop area, or the page scrolls while the user drags a handle on a phone. - Move from the anchor. When a corner is dragged, the opposite corner stays fixed. Work out the new box from the anchor and the pointer, rather than adding up small movements, which drift.
- Clamp everything. The box never leaves the photo and never gets smaller than a minimum size (around 48 pixels on screen, big enough to grab).
- Store the box as fractions of the photo (0.2 from the left, 0.5 wide), not as pixels. When the window resizes and the photo is redrawn at a new size, the crop stays in the same place.
// Dragging the bottom-right handle: the top-left corner is the anchor.
function resizeFromCorner(start, dx, dy, bounds, minSize = 48) {
const right = clamp(start.x + start.width + dx, start.x + minSize, bounds.width);
const bottom = clamp(start.y + start.height + dy, start.y + minSize, bounds.height);
return { x: start.x, y: start.y, width: right - start.x, height: bottom - start.y };
}
const clamp = (v, min, max) => Math.min(Math.max(v, min), max);
start is the box when the drag began, and dx, dy are how far the pointer has moved since then. Always measuring from the start of the drag is what keeps the corner exactly under the finger.
With a fixed aspect ratio such as 1:1 or 16:9, do the same thing, then shrink whichever side is too long so the ratio holds. The anchor stays put either way.
Filters you can change your mind about
Brightness, contrast and saturation sliders should feel instant, and the user should be able to move them back.
- Keep the slider values, not the filtered pixels. Every time a slider moves, apply the full set of values to the untouched photo again. If you apply each change on top of the last result, moving a slider back and forth slowly wrecks the image.
- Apply on the next frame, not on every input event. A slider can fire dozens of events a second. Record the latest value and apply it once per animation frame (more on that next).
- Presets are just saved slider values. "Warm" might be a little more brightness and saturation. Choosing a preset sets the sliders, so the user can still adjust from there.
Drawing only when something changed
A lot of editor lag comes from redrawing the canvas far more often than needed: once for every object added, once for every pointer move, once for every slider event. The screen only updates about 60 times a second, so draw at most once per frame:
let frame = null;
function scheduleRender() {
if (frame !== null) return; // already queued for this frame
frame = requestAnimationFrame(() => {
frame = null;
render();
});
}
Call scheduleRender() from anywhere, as often as you like, and it still draws once. If your canvas library redraws on every change by itself (Fabric.js has a renderOnAddRemove option), turn that off and use this instead.
The same goes for resizing. Watch the editor's container with a ResizeObserver, and when it changes size, resize the canvas and fit the photo again, once per frame.
Exporting at full quality
The canvas on screen is small, so saving it directly gives you an 800-pixel image with fuzzy text. Instead, redraw the scene on a full-size canvas. Every object's position and size is multiplied by the same factor: the working copy's width divided by the width on screen.
Because text, stickers and drawings are objects rather than pixels, they're redrawn sharp at the bigger size. Many canvas libraries can do this for you: Fabric.js, for example, takes a multiplier option when exporting.
Then turn the canvas into a file:
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
const file = new File([blob], "photo.jpg", { type: "image/jpeg" });
Use toBlob rather than toDataURL. A data URL is the image as a long text string, about a third bigger than the file, and making it holds everything up while it's built. toBlob hands you a real file, ready to upload.
Cleaning up
Image editors leak memory quietly. Each photo the user opens can hold tens of megabytes, and if nothing is freed, the tab gets slower with every photo until a phone gives up. Free things as soon as you're done with them:
URL.revokeObjectURL(url)for everyURL.createObjectURLyou made for a preview.bitmap.close()for everyImageBitmap.- Dispose of canvases your library created (
canvas.dispose()in Fabric.js), and drop references to big canvases you made yourself. - Remove listeners such as the
ResizeObserverwhen the editor closes.
A checklist
- Know which of the three sizes every number belongs to: original, working copy or on screen.
- Make a working copy capped around 4096 pixels as soon as the photo is picked.
- Keep text, stickers and drawings as objects above the photo, and filters as settings.
- Convert the crop box to the photo's own pixels before cutting, and cut from the full-size photo.
- Build the crop box with pointer events, an anchor corner, clamping, and positions stored as fractions.
- Re-apply filters from the original on each change, once per frame.
- Batch drawing with
requestAnimationFrame. - Export by redrawing at full size, with
toBlob. - Revoke object URLs, close bitmaps and dispose of canvases when you're done.