Whenever a web app needs a "Share to Instagram Story" button, the default instinct is reaching for html2canvas or html-to-image to snapshot an existing DOM card.
Then you test on an iPhone inside iOS Safari or an in-app WebView.
While building the client-side 9:16 Story exporter and 78-card shuffle engine for VibeKit, I hit every classic DOM-to-image failure mode on WebKit: missing custom serif fonts on first tap, SecurityError tainted canvases, blurry DPR scaling mismatches, and 600ms main-thread stalls right as the mobile share sheet tried to open.
Replacing DOM cloning with direct 1080x1920 HTML5 2D Canvas primitives dropped render time below 12ms and eliminated every WebKit quirk. I extracted the layout math, greedy word-wrapper, privacy boundary, and rejection-sampled shuffler into a zero-dependency MIT module: canvas-story-deck-kit on GitHub, alongside an interactive 1080x1920 Canvas2D verifier.
Here are four practical front-end lessons from shipping it in production.
1. Why html2canvas and foreignObject Break on iOS Safari
DOM-snapshot libraries either walk your live tree with getComputedStyle() and inline hundreds of CSS declarations into an SVG <foreignObject> (html-to-image), or re-implement CSS box layout in JavaScript (html2canvas). On mobile WebKit, three issues surface repeatedly:
- Blank Webfonts on First Tap: WebKit isolates SVG image resources. Even after
document.fonts.readyresolves on the page, Base64@font-facerules injected inside<foreignObject>frequently miss the first rasterization pass and fall back to system fonts. - Tainted Canvas Errors: Any cross-origin stylesheet rule, mask, or external sub-resource inside
<foreignObject>marks the<canvas>origin-unclean and throws aSecurityErrorinsidetoBlob(). - 600ms Main-Thread Stalls: Cloning computed styles across dozens of nodes blocks mobile CPUs long enough to expire Safari's transient user-activation window before
navigator.share()runs.
Drawing directly onto an offscreen 1080x1920 2D context bypasses the DOM completely, painting radial gradients, card frames, badges, and typography in 4ms to 11ms. Gate Web Share Level 2 behind (pointer: coarse) so touch devices open the native share sheet while desktop browsers trigger an immediate .png download instead of macOS Safari's desktop AirDrop menu:
async function exportStoryCanvas( canvas: HTMLCanvasElement, fileName: string, shareTitle: string ): Promise<"shared" | "downloaded" | "cancelled"> { const blob = await new Promise<Blob>((resolve, reject) => { canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("PNG failed"))), "image/png"); }); if (window.matchMedia("(pointer: coarse)").matches && navigator.canShare) { const file = new File([blob], fileName, { type: "image/png" }); try { if (navigator.canShare({ files: [file] })) { await navigator.share({ files: [file], title: shareTitle }); return "shared"; } } catch (err) { if (err instanceof DOMException && err.name === "AbortError") return "cancelled"; } } const url = URL.createObjectURL(blob); const a = Object.assign(document.createElement("a"), { href: url, download: fileName }); a.click(); setTimeout(() => URL.revokeObjectURL(url), 4000); return "downloaded"; } 2. 9:16 UI Safe Zones, Greedy measureText Wrap, and 180° Card Pivots
Moving off CSS means owning two layout problems directly: social overlay safe zones and multi-line text measurement.
Locking Core Content Inside y: 220..1660
Centering artwork across the full 1080x1920 frame puts titles and footers right underneath native platform overlays on Instagram Stories, TikTok, and Pinterest:
- Top
0..220px: Story progress bars, avatar, username, audio pill, and close button. - Bottom
1660..1920px(260px): Reply input bar, reaction buttons, and the home indicator.
That leaves a 1440px safe vertical stage (y: 220..1660). Both our single-card Yes or No Tarot draw and three-card Situationship Tarot Spread constrain every semantic block (kicker pill, card slots, answer badge, summary rows, and footer mark) inside x: 84..996 and y: 220..1660.
Pure Metric-Callback Word Wrapping
ctx.fillText() only paints single lines. Accepting a width callback (text: string) => number decouples greedy line breaking and ellipsis clamping from the browser DOM so the exact same function runs against ctx.measureText(s).width in production and inside node --test:
export function wrapParagraphToLines(text, maxWidth, measureWidth, maxLines = 4) { const words = text.trim().replace(/\s+/g, " ").split(" ").filter(Boolean); if (!words.length) return []; const lines = []; let current = words[0]; for (let i = 1; i < words.length; i += 1) { const next = `${current} ${words[i]}`; if (measureWidth(next) <= maxWidth) current = next; else { lines.push(current); current = words[i]; } } lines.push(current); if (lines.length <= maxLines) return lines; const clamped = lines.slice(0, maxLines); let last = clamped[maxLines - 1].replace(/[.,;:!?-]+$/, ""); while (last.length > 1 && measureWidth(`${last}…`) > maxWidth) { last = last.slice(0, -1).trimEnd(); } clamped[maxLines - 1] = `${last.replace(/[.,;:!?-]+$/, "")}…`; return clamped; } In deck-story-kit.mjs, a pre-pass also hyphenates single unbroken tokens wider than maxWidth so long strings never bleed past card padding.
Upside-Down Reversed Cards via Center-Pivot Rotation
When a drawn card is reversed (180°), its artwork must flip upside-down without shifting its rounded-rectangle frame or drop shadow. Translating to (cx, cy) = (x + width / 2, y + height / 2) and rotating by Math.PI keeps [x, x + width] x [y, y + height] invariant:
ctx.save(); roundRectPath(ctx, x, y, width, height, radius); ctx.clip(); if (orientation === "reversed") { ctx.translate(x + width / 2, y + height / 2); ctx.rotate(Math.PI); ctx.drawImage(img, -width / 2, -height / 2, width, height); } else { ctx.drawImage(img, x, y, width, height); } ctx.restore(); In matrix form T(cx, cy) * R(π) * T(-cx, -cy), this equals ctx.transform(-1, 0, 0, -1, 2 * cx, 2 * cy), making pivot invariance trivial to verify in headless tests.
3. Rejection-Sampled Web Crypto Shuffles and Local-Date Daily Seeds
Card mechanics need two entropy modes: unbiased cryptographic randomness for live draws, and deterministic repeatability for daily cards.
Fixing Uint32 % 78 Modulo Bias
Taking crypto.getRandomValues(new Uint32Array(1))[0] % 78 still leaves a tiny modulo bias: 2^32 = 4,294,967,296 = 55,063,683 * 78 + 22, giving indices 0..21 one extra mapping over 22..77. Rejecting the top 22 values (>= 4,294,967,274) inside backward Fisher-Yates makes all 78! permutations equiprobable, paired with an independent 1-bit draw for upright/reversed orientation:
const UINT32_RANGE = 0x100000000; export function cryptoRandomInt(maxExclusive) { const threshold = UINT32_RANGE - (UINT32_RANGE % maxExclusive); const buf = new Uint32Array(1); while (true) { crypto.getRandomValues(buf); if (buf[0] < threshold) return buf[0] % maxExclusive; } } export function shuffleDeckUnbiased(deck) { const copy = deck.slice(); for (let i = copy.length - 1; i > 0; i -= 1) { const j = cryptoRandomInt(i + 1); [copy[i], copy[j]] = [copy[j], copy[i]]; } return copy; } Local YYYY-MM-DD Seeds vs. UTC Midnight Drift
For our Daily Vibe Card, refreshing at 9:00 AM and 9:00 PM should return the same card with zero backend state. Never seed daily draws with new Date().toISOString().slice(0, 10): toISOString() converts to UTC first, rolling New York (UTC-5) users onto tomorrow's card at 7:00 PM local time. Build "YYYY-MM-DD" from local getFullYear(), getMonth() + 1, and getDate(), mix the string with FNV-1a, and drive a 32-bit mulberry32 PRNG.
4. Privacy by Type Design at the Export Boundary
In reflection flows like Career Decision Yes or No Tarot, visitors often type candid context before drawing ("Should I take the competing offer or stay through Q2?").
People want to share their drawn card and takeaway on Stories, never their private prompt. Instead of hiding DOM inputs with fragile CSS classes during capture, omit user-typed fields from the export type altogether:
export type SingleCardStoryInput = { kicker?: string; card: TarotCard; orientation: "upright" | "reversed"; insight: string; nextMove: string; // `question`, `prompt`, and `notes` are intentionally excluded at the type boundary }; For untyped callers, buildPrivacySafeStoryPayload() copies only allowlisted symbolic fields and strips question, prompt, notes, and rawInput before any Canvas2D fillText call executes, guaranteeing private journal entries never touch the exported PNG bitmap.
Grab the Code or Test Live
- GitHub Repo &
node --testSuite: github.com/kaiyilu/canvas-story-deck-kit - Live
1080x1920Safe-Zone Verifier: kaiyilu.github.io/canvas-story-deck-kit - Production App: usevibekit.com
