Rendering Custom Fonts to a 2048px PNG with Canvas
A browser preview can look correct while the downloaded image is wrong. The usual failure is timing: CSS eventually applies the custom font to the preview, but Canvas draws once. If the font is not ready at that exact moment, fillText() can silently use a fallback face. The user sees one design and downloads another. I ran into this while building GraffForge, a browser-based graffiti text tool. The free editor compares the same user-entered word across multiple bundled styles, then exports the selected result as a transparent 2048 × 2048 PNG. That gave the export path a clear contract: preserve the exact text; use the selected font; keep spacing, outline, shadow, and skew; fit inside a safe area; preserve real transparency; never upload the user's text or image. Here is the approach that made the output deterministic. 1. Treat export as a separate rendering target Do not enlarge the preview DOM and take a screenshot. Create a fresh Canvas with explicit bitmap dimensions: const EXPORT_SIZE = 2048 ; const canvas = document . createElement ( ' canvas ' ); canvas . width = EXPORT_SIZE ; canvas . height = EXPORT_SIZE ; const context = canvas . getContext ( ' 2d ' ); if ( ! context ) { throw new Error ( ' Canvas rendering is unavailable. ' ); } The width and height attributes define the actual PNG pixel dimensions. CSS sizing and devicePixelRatio are useful for an on-screen preview, but neither should determine the export contract. A fixed bitmap size also makes automated verification straightforward. 2. Load the font before measuring anything Canvas does not redraw automatically when a font finishes loading. Load the exact family, weight, size, and text before calling measureText() : await document . fonts . load ( `400 160px " ${ fontFamily } "` , text ); Passing the actual text is useful because the browser can confirm that the required glyphs are available. After this point, set the Canvas font explicitly: context . font = `400 ${ fontSize } px " ${ fontFamily } "` ;