When I built a free VTT Token Maker for FantasyGen, I had one hard constraint: no image processing on the server.

Tabletop RPG players drag in character portraits, pan and zoom around the face, swap between hundreds of ornate round and hexagonal frames, tint the metal, and export either a single token or a numbered set of 10+ tokens (think Goblin 01 through Goblin 10) as a ZIP file. Running that through a backend endpoint would add upload latency, burn bandwidth, and force users to send local artwork to a server just to crop a circle.

Putting the entire pipeline in HTML5 Canvas solved the latency and privacy problems, but it immediately surfaced four surprisingly tricky graphics and binary-format problems:

  1. Simple ctx.arc() / polygon clipping breaks on ornate, asymmetric art borders.
  2. Real-time metallic recoloring without sluggish per-pixel loops.
  3. Letting users upload their own borders—even opaque JPEGs with a solid background.
  4. Exporting batches of PNG/WebP tokens as a ZIP without pulling in a heavy compression library.

Here is how I solved each one in plain TypeScript.

1. Why ctx.arc() Fails on Ornate Borders (and Flood-Fill Masking)

My first naive version clipped the portrait with a circle (ctx.arc(...) + ctx.clip()) or a pointy-top hexagon path, drew the portrait, and stamped the transparent border PNG on top.

That works fine for clean geometric rings. It falls apart the moment you introduce illustrated borders with skulls, vines, spikes, or hand-drawn hex frames where the inner opening isn't a mathematically perfect circle. You either clip too tight (leaving a thin transparent gap between the portrait and the frame) or too wide (the portrait bleeds out past decorative notches).

Instead of guessing a radius, we can compute a pixel-exact interior mask once per border image using a breadth-first flood fill from the center pixel:

const maskCache = new WeakMap<object, HTMLCanvasElement | null>() function openingMask(image: HTMLImageElement): HTMLCanvasElement | null { if (maskCache.has(image)) return maskCache.get(image) ?? null const M = Math.min(512, image.width || 512) const canvas = document.createElement('canvas') canvas.width = M canvas.height = M const ctx = canvas.getContext('2d', { willReadFrequently: true }) if (!ctx) { maskCache.set(image, null) return null } ctx.drawImage(image, 0, 0, M, M) let data: Uint8ClampedArray try { data = ctx.getImageData(0, 0, M, M).data } catch { // Graceful fallback to geometric clipping if a cross-origin image taints the canvas maskCache.set(image, null) return null } const total = M * M const alpha = new Uint8Array(total) for (let i = 0; i < total; i++) alpha[i] = data[i * 4 + 3] const center = (M >> 1) * M + (M >> 1) const queue = new Int32Array(total) let hole: Uint8Array | null = null // Try progressively stricter alpha thresholds in case a delicate border // has semi-transparent pixels along its ring. for (const wall of [180, 80, 24]) { if (alpha[center] >= wall) continue const visited = new Uint8Array(total) let head = 0 let tail = 0 let leaked = false visited[center] = 1 queue[tail++] = center while (head < tail) { const idx = queue[head++] const x = idx % M const y = (idx - x) / M if (x === 0 || x === M - 1 || y === 0 || y === M - 1) { leaked = true break } const neighbors = [idx - 1, idx + 1, idx - M, idx + M] for (const n of neighbors) { if (!visited[n] && alpha[n] < wall) { visited[n] = 1 queue[tail++] = n } } } if (!leaked) { hole = visited break } } if (!hole) { maskCache.set(image, null) return null } // Dilate 1–2 px into the opaque inner wall (alpha >= 180) so anti-aliased // inner edges never show a seam, without ever bleeding past the outer edge. const pad = M >= 384 ? 2 : 1 let mask = hole for (let step = 0; step < pad; step++) { const next = new Uint8Array(mask) for (let y = 1; y < M - 1; y++) { const row = y * M for (let x = 1; x < M - 1; x++) { const idx = row + x if (mask[idx] || alpha[idx] < 180) continue if (mask[idx - 1] || mask[idx + 1] || mask[idx - M] || mask[idx + M]) { next[idx] = 1 } } } mask = next } const out = ctx.createImageData(M, M) const buf = out.data for (let i = 0; i < total; i++) { if (mask[i]) { const p = i * 4 buf[p] = 255 buf[p + 1] = 255 buf[p + 2] = 255 buf[p + 3] = 255 } } ctx.putImageData(out, 0, 0) maskCache.set(image, canvas) return canvas } 

Three details make this reliable in production:

  • Multi-threshold fallback ([180, 80, 24]): If a semi-transparent glow or thin ornament lets the flood fill escape to the canvas edge (leaked = true), we retry with a lower alpha wall before giving up and falling back to geometric clipping.
  • Constrained dilation: Expanding the hole by 1–2 pixels only into pixels with alpha >= 180 eliminates ugly anti-aliased halos along the inner rim while guaranteeing the portrait stays tucked behind the solid frame.
  • Compositing & caching: When rendering the token, we draw the portrait first, apply ctx.globalCompositeOperation = 'destination-in' with the cached mask canvas, restore the context, and stamp the border on top. Because the mask is cached in a WeakMap keyed by the HTMLImageElement, panning and zooming stays at a steady 60fps and old masks get garbage-collected automatically.

2. Real-Time Metallic Recoloring with Two Composite Passes

Users also want to recolor a gold or silver ornate border to crimson, emerald, or obsidian while keeping all of its highlights, bevels, and shadows intact.

Looping over ImageData in JavaScript to convert RGB → HSL → RGB on every slider drag is slow and unnecessary. HTML5 Canvas already supports the 'color' blend mode natively: it applies the fill color's hue and saturation while preserving the underlying image's luminance.

The only snag is that filling a rectangle with 'color' also paints over transparent pixels. A second pass with 'destination-in' restores the exact original alpha silhouette:

const tintCache = new WeakMap<object, Map<string, HTMLCanvasElement>>() function tintedArt(image: HTMLImageElement, tint: string): HTMLCanvasElement { let byTint = tintCache.get(image) if (!byTint) { byTint = new Map() tintCache.set(image, byTint) } const cached = byTint.get(tint) if (cached) return cached const canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height const ctx = canvas.getContext('2d')! // 1. Draw the original border (keeps highlights and shading) ctx.drawImage(image, 0, 0) // 2. Apply hue + saturation while preserving luminance ctx.globalCompositeOperation = 'color' ctx.fillStyle = tint ctx.fillRect(0, 0, canvas.width, canvas.height) // 3. Mask back to the border's original alpha channel ctx.globalCompositeOperation = 'destination-in' ctx.drawImage(image, 0, 0) byTint.set(tint, canvas) return canvas } 

Two draw calls, zero pixel loops, and instant re-use from the nested WeakMap<object, Map<string, HTMLCanvasElement>> cache.

3. Handling User-Uploaded Opaque Borders (Auto-Keying + Raycasting)

Many people who want to use their own frame upload a JPEG or an opaque PNG with a solid white or black background. If we just slap it on top of the portrait, it hides the whole image.

So when a visitor uploads a custom border, we run a quick client-side preprocessor:

  1. Detect transparency: Sample every 7th pixel's alpha channel. If fewer than 5% of sampled pixels are transparent, treat the image as opaque.
  2. 5-seed background flood fill: Sample the top-left corner color (d[0], d[1], d[2]). Seed a stack-based flood fill from all four corners plus the center pixel (to knock out both the exterior background and the interior hole), clearing matching pixels within a Chebyshev color distance of 40.
  3. Auto-center & square-crop: Compute the tight bounding box of the remaining opaque pixels (alpha > 40) and draw it centered into a normalized 768 × 768 square canvas.
  4. Raycast the inner opening: Cast 180 rays outward from the bounding box center (every 2°) until hitting an opaque pixel (alpha > 128). Sort the distances and take the 90th percentile as the opening ratio inner.

Why the 90th percentile instead of the minimum or average? Because ornate frames often have a small gem or spike jutting inward on one side; taking the 90th percentile ignores localized inward protrusions and reliably measures the true circular opening.

export async function prepareUploadedBorder( image: HTMLImageElement ): Promise<{ dataUrl: string; inner: number }> { const W = Math.min(1024, image.naturalWidth) const H = Math.round((image.naturalHeight * W) / image.naturalWidth) const canvas = document.createElement('canvas') canvas.width = W canvas.height = H const ctx = canvas.getContext('2d', { willReadFrequently: true })! ctx.drawImage(image, 0, 0, W, H) const pixels = ctx.getImageData(0, 0, W, H) const d = pixels.data const N = W * H let transparent = 0 let sampled = 0 for (let i = 3; i < d.length; i += 4 * 7) { sampled++ if (d[i] < 200) transparent++ } // Flood-fill away a flat background from the 4 corners + center if (transparent < sampled * 0.05) { const ref = [d[0], d[1], d[2]] const dist = (i: number) => Math.max( Math.abs(d[i * 4] - ref[0]), Math.abs(d[i * 4 + 1] - ref[1]), Math.abs(d[i * 4 + 2] - ref[2]) ) const bg = new Uint8Array(N) const stack = [0, W - 1, N - W, N - 1, (H >> 1) * W + (W >> 1)].filter( seed => dist(seed) < 40 ) stack.forEach(seed => { bg[seed] = 1 }) while (stack.length) { const i = stack.pop()! const x = i % W const y = (i / W) | 0 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const nx = x + dx const ny = y + dy if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue const j = ny * W + nx if (!bg[j] && dist(j) < 40) { bg[j] = 1 stack.push(j) } } } for (let i = 0; i < N; i++) { if (bg[i]) d[i * 4 + 3] = 0 } ctx.putImageData(pixels, 0, 0) } // Find tight opaque bounds let x0 = W, y0 = H, x1 = 0, y1 = 0 for (let i = 0; i < N; i++) { if (d[i * 4 + 3] > 40) { const x = i % W const y = (i / W) | 0 if (x < x0) x0 = x if (x > x1) x1 = x if (y < y0) y0 = y if (y > y1) y1 = y } } if (x1 <= x0 || y1 <= y0) throw new Error('Empty border image') const cx = (x0 + x1) / 2 const cy = (y0 + y1) / 2 const half = Math.max(x1 - x0, y1 - y0) / 2 + 2 // Cast 180 rays to measure the inner opening radius const rays: number[] = [] for (let k = 0; k < 360; k += 2) { const a = (k * Math.PI) / 180 for (let r = 0; r < half; r++) { const x = Math.round(cx + Math.cos(a) * r) const y = Math.round(cy + Math.sin(a) * r) if (x < 0 || y < 0 || x >= W || y >= H) break ifSource:https://dev.to/toby_snard/how-i-built-a-client-side-rpg-token-maker-with-html5-canvas-and-a-40-line-zero-dependency-zip-writer-lj4

Related posts