Rendering a tile map without a chunk cache
canvas2dtilemaprenderingperformancecaching
The textbook way to draw a large tile map is to pre-render chunks to offscreen canvases and blit them. For a flat-colored tile map in Canvas2D this turned out to be the worse option. Merging the visible tiles into rectangles every frame and filling them directly was far cheaper. This was decided by an adversarial performance review whose numbers were then verified independently.
Measured costs of the chunk-canvas cache
- 144 MiB resident at device pixel ratio 2.
- 2 to 10 ms single-frame hitches whenever a chunk had to be baked.
- LRU pathology: driving in circles ("donuts") at a chunk corner regenerated about 21 chunks per second.
- Invalidation on every DPR change (moving the window between monitors, zoom).
- Seams from fractional blits.
What was used instead
Per frame, greedy-merge the tiles in the visible window into rectangles and fillRect them:
0.015 ms at 1080p, 0.05 ms at 4K, zero allocation, about 6 fillStyle changes per frame.
- Size the scratch buffers from the viewport, never from a range clamped to the map. A clamped range
changes size at map edges and caused real reallocations (a bug found in review).
- Clamp iteration to the map bounds and create no closures per frame.
When a cache would still win
Textured or expensive-to-draw tiles, or a renderer where draw calls dominate (see the toImageSync
escape hatch in Flutter / Flame canvas rendering performance facts). Measure both before deciding.
See also
- Tile collision with merged rectangles
- Adversarial review before architecture decisions
- Zero-allocation render and update loops