Originally published on Medium. Read on Medium for free via Friend Link.
🎮 Try the Live Interactive Demo · 📦 GitHub Repo & Vitest Suite · ⚡ Get the TS 2D Canvas Physics Starter Kit
Try the Interactive Live Demo · Full TypeScript Source & Tests on GitHub
Quick takeaways
- With 5 moving objects out of 2,000, dirty-rectangle rendering cuts draws by up to 97%, processing 52.7 sprites per frame instead of 2,000.
- A ratio-based merge rule snowballs and inflates dirty area by a third; a fixed
maxWastepixel budget (2,000 px²) cuts clip regions by 40% while keeping dirty area at 12.5%. - Above 5% moving objects,
DirtyTrackerautomatically falls back to a full redraw (0.015 msoverhead) instead of burning44 msmerging rectangles. - A scrolling camera invalidates the entire screen every frame, so when the camera moves, skip dirty-rects and use layered canvases or frustum culling instead.
Every canvas demo I have built in this series starts its draw function with the exact same reflex: wiping the entire canvas clean.
// BEFORE — the opening line of most demos in this series.
// Still present in full-redraw mode (src/main.ts), absent on the dirty-rect path.
ctx.clearRect(0, 0, canvas.width, canvas.height);
It was there in the 2D physics engine and the Part 4 object pool demo (painting over with fillRect), and it stayed unchanged in the HiDPI Retina canvas and the fixed timestep loop. It becomes muscle memory: start the frame, wipe everything, redraw everything. Nobody questions it because it works.
I finally stopped in front of that line while building an inventory screen. There were over 300 item slots on screen, and every single one of them was sitting completely still except the one I was dragging with my mouse. For that single dragged slot, I was redrawing all 300 items every frame.
Imagine spilling a single drop of coffee in the kitchen and then wiping the entire table, the chairs, the countertops, and the cabinet doors from scratch, 60 times a second.
We can break that reflex and wipe only the spots that actually got dirty.
Wiping everything every frame
Putting a number on the bill makes the wasted work concrete.
A typical Canvas 2D frame pays two costs. The first is pixel cost: clearRect and every fillRect or drawImage writes pixels to be composited on the GPU. Even a modest 640×360 canvas is 230,400 pixels per frame, and on a Retina display with devicePixelRatio = 2, that jumps fourfold.
The second is call cost: the save, translate, beginPath, fill, and restore calls issued for every object. Canvas 2D pays a fixed overhead per draw call, and it scales linearly with object count.
In a scene with 2,000 objects where only 5 are moving, redrawing the other 1,995 buys us nothing. We write the exact same pixels to the exact same coordinates. The canvas content was already right; we erased it just so we could make it right again.
Canvas 2D gives us a guarantee we rarely cash in on: unless you call clearRect, the canvas is persistent. Anything you draw stays put until you erase it. Throughout this entire series, we threw that guarantee away and opened a blank page every frame. Dirty rectangle rendering is how you turn that persistence into performance.
The dirty region idea
The idea fits in one sentence: mark every region whose pixels may have changed during the frame, clear only those regions, and redraw only the objects that touch them.
Back to the kitchen table. If coffee spills in a four-inch spot on the top-left corner, you wipe that four-inch spot plus a finger's width of margin around it, and leave the rest of the table alone.
First, we need a rectangle type and pure geometry helpers. This entire file is 100% testable and never touches the DOM:
// src/rect.ts
export interface Rect {
x: number;
y: number;
w: number;
h: number;
}
// Touching edges do not count as intersecting: half-open interval [x, x+w).
export function rectIntersects(a: Rect, b: Rect): boolean {
return (
a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
);
}
// Smallest rectangle containing both inputs.
export function rectUnion(a: Rect, b: Rect): Rect {
const x = Math.min(a.x, b.x);
const y = Math.min(a.y, b.y);
const right = Math.max(a.x + a.w, b.x + b.w);
const bottom = Math.max(a.y + a.h, b.y + b.h);
return { x, y, w: right - x, h: bottom - y };
}
export function rectArea(r: Rect): number {
return Math.max(0, r.w) * Math.max(0, r.h);
}
export function rectIntersectionArea(a: Rect, b: Rect): number {
const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
return w > 0 && h > 0 ? w * h : 0;
}
That margin matters because Canvas 2D applies anti-aliasing: the edge pixels of a circle or diagonal line are painted semi-transparently, and that shading can bleed one pixel outside the object's geometric bounds. If you clear only the exact bounding box, those half-pixels stay behind, and every moving object leaves a faint ghost trail in its wake. I hit this exact bug on my first run: a pale gray tail followed every moving square, and I could not figure out where it came from until I turned on dirty-region outlines.
The fix is a single step. Inflate every dirty rectangle by one pixel, then snap it outward to integer coordinates:
// src/rect.ts (continued)
export function expandRect(r: Rect, pad = 1): Rect {
return { x: r.x - pad, y: r.y - pad, w: r.w + pad * 2, h: r.h + pad * 2 };
}
// Snap fractional coordinates outward to integers:
// not even a half-pixel escapes outside.
export function snapRect(r: Rect): Rect {
const x = Math.floor(r.x);
const y = Math.floor(r.y);
return { x, y, w: Math.ceil(r.x + r.w) - x, h: Math.ceil(r.y + r.h) - y };
}
// Clip anything extending outside the canvas bounds.
export function clipRect(r: Rect, bounds: Rect): Rect {
const x = Math.max(r.x, bounds.x);
const y = Math.max(r.y, bounds.y);
const right = Math.min(r.x + r.w, bounds.x + bounds.w);
const bottom = Math.min(r.y + r.h, bounds.y + bounds.h);
return { x, y, w: Math.max(0, right - x), h: Math.max(0, bottom - y) };
}
If you use shadowBlur or a thick lineWidth, 1 pixel will not be enough; set pad to the radius of your effect. The rule is simple: pad must be at least the farthest distance a stroke or shadow can bleed past the geometric bounding box.
Collecting dirty rectangles
When a box moves from point A to point B, instinct says B is the dirty region because that is where the box sits now. An image of the box is still sitting at A, though, and nobody erased it. Because the canvas is persistent, clearing only B and drawing the box there leaves two boxes on screen: one real, one ghost.
A moving object dirties two places at once: where it left and where it arrived. If a leaky mug slides from one end of the table to the other, you wipe both the old ring and the new ring.
That is why DirtyTracker starts with markMoved:
// src/dirty.ts
import { type Rect, clipRect, expandRect, rectArea, snapRect } from "./rect";
import { mergeRects } from "./merge";
export interface DirtyOptions {
pad?: number; // anti-aliasing margin (px)
maxWaste?: number; // acceptable empty area when merging (px²)
maxRegions?: number;
}
export class DirtyTracker {
private rects: Rect[] = [];
private fullyDirty = false;
private readonly pad: number;
private readonly maxWaste: number;
private readonly maxRegions: number;
constructor(
private readonly bounds: Rect,
options: DirtyOptions = {},
) {
this.pad = options.pad ?? 1;
this.maxWaste = options.maxWaste ?? 2000;
this.maxRegions = options.maxRegions ?? 24;
}
markRect(r: Rect): void {
if (this.fullyDirty) return; // everything is already dirty, no need to track
const clipped = clipRect(snapRect(expandRect(r, this.pad)), this.bounds);
if (rectArea(clipped) > 0) this.rects.push(clipped);
}
// A moving object dirties TWO places: where it left and where it went.
markMoved(prev: Rect, next: Rect): void {
this.markRect(prev);
this.markRect(next);
}
markAll(): void {
this.fullyDirty = true;
this.rects = [{ ...this.bounds }];
}
regions(): Rect[] {
if (this.fullyDirty) return [{ ...this.bounds }];
// Merging scans pairs O(n²): when input grows large, its own cost
// exceeds drawing. Bail out if we exceed 4x the region cap.
if (this.rects.length > this.maxRegions * 4) return [{ ...this.bounds }];
const merged = mergeRects(this.rects, this.maxWaste);
// Too fragmented? A single full redraw is cheaper.
if (merged.length > this.maxRegions) return [{ ...this.bounds }];
return merged;
}
clear(): void {
this.rects.length = 0;
this.fullyDirty = false;
}
get pendingCount(): number {
return this.rects.length;
}
// Raw unmerged dirty rectangles: useful for metrics and debugging.
pending(): Rect[] {
return this.rects.map((r) => ({ ...r }));
}
}
Position is not the only thing that changes. Appearance changes too (color, selection state, animation frame, opacity). A button that never moves but changes color on hover is still dirty. Giving each object a small dirty flag and calling markRect(obj.bounds) when it is raised keeps everything clean: markMoved handles motion, and markRect handles appearance.
markAll() is your escape hatch. Window resized, theme switched, scene reloaded: everything is dirty, no argument needed.
That first guard inside regions() came directly from profiling. The merger scans pairs (O(n²)), so when the input list swells, its own cost explodes. In my 2,000-object scene with 200 movers, just merging rectangles burned 44 ms per frame, blowing the entire frame budget before a single pixel was drawn. Bailing out to a full redraw whenever raw rectangles exceed four times maxRegions dropped that exact scenario to 0.029 ms. (You will not see that 44 ms in npm run bench; I measured it manually with simulate(2000, 200, { maxRegions: 1000 }), while 0.029 ms is the default config shown in the final decision table.) Always measure the cost of an optimization itself.
To merge or to draw separately
We have a list of dirty rectangles. Looping over them directly runs into two problems. First, if two regions overlap, you clear and redraw the overlapping area twice. Second, every region pays a fixed save/clip/restore tax; a hundred tiny regions can cost more than one medium-sized region.
You do not dip the mop twice for two coffee drops sitting an inch apart; you wipe them in one pass. If one drop is in the kitchen and the other is in the living room, though, forcing a single sweep means mopping the entire hallway in between.
The metric is simple: how much empty waste area does merging two rectangles introduce? Whatever the bounding union covers beyond the actual area of the two rectangles is wasted pixels we will clear for nothing.
// src/merge.ts
import {
type Rect,
rectArea,
rectIntersectionArea,
rectIntersects,
rectUnion,
} from "./rect";
// How many extra pixels would we clear for nothing if we merge a and b?
export function mergeWaste(a: Rect, b: Rect): number {
const covered = rectArea(a) + rectArea(b) - rectIntersectionArea(a, b);
return rectArea(rectUnion(a, b)) - covered;
}
export function mergeRects(rects: Rect[], maxWaste = 0): Rect[] {
const out: Rect[] = rects.map((r) => ({ ...r }));
let changed = true;
while (changed) {
changed = false;
let bi = -1;
let bj = -1;
let best = Infinity;
for (let i = 0; i < out.length; i++) {
for (let j = i + 1; j < out.length; j++) {
// Overlapping rects always merge: no point clearing twice.
if (rectIntersects(out[i], out[j])) {
bi = i;
bj = j;
best = -1;
break;
}
const waste = mergeWaste(out[i], out[j]);
if (waste <= maxWaste && waste < best) {
best = waste;
bi = i;
bj = j;
}
}
if (best === -1) break;
}
if (bi >= 0) {
out[bi] = rectUnion(out[bi], out[bj]);
out.splice(bj, 1);
changed = true;
}
}
return out;
}
On every pass, we pick the pair with the least waste and merge them, repeating until no eligible pairs remain. Overlapping rectangles bypass the threshold completely because leaving them separate buys us nothing.
In my first version of this function, I made a mistake I am slightly embarrassed to admit: I wrote the threshold as a ratio ("merge if the union's area is at most 1.5× the sum of the two rectangles' areas"). It sounded reasonable at the time. I kept that version in the repo so we can compare them side by side:
// src/merge.ts (initial version kept for benchmark comparison)
export function mergeRectsRatio(rects: Rect[], maxGrowth = 1.5): Rect[] {
const out: Rect[] = rects.map((r) => ({ ...r }));
let changed = true;
while (changed) {
changed = false;
outer: for (let i = 0; i < out.length; i++) {
for (let j = i + 1; j < out.length; j++) {
const union = rectUnion(out[i], out[j]);
// Snowball effect: as the merged rect grows, this threshold grows too.
if (
rectArea(union) <=
maxGrowth * (rectArea(out[i]) + rectArea(out[j]))
) {
out[i] = union;
out.splice(j, 1);
changed = true;
break outer;
}
}
}
}
return out;
}
The bug is the snowball effect. A ratio threshold gets more generous as the merged rectangle grows: larger area means a larger 1.5× budget, which makes swallowing the next neighbor even easier. I measured it over 300 frames in my 2,000-object scene with 40 movers:
Merge Rule Regions/f Dirty Area Sprites/f
------------------------------------------------------------------
No merge (overlaps only) 34.8 6.3% 415.8
Ratio threshold 1.5 32.1 8.4% 446.5
At first glance the numbers look mild, but the verdict is clear: region count barely budged (34.8 down to 32.1), while dirty area jumped by a third and we drew 30 extra sprites every frame. I paid more and got nothing in return. With larger sprites, that snowball rolls even faster because the growth is baked into the math of ratio thresholds.
Switching to an absolute waste budget (in square pixels) made the behavior predictable because the threshold never inflates as regions grow:
maxWaste (px²) Regions/frame Dirty Area Sprites/frame
--------------------------------------------------------------
0 34.8 6.3% 415.8
500 31.9 6.7% 414.7
2,000 20.9 12.5% 521.1
8,000 10.4 31.1% 885.5
32,000 1.4 89.8% 1,899.5
∞ (single box) 1.0 94.1% 1,965.1
(640×360 canvas, 2,000 sprites, 40 movers, seeded scene, 300-frame average. Reproduced verbatim with npm run bench; counts are deterministic and independent of machine speed.)
Here is how to read that table: maxWaste = 500 is practically free, trimming three regions while adding less than half a point of dirty area. At 2,000, the real tradeoff appears: region count drops by 40% while dirty area doubles, yet 12.5% is still only one-eighth of the canvas, or 28,800 pixels. Past 8,000, dirty area explodes and you hand every microsecond saved on clip calls right back to pixel fill. At infinity, you have abandoned the technique altogether.
That is why DirtyTracker defaults to 2,000: it cuts the save/clip/restore overhead by 40% while keeping the dirty area small. If your sprites are larger or more scattered than mine, a different row will win. Re-run the table on your own scene.
Constraining draws with clip()
Once the regions are ready, drawing them has its own catch.
Clearing a region with clearRect and drawing the touching sprites is not enough, because a sprite that partially overlaps a dirty region will still try to draw its entire body. Repainting the part outside the dirty region might look harmless until alpha blending enters the picture: painting a semi-transparent edge twice darkens it, leaving ugly artifacts along the seam.
You do not let the mop wander outside the square you just cleared. That is exactly what ctx.clip() does: after calling it, no draw call can write a single pixel outside the path you defined.
Our sprite interface stays minimal, requiring only an AABB (axis-aligned bounding box):
// src/scene.ts
import type { HasBounds } from "./query";
export interface Sprite extends HasBounds {
id: number;
vx: number;
vy: number;
color: string;
}
// src/render.ts
import type { Rect } from "./rect";
import type { Sprite } from "./scene";
import type { GridIndex } from "./query";
export function drawRegion(
ctx: CanvasRenderingContext2D,
region: Rect,
index: GridIndex<Sprite>,
drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) => void,
): number {
ctx.save();
ctx.beginPath();
ctx.rect(region.x, region.y, region.w, region.h);
ctx.clip(); // nothing leaks outside
ctx.clearRect(region.x, region.y, region.w, region.h); // clear only this box
const touching = index.query(region);
for (const sprite of touching) drawSprite(ctx, sprite);
ctx.restore(); // release the clip so the next region sets its own
return touching.length; // metric: how many sprites we drew in this region
}
ctx.restore() is mandatory. A clip region cannot be undone; it can only be scoped out with a save/restore pair. Forget it once, and the second region clips against the intersection with the first, silently erasing half your screen.
index.query(region) connects directly to the next article in this series (Up Next: Broad-Phase Collision & Spatial Hashing), where we divide the world into uniform grid cells to ask which bodies are near each other. Here we use the same spatial query to ask which sprites touch a given rectangle.
// src/query.ts
import { type Rect, rectIntersects } from "./rect";
export interface HasBounds {
bounds: Rect;
}
// Ground truth reference: check every item. Used as the oracle in tests.
export function queryBrute<T extends HasBounds>(items: T[], region: Rect): T[] {
return items.filter((it) => rectIntersects(it.bounds, region));
}
export class GridIndex<T extends HasBounds> {
private cells = new Map<string, number[]>();
private items: T[] = [];
constructor(public readonly cellSize: number) {}
clear(): void {
this.cells.clear();
this.items.length = 0;
}
private cellOf(v: number): number {
return Math.floor(v / this.cellSize);
}
insert(item: T): void {
const id = this.items.length;
this.items.push(item);
const b = item.bounds;
// Register the item in EVERY cell its AABB touches.
for (let cx = this.cellOf(b.x); cx <= this.cellOf(b.x + b.w); cx++) {
for (let cy = this.cellOf(b.y); cy <= this.cellOf(b.y + b.h); cy++) {
const key = cx + "," + cy;
let cell = this.cells.get(key);
if (!cell) {
cell = [];
this.cells.set(key, cell);
}
cell.push(id);
}
}
}
query(region: Rect): T[] {
const seen = new Set<number>();
const out: T[] = [];
for (
let cx = this.cellOf(region.x);
cx <= this.cellOf(region.x + region.w);
cx++
) {
for (
let cy = this.cellOf(region.y);
cy <= this.cellOf(region.y + region.h);
cy++
) {
const cell = this.cells.get(cx + "," + cy);
if (!cell) continue;
for (const id of cell) {
if (seen.has(id)) continue; // same item can span multiple cells
seen.add(id);
const item = this.items[id];
if (rectIntersects(item.bounds, region)) out.push(item);
}
}
}
return out;
}
}
One warning: draw order. query returns items in cell traversal order, not insertion order. If your sprites overlap and z-order matters, sort the returned array by draw order before rendering. Otherwise, layer order breaks exclusively inside dirty regions, putting a background box on top of a foreground box. That is a miserable bug to track down because it only appears where sprites overlap and only when that spot gets dirty.
Now let's wire up a complete frame from start to finish:
// src/loop.ts
import type { Rect } from "./rect";
import { DirtyTracker } from "./dirty";
import { GridIndex } from "./query";
import { drawRegion } from "./render";
import type { Sprite } from "./scene";
const CANVAS: Rect = { x: 0, y: 0, w: 640, h: 360 };
export function makeFrame(
ctx: CanvasRenderingContext2D,
sprites: Sprite[],
drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) => void,
) {
const tracker = new DirtyTracker(CANVAS, { pad: 1, maxWaste: 2000 });
const index = new GridIndex<Sprite>(64);
return function frame(dt: number) {
tracker.clear();
// 1. Update positions and mark dirty regions
for (const sprite of sprites) {
if (sprite.vx === 0 && sprite.vy === 0) continue;
const prev = { ...sprite.bounds };
sprite.bounds = {
...sprite.bounds,
x: sprite.bounds.x + sprite.vx * dt,
y: sprite.bounds.y + sprite.vy * dt,
};
tracker.markMoved(prev, sprite.bounds);
}
// 2. Rebuild spatial index (ALL sprites, not just movers:
// static sprites can overlap a dirty region too)
index.clear();
for (const sprite of sprites) index.insert(sprite);
// 3. Draw only dirty regions
let drawn = 0;
let dirtyPixels = 0;
for (const region of tracker.regions()) {
drawn += drawRegion(ctx, region, index, drawSprite);
dirtyPixels += region.w * region.h;
}
return { drawn, dirtyPixels, total: sprites.length };
};
}
Do not skip the comment on step two. We insert all sprites into the index, not just the moving ones. A dirty region cleared behind a moving sprite also erases any static sprite underneath it, so that static sprite must be redrawn. When you lift a mug off the table, the coaster underneath shows back up, so you have to paint it too.
The moment a camera breaks everything
One common scenario breaks this technique outright: a scrolling camera (later in this series, we will build a side-scroller with per-layer parallax multipliers using this same pattern):
// Typical scrolling camera setup — illustrative only, NOT in this repo
// (src/ never calls translate).
ctx.save();
ctx.translate(-camera.x, -camera.y);
drawWorld(ctx);
ctx.restore();
When the player walks right and camera.x increases by a few pixels, every pixel on screen changes. Shifting the camera by even one pixel moves every object on the canvas by one pixel in screen space: ground tiles, clouds, distant hills, all of them. Your dirty region list covers the entire viewport. DirtyTracker works properly and gives the honest answer that everything is dirty.
You wiped the table, then picked up the table and carried it six feet to the left. Now everything is dirty again, and this time it is your fault.
While a camera is scrolling, dirty-rect saves you nothing, and you still pay the tracking tax (markMoved calls, the mergeRects loop, and spatial queries) for zero return. That is why you should watch the camera explicitly and trigger the escape hatch:
// src/camera.ts
import type { DirtyTracker } from "./dirty";
export interface Camera {
x: number;
y: number;
}
export class CameraWatcher {
private lastX: number;
private lastY: number;
constructor(camera: Camera) {
this.lastX = camera.x;
this.lastY = camera.y;
}
// If the camera moved, dirty-rect has nothing to offer: mark everything.
sync(camera: Camera, tracker: DirtyTracker): boolean {
const moved = camera.x !== this.lastX || camera.y !== this.lastY;
this.lastX = camera.x;
this.lastY = camera.y;
if (moved) tracker.markAll();
return moved;
}
}
For pure horizontal scrolling, there is a classic rescue trick: blit the canvas onto itself shifted by dx, then draw only the newly exposed strip.
// src/scroll.ts
// Shift the canvas by dx and dirty only the newly exposed strip.
// Fractional dx accumulates anti-aliasing blur; integer steps are mandatory.
export function scrollCanvas(
ctx: CanvasRenderingContext2D,
width: number,
height: number,
dx: number,
): { x: number; y: number; w: number; h: number } | null {
if (dx === 0 || Math.abs(dx) >= width) return null;
const shift = Math.trunc(dx);
if (shift === 0) return null;
ctx.save();
ctx.globalCompositeOperation = "copy"; // no blending, raw pixel copy
ctx.drawImage(ctx.canvas, -shift, 0);
ctx.restore();
return shift > 0
? { x: width - shift, y: 0, w: shift, h: height } // new strip on the right
: { x: 0, y: 0, w: -shift, h: height }; // new strip on the left
}
This looks clever on paper and feels brittle in production. Camera velocity has to be an integer, or sub-pixel shifts smear the scene into a blur over time. Vertical scrolling forces you to manage two axes. Parallax layers move at different speeds, so a single dx does not work. The moment you add camera zoom, the trick collapses completely. I wired this into a platformer once and ripped it out two days later; the performance gain was not worth the fragility.
My rule of thumb: if the camera moves continuously, do not build dirty-rect at all. Call clearRect(0, 0, W, H) and spend your engineering budget on frustum culling instead. Skipping 1,900 off-screen objects beats cleverly redrawing 100 on-screen ones every time.
Layered canvases: the cheap alternative
If you do not want the complexity of tracking, merging, and clipping dirty rectangles, there is a cruder, simpler trick that works for most scenes: split the canvas into layers.
Instead of wiping the tablecloth every meal, you put a disposable placemat on top and only swap the placemat.
You stack two <canvas> elements with CSS. The bottom one holds the static background and is drawn once. The top one is transparent, holds only the moving objects, and gets wiped cleanly every frame. The browser composites the two on the GPU practically for free.
<!-- index.html -->
<div class="stage">
<canvas id="bg" width="640" height="360"></canvas>
<canvas id="fg" width="640" height="360"></canvas>
</div>
/* index.html <style> block */
.stage { position: relative; width: 640px; height: 360px; background: #0b1220; border: 1px solid #334155; }
.stage canvas { position: absolute; inset: 0; }
// src/layers.ts
import type { Sprite } from "./scene";
export interface Layers {
bg: CanvasRenderingContext2D;
fg: CanvasRenderingContext2D;
width: number;
height: number;
}
export function createLayers(
bgCanvas: HTMLCanvasElement,
fgCanvas: HTMLCanvasElement,
): Layers {
const bg = bgCanvas.getContext("2d");
const fg = fgCanvas.getContext("2d");
if (!bg || !fg) throw new Error("Failed to get 2d context");
return { bg, fg, width: bgCanvas.width, height: bgCanvas.height };
}
// Static layer: drawn ONCE on scene setup and resize.
export function paintStatic(
layers: Layers,
statics: Sprite[],
drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) => void,
): void {
layers.bg.clearRect(0, 0, layers.width, layers.height);
for (const sprite of statics) drawSprite(layers.bg, sprite);
}
// Dynamic layer: cleared in full every frame, but only holds
// a handful of movers — not 2,000.
export function paintDynamic(
layers: Layers,
movers: Sprite[],
drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) => void,
): void {
layers.fg.clearRect(0, 0, layers.width, layers.height);
for (const sprite of movers) drawSprite(layers.fg, sprite);
}
Layered canvases do not eliminate pixel cost: you still call clearRect across all 640×360 pixels of the top layer every frame. What they eliminate is call cost, issuing 40 draw calls instead of 2,000.
Dirty-rect saves on both, at the price of markMoved discipline, merge tuning, and z-order sorting.
My selection rule:
- If you have a clear split between a static background and a few movers, use layered canvases. Twenty lines of code, zero bug risk.
- If movers are interleaved with static scenery, z-order is mixed, or a HUD updates a few numbers, use dirty-rect.
- If both apply, put the static background on the bottom canvas and run dirty-rect on the top canvas.
Tests: is your dirty region lying?
This technique has one fatal sin: failing to mark a dirty pixel as dirty. When that happens, ghosts linger on screen, users report corrupted rendering, and you burn two hours debugging sprite code that is completely innocent.
The good news is that every piece of logic here is pure math. Rect operations, merging, tracking, and spatial queries do not need a <canvas> element, and all of them run in headless Vitest:
// test/dirty.test.ts
import { describe, it, expect } from "vitest";
import {
type Rect,
expandRect,
rectArea,
rectIntersectionArea,
rectIntersects,
rectUnion,
} from "../src/rect";
import { mergeRects } from "../src/merge";
import { DirtyTracker } from "../src/dirty";
import { GridIndex, queryBrute, type HasBounds } from "../src/query";
describe("rect math", () => {
it("touching edges do not count as intersecting", () => {
const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
expect(rectIntersects(a, { x: 10, y: 0, w: 10, h: 10 })).toBe(false);
expect(rectIntersects(a, { x: 9, y: 0, w: 10, h: 10 })).toBe(true);
});
it("union covers both rectangles", () => {
const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
const b: Rect = { x: 20, y: 5, w: 10, h: 10 };
expect(rectUnion(a, b)).toEqual({ x: 0, y: 0, w: 30, h: 15 });
expect(rectArea(rectUnion(a, b))).toBeGreaterThanOrEqual(
rectArea(a) + rectArea(b),
);
});
it("expandRect grows by 1px in all directions for anti-aliasing", () => {
expect(expandRect({ x: 10, y: 10, w: 5, h: 5 }, 1)).toEqual({
x: 9,
y: 9,
w: 7,
h: 7,
});
});
it("rectIntersectionArea returns 0 for disjoint pairs", () => {
const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
expect(rectIntersectionArea(a, { x: 20, y: 0, w: 10, h: 10 })).toBe(0);
expect(rectIntersectionArea(a, { x: 5, y: 5, w: 10, h: 10 })).toBe(25);
});
});
describe("mergeRects", () => {
it("merges overlapping rects into one", () => {
const merged = mergeRects(
[
{ x: 0, y: 0, w: 20, h: 20 },
{ x: 10, y: 10, w: 20, h: 20 },
],
0,
);
expect(merged).toHaveLength(1);
expect(merged[0]).toEqual({ x: 0, y: 0, w: 30, h: 30 });
});
it("keeps distant rectangles separate", () => {
const merged = mergeRects(
[
{ x: 0, y: 0, w: 10, h: 10 },
{ x: 500, y: 500, w: 10, h: 10 },
],
2000,
);
expect(merged).toHaveLength(2);
expect(merged.reduce((s, r) => s + rectArea(r), 0)).toBe(200);
});
it("merged regions fully cover every input", () => {
const input: Rect[] = [
{ x: 0, y: 0, w: 12, h: 12 },
{ x: 8, y: 4, w: 12, h: 12 },
{ x: 300, y: 200, w: 30, h: 30 },
];
const merged = mergeRects(input, 0);
for (const r of input) {
// Every input must sit COMPLETELY inside one output: no dirty pixel escapes.
expect(
merged.some((m) => rectIntersectionArea(m, r) === rectArea(r)),
).toBe(true);
}
});
it("with 0 waste budget only overlaps merge", () => {
const near: Rect[] = [
{ x: 0, y: 0, w: 10, h: 10 },
{ x: 12, y: 0, w: 10, h: 10 }, // 2px gap -> 20px² waste
];
expect(mergeRects(near, 0)).toHaveLength(2);
expect(mergeRects(near, 20)).toHaveLength(1);
});
});
describe("DirtyTracker", () => {
const bounds: Rect = { x: 0, y: 0, w: 640, h: 360 };
it("markMoved dirties both old and new positions", () => {
const t = new DirtyTracker(bounds, { pad: 1, maxWaste: 0 });
t.markMoved(
{ x: 10, y: 10, w: 20, h: 20 },
{ x: 300, y: 200, w: 20, h: 20 },
);
const regions = t.regions();
expect(regions).toHaveLength(2);
expect(
regions.some((r) => rectIntersects(r, { x: 10, y: 10, w: 20, h: 20 })),
).toBe(true);
expect(
regions.some((r) => rectIntersects(r, { x: 300, y: 200, w: 20, h: 20 })),
).toBe(true);
});
it("small step merges old and new positions into one region", () => {
const t = new DirtyTracker(bounds, { pad: 1, maxWaste: 0 });
t.markMoved(
{ x: 100, y: 100, w: 20, h: 20 },
{ x: 103, y: 100, w: 20, h: 20 },
);
expect(t.regions()).toHaveLength(1);
});
it("regions stay clipped within canvas bounds", () => {
const t = new DirtyTracker(bounds, { maxWaste: 0 });
t.markRect({ x: -50, y: -50, w: 100, h: 100 });
const [r] = t.regions();
expect(r.x).toBe(0);
expect(r.y).toBe(0);
expect(r.x + r.w).toBeLessThanOrEqual(640);
});
it("falls back to full redraw when region cap is exceeded", () => {
const t = new DirtyTracker(bounds, { pad: 0, maxWaste: 0, maxRegions: 3 });
for (let i = 0; i < 8; i++)
t.markRect({ x: i * 70, y: i * 40, w: 10, h: 10 });
expect(t.regions()).toEqual([bounds]);
});
it("markAll dirties everything and swallows subsequent markRect calls", () => {
const t = new DirtyTracker(bounds, { maxWaste: 0 });
t.markAll();
t.markRect({ x: 5, y: 5, w: 5, h: 5 });
expect(t.regions()).toEqual([bounds]);
expect(t.pendingCount).toBe(1);
});
it("no dirty regions remain after clear", () => {
const t = new DirtyTracker(bounds);
t.markRect({ x: 5, y: 5, w: 5, h: 5 });
t.clear();
expect(t.regions()).toHaveLength(0);
});
});
interface TestSprite extends HasBounds {
id: number;
}
function scene(n: number, seed: number): TestSprite[] {
let s = seed;
const rand = () => {
s = (s * 1103515245 + 12345) & 0x7fffffff;
return s / 0x7fffffff;
};
return Array.from({ length: n }, (_, id) => ({
id,
bounds: {
x: rand() * 620,
y: rand() * 340,
w: 4 + rand() * 40,
h: 4 + rand() * 40,
},
}));
}
describe("spatial query for touching sprites", () => {
it("grid query matches brute-force set exactly", () => {
const items = scene(400, 9);
const grid = new GridIndex<TestSprite>(64);
for (const it of items) grid.insert(it);
const regions: Rect[] = [
{ x: 0, y: 0, w: 50, h: 50 }, // corner
{ x: 200, y: 120, w: 90, h: 40 }, // center
{ x: 610, y: 330, w: 30, h: 30 }, // edge-clipping
{ x: 0, y: 0, w: 640, h: 360 }, // full screen
];
for (const region of regions) {
const fromGrid = grid
.query(region)
.map((s) => s.id)
.sort((a, b) => a - b);
const brute = queryBrute(items, region)
.map((s) => s.id)
.sort((a, b) => a - b);
expect(fromGrid).toEqual(brute);
}
});
it("matches brute-force even with negative coordinates", () => {
const items = scene(300, 17);
const grid = new GridIndex<TestSprite>(48);
for (const it of items) grid.insert(it);
const region: Rect = { x: -80, y: -40, w: 200, h: 150 };
const fromGrid = grid
.query(region)
.map((s) => s.id)
.sort((a, b) => a - b);
const brute = queryBrute(items, region)
.map((s) => s.id)
.sort((a, b) => a - b);
expect(fromGrid).toEqual(brute);
});
it("never returns the same sprite twice", () => {
const items = scene(200, 3);
const grid = new GridIndex<TestSprite>(32);
for (const it of items) grid.insert(it);
const ids = grid.query({ x: 0, y: 0, w: 640, h: 360 }).map((s) => s.id);
expect(new Set(ids).size).toBe(ids.length);
});
});
Two tests matter above all others. First, "merged regions fully cover every input": after merging, every original dirty rectangle must sit completely inside one output region. If its intersection area equals its own area, nothing escaped. If that test turns red, ghosts are guaranteed.
Second, the brute-force oracle. The set returned by GridIndex must match "check every item one by one" identically. We will use this exact discipline in the upcoming broad-phase collision article: validate your fast spatial structure against the slow, exact one. I tested four regions (corner, center, edge-clipping, full screen) because off-by-one cell math almost always hides at canvas boundaries.
If those two tests are green, everything else is visual tuning.
When it pays off, and when it does not
In the same 2,000-sprite scene, I varied the number of moving sprites and averaged 300 frames (maxWaste = 2000, maxRegions = 24):
Movers Ratio Reg/f Dirty Drawn/f vs Full Tracking
-------------------------------------------------------------
5 0.25% 4.6 1.0% 52.7 3% 0.006 ms
20 1% 14.6 5.2% 260.2 13% 0.254 ms
40 2% 20.9 12.5% 521.1 26% 1.903 ms
100 5% 1.0 100.0% 2,000.0 100% 0.015 ms
200 10% 1.0 100.0% 2,000.0 100% 0.029 ms
400 20% 1.0 100.0% 2,000.0 100% 0.058 ms
2,000 100% 1.0 100.0% 2,000.0 100% 0.294 ms
The last column is per-frame tracking cost (marking plus merging, excluding drawing, on an Apple M2 Pro with Node 22).
The curve turned out steeper than I expected. With 5 movers, we do only 3% of the work, better than a 30× reduction. At 20 movers, 13%; at 40 movers, 26%. Then comes the cliff: at 100 movers, the technique shuts itself off and drops back to a full redraw.
That cliff is the bailout guard doing its job. A hundred moving sprites generate 200 raw dirty rectangles per frame. Because that exceeds four times maxRegions, regions() skips merging altogether and reports everything as dirty. I built that behavior intentionally, because nothing is sneakier than an optimization that slows down your frame rate without telling you.
The bottom row is the honest limit: when every object moves, dirty-rect loses. It performs the exact same draw work as a full redraw (2,000 sprites, 100% of the canvas) while charging an extra 0.29 ms per frame for tracking. At 60 fps, that is 1.8% of your entire frame budget burned for zero return.
Here is my decision rule:
- Under 1% moving objects, dirty-rect wins decisively. Inventories, maps, tables, editors, and HUD-heavy screens live here.
- Between 1% and 2%, it still wins, though tracking cost becomes visible (1.9 ms/frame at 2% in my test). Measure it.
- Above 5%, don't bother. The bailout already shuts it off. Call
clearRect(0, 0, W, H)and optimize drawing itself with sprite batching, offscreen pre-rendering, and object pools. - With a continuously scrolling camera, skip dirty-rect regardless of mover ratio.
- In a fixed-camera tile game, it is a textbook fit because terrain tiles never move and only characters and effects dirty the screen.
Never guess without measuring. The live demo includes a toggle that outlines dirty regions on screen, and turning it on shows you in a second which object is needlessly dirtying the canvas. Drag the movers slider up to 100 in the demo and watch the outline snap around the entire screen: that is the 100% row of the table right before your eyes.
Summary
- A Canvas 2D surface is persistent. Calling
clearRect(0, 0, W, H)throws that guarantee away every frame; dirty-rectangle rendering cashes it in. - A moving object dirties two places at once: where it left and where it arrived. That is why
markMoved(prev, next)exists. - Anti-aliasing bleeds past geometric bounds. Inflate every dirty rectangle by at least 1 px and snap outward to integers, or ghost trails will stay behind.
- Never write merge thresholds as area ratios; they snowball and inflate dirty area for no gain. Use an absolute pixel-waste budget (
px²), where500to2,000was the sweet spot in my scene. - Per region, run
save,clip,clearRect, draw, andrestore. Skiprestoreand the next region intersects the previous clip, silently hiding the screen. - Finding every sprite touching a dirty rectangle is a spatial query; the same grid we will use for broad-phase collision in the next article handles it here. Sort by z-order if sprites overlap.
- A scrolling camera invalidates the whole technique: shift one pixel and the entire screen is dirty. Accept it, call
markAll(), and spend your budget on culling. - The simple alternative is layered canvases: static background on the bottom once, movers on top every frame. Twenty lines, zero bug risk, plenty for most scenes.
- Let mover ratio decide: under 1% is a guaranteed win, over 5% is a loss, and at 100% moving, dirty-rect does all the full-redraw work plus tracking overhead. Measure, don't guess.
The GitHub repository runs with three commands: npm test verifies all 17 unit tests across Rect math, merging, tracking, and the spatial index; npm run bench reproduces all three tables locally (count columns are deterministic, only tracking time varies by hardware); and npm run dev launches the interactive demo with dirty-region outlines and a full-redraw toggle (the layered canvas example lives in the same repo). Or launch the interactive live demo straight in your browser.
Figuring out why my ratio threshold made things worse took longer than writing the code. On my first benchmark run, I saw the region count drop and celebrated. It took me half an hour to notice the dirty area column, and for that entire half hour I was staring at a table that hid the very thing I had broken. Knowing which column to read matters just as much as writing fast code.
If there is one drop of coffee on the table, clean one drop and leave the rest alone.
Canvas 2D and game architecture series
- Part 1: How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas
- Part 2: Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes
- Part 3: Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript
- Part 4: Return the Glass, Not the Trash: Object Pools and Zero-Allocation Game Loops in Canvas (Series entry)
- Part 5 (This Article): No Need to Wipe the Whole Table: Dirty Rectangle Rendering in Canvas 2D
- Part 6 (Up Next): Broad-Phase Collision & Spatial Hashing in Canvas 2D
About the author
I'm Mustafa Morbel, a software engineer with over 17 years of experience building modern web applications, game engines, WebGL/Canvas graphics, and AI-assisted developer workflows.
- Explore the full TypeScript source, 17 Vitest tests, and benchmarks in the GitHub repository, or try the interactive live demo in your browser.
- Follow me on LinkedIn and X / Twitter (@mustafamorbel) for upcoming articles in this series.
Have you hit the scrolling-camera wall or tuned dirty-rect budgets in your own Canvas app? I'd love to hear how you solved it.

Top comments (1)
With 5 of 2,000 objects moving, a 97% cut in draws is a great argument for dirty rectangles. The part I would watch is overlapping rects: merging them past a threshold usually beats redrawing many small ones.