How I Built a Client-Side RPG Token Maker with HTML5 Canvas and a 40-Line Zero-Dependency ZIP Writer
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
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:
- Simple
ctx.arc()/ polygon clipping breaks on ornate, asymmetric art borders. - Real-time metallic recoloring without sluggish per-pixel loops.
- Letting users upload their own bordersβeven opaque JPEGs with a solid background.
- 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 >= 180eliminates 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 aWeakMapkeyed by theHTMLImageElement, 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:
- Detect transparency: Sample every 7th pixel's alpha channel. If fewer than 5% of sampled pixels are transparent, treat the image as opaque.
-
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 of40. -
Auto-center & square-crop: Compute the tight bounding box of the remaining opaque pixels (
alpha > 40) and draw it centered into a normalized768 Γ 768square canvas. -
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 ratioinner.
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
if (d[(y * W + x) * 4 + 3] > 128) {
rays.push(r)
break
}
}
}
rays.sort((a, b) => a - b)
const inner = (rays[Math.floor(rays.length * 0.9)] || 0) / half
if (inner < 0.3) throw new Error('No clear opening detected')
const out = document.createElement('canvas')
out.width = out.height = 768
out
.getContext('2d')!
.drawImage(canvas, cx - half, cy - half, half * 2, half * 2, 0, 0, 768, 768)
return { dataUrl: out.toDataURL('image/png'), inner }
}
4. Replacing JSZip with a 40-Line Store-Only ZIP Writer
When users export a batch of portraits or a numbered minion set (e.g., 12 tokens with 01β12 badges), downloading 12 separate files triggers browser multi-download warnings. Packing them into a .zip file is a much cleaner UX.
My first instinct was npm install jszip. Then I stopped and thought about what we were actually zipping: already-compressed PNG and WebP blobs.
Running DEFLATE over PNG or WebP images gives you ~0% compression (sometimes the output is even a few bytes larger), burns CPU cycles on the main thread, and adds ~90 KB of JavaScript to the bundle.
The ZIP format explicitly supports compression method 0 (STORE)βno compression at all, just framing bytes plus a CRC-32 checksum per file. That entire spec fits in 40 lines of zero-dependency TypeScript:
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let n = 0; n < 256; n++) {
let c = n
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
}
table[n] = c >>> 0
}
return table
})()
function crc32(bytes: Uint8Array): number {
let crc = 0xffffffff
for (let i = 0; i < bytes.length; i++) {
crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8)
}
return (crc ^ 0xffffffff) >>> 0
}
export async function zipFiles(
files: Array<{ name: string; blob: Blob }>
): Promise<Blob> {
const encoder = new TextEncoder()
const parts: BlobPart[] = []
const central: Uint8Array[] = []
let offset = 0
for (const file of files) {
const data = new Uint8Array(await file.blob.arrayBuffer())
const name = encoder.encode(file.name)
const crc = crc32(data)
// Local File Header (30 bytes)
const local = new DataView(new ArrayBuffer(30))
local.setUint32(0, 0x04034b50, true) // Local file header signature
local.setUint16(4, 20, true) // Version needed (2.0)
local.setUint16(6, 0x0800, true) // UTF-8 filename flag
local.setUint16(8, 0, true) // Compression method: 0 (STORE)
local.setUint32(14, crc, true)
local.setUint32(18, data.length, true)
local.setUint32(22, data.length, true)
local.setUint16(26, name.length, true)
parts.push(local.buffer, name, data)
// Central Directory Header (46 bytes + filename)
const entry = new DataView(new ArrayBuffer(46))
entry.setUint32(0, 0x02014b50, true) // Central directory signature
entry.setUint16(4, 20, true) // Version made by
entry.setUint16(6, 20, true) // Version needed
entry.setUint16(8, 0x0800, true) // UTF-8 filename flag
entry.setUint32(16, crc, true)
entry.setUint32(20, data.length, true)
entry.setUint32(24, data.length, true)
entry.setUint16(28, name.length, true)
entry.setUint32(42, offset, true) // Relative offset of local header
const record = new Uint8Array(46 + name.length)
record.set(new Uint8Array(entry.buffer))
record.set(name, 46)
central.push(record)
offset += 30 + name.length + data.length
}
const centralSize = central.reduce((sum, r) => sum + r.length, 0)
// End of Central Directory Record (22 bytes)
const end = new DataView(new ArrayBuffer(22))
end.setUint32(0, 0x06054b50, true)
end.setUint16(8, files.length, true)
end.setUint16(10, files.length, true)
end.setUint32(12, centralSize, true)
end.setUint32(16, offset, true)
return new Blob([...parts, ...central, end.buffer], {
type: 'application/zip',
})
}
A few notes if you reuse this snippet:
- Setting bit 11 (
0x0800) in the general-purpose bit flag tells macOS Archive Utility, Windows Explorer, and Linuxunzipto decode filenames as UTF-8. - Because it's only needed when the user clicks "Download ZIP", load it lazily via
const { zipFiles } = await import('./zip')so it doesn't even touch the initial page bundle. - This is strictly for already-compressed binary formats (PNG, WebP, JPEG, MP3, MP4). If you're zipping JSON, SVG, or plain text, use a real DEFLATE implementation or
CompressionStream.
5. Small UX Details Worth Stealing
One tiny helper that saved users a surprising amount of manual dragging was smart initial framing for full-body character art:
export function initialPlacement(width: number, height: number) {
if (!width || !height || height / width <= 1.15) {
return { zoom: 1, x: 0, y: 0, rot: 0 }
}
// Tall full-body portraits usually have the face in the upper portion
const y = Math.min(1, Math.max(0, (height / width - 1) / 2 - 0.05))
return { zoom: 1, x: 0, y, rot: 0 }
}
Most fantasy character art is vertical (2:3 or 9:16). Centering a full-body illustration inside a circular token crops straight onto the character's belt or torso. Shifting y upward whenever height / width > 1.15 puts the face right inside the ring on drop.
Gotchas I Ran Into Along the Way
-
Always pass
{ willReadFrequently: true }when creating offscreen canvases meant forgetImageData(). Without it, Chrome logs performance warnings and incurs expensive GPU-to-CPU readbacks. -
Guard
getImageData()withtry/catch: If a border asset is ever served without properAccess-Control-Allow-Originheaders (orcrossOrigin = 'anonymous'), the canvas gets tainted and throws aSecurityError. Falling back cleanly toctx.arc()/hexPath()ensures the app never white-screens. -
Use
WeakMapfor derived canvases: Users love clicking through dozens of borders and color swatches. Caching derived masks and tinted canvases in aWeakMapkeyed by the source image prevents unbounded memory growth when images are replaced.
Try It Live
If you want to see the flood-fill masking, real-time metallic tinting, opaque border auto-keying, and 40-line ZIP export running in the browser, you can test it on FantasyGen Token Maker β drop in any portrait or your own opaque frame image, everything runs locally with no sign-up required.
If you've built similar client-side Canvas pipelines (or have tricks for speeding up offscreen pixel work with OffscreenCanvas / Workers), I'd love to hear how you approached it in the comments!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.