DEV Community

Quiet Stack Lab
Quiet Stack Lab

Posted on Originally published at quietstack-labs.github.io

Zero-Dependency 1080x1350 Shareable Cards in Pure HTML5 Canvas (Path2D + Deterministic FNV-1a Shuffle)

Most "shareable result card" web apps reach for html2canvas, a headless Chromium screenshot API, or a server-side Puppeteer worker. All three add latency, font-loading flakes, or CORS headaches.

When we built FateCard 2027 (a zero-backend, bilingual EN/KO 3-card archetype & 2027 aura generator), we wanted two guarantees:

  1. Deterministic draws with zero database: the same birth date + focus always yields the exact same 3-card spread across devices, with zero API calls or cookies.
  2. Crisp 1080×1350 PNG export in pure browser JS: no html2canvas, no SVG-to-<img> tainting bugs, and proper CJK + Latin typography fallback.

Here is the exact zero-dependency code powering both halves.


1. Preventing Silent Date Rollover & Seeding a Reproducible Shuffle

JavaScript's new Date("2026-02-31T00:00:00Z") silently rolls over to March 3 instead of failing. Round-tripping the ISO slice catches invalid calendar dates in two lines:

export function localIso(date = new Date()) {
  return [
    date.getFullYear(),
    String(date.getMonth() + 1).padStart(2, '0'),
    String(date.getDate()).padStart(2, '0'),
  ].join('-');
}

export function validBirth(value, today = localIso()) {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || value < '1900-01-01' || value > today) return false;
  const parsed = new Date(value + 'T00:00:00Z');
  return Number.isFinite(+parsed) && parsed.toISOString().slice(0, 10) === value;
}
Enter fullscreen mode Exit fullscreen mode

Once validated, we hash the composite key (FateCard|2027|<birth>|<focus>) with 32-bit FNV-1a (Math.imul + >>> 0 to keep unsigned 32-bit math exact) and feed it into a Numerical Recipes LCG inside a Fisher-Yates shuffle:

export function drawCards(birth, focus = '', today) {
  if (!validBirth(birth, today)) throw new RangeError('Invalid birth date');
  if (!['', 'love', 'wealth', 'turning'].includes(focus)) throw new RangeError('Invalid focus');

  let state = 2166136261;
  for (const code of 'FateCard|2027|' + birth + '|' + focus) {
    state = Math.imul(state ^ code.charCodeAt(0), 16777619) >>> 0;
  }

  const pool = [...deck];
  for (let index = pool.length - 1; index > 0; index--) {
    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
    const pick = Math.floor((state / 4294967296) * (index + 1));
    [pool[index], pool[pick]] = [pool[pick], pool[index]];
  }
  return pool.slice(0, 3);
}
Enter fullscreen mode Exit fullscreen mode

Why Fisher-Yates over Math.random() or modulo indexing?

  • No duplicates: you never draw the same card twice in a 3-card spread.
  • No server state: bookmarking or revisiting the same inputs produces identical results offline.
  • Zero floating-point seed drift: Math.imul(...) >>> 0 behaves identically across V8, SpiderMonkey, and JavaScriptCore.

2. Rendering Vector Icons onto a 1080×1350 Canvas with Path2D (Zero CORS Tainting)

Drawing external SVGs via new Image() frequently breaks canvas.toBlob() with SecurityError: Tainted canvases may not be exported or rasterizes blurry icons.

Instead, store each emblem as a plain SVG path string (card.path) in a 120×120 coordinate space and stroke it directly with new Path2D(card.path) inside a scaled ctx.save() / ctx.restore() block:

export async function downloadAura(cards, copy, lang) {
  const canvas = document.createElement('canvas');
  canvas.width = 1080;
  canvas.height = 1350; // 4:5 portrait ratio for Instagram / Threads / X
  const ctx = canvas.getContext('2d');

  const serif =
    lang === 'ko'
      ? '"Malgun Gothic", "Apple SD Gothic Neo", sans-serif'
      : 'Georgia, serif';

  // Radial parchment-obsidian backdrop + metallic foil double border
  const backdrop = ctx.createRadialGradient(540, 330, 45, 540, 500, 1000);
  backdrop.addColorStop(0, '#402c19');
  backdrop.addColorStop(1, '#131310');
  ctx.fillStyle = backdrop;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  const foil = ctx.createLinearGradient(80, 40, 990, 1290);
  foil.addColorStop(0, '#9b734a');
  foil.addColorStop(0.5, '#f1d293');
  foil.addColorStop(1, '#99673c');
  ctx.strokeStyle = foil;
  ctx.lineWidth = 2;
  ctx.strokeRect(34, 34, 1012, 1282);
  ctx.strokeRect(52, 52, 976, 1246);

  function label(text, x, y, size, color, width = 920) {
    ctx.fillStyle = color;
    ctx.textAlign = 'center';
    ctx.font = size + 'px ' + serif;
    ctx.fillText(text, x, y, width); // maxWidth prevents overflow in long translations
  }

  cards.forEach((card, index) => {
    const x = 94 + 300 * index;
    ctx.fillStyle = '#e9d9b3';
    ctx.fillRect(x, 535, 292, 390);
    ctx.strokeStyle = '#856034';
    ctx.strokeRect(x + 12, 547, 268, 366);

    ctx.save();
    ctx.translate(x + 36, 615);
    ctx.scale(220 / 120, 220 / 120);
    ctx.strokeStyle = '#654525';
    ctx.lineWidth = 2;
    ctx.lineJoin = 'round';
    ctx.stroke(new Path2D(card.path));
    ctx.restore();

    label(card.name[lang], x + 146, 882, 32, '#2b2014', 250);
  });

  const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
  if (!blob) throw new Error('PNG encoding failed');
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'fatecard-2027-destiny-aura.png';
  document.body.append(link);
  link.click();
  link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 60000);
}
Enter fullscreen mode Exit fullscreen mode

Three small details that saved real mobile bugs

  1. fillText(text, x, y, maxWidth): Passing maxWidth (250–270px per card) automatically compresses longer Korean or English card titles horizontally instead of letting them bleed across card borders.
  2. Deferred URL.revokeObjectURL(url): Revoking immediately after link.click() cancels the download on mobile Safari and several in-app browsers. A 60-second timeout keeps memory tidy without breaking iOS/Android downloads.
  3. Pure Path2D vector art: Because zero external images touch the canvas, canvas.toBlob() works offline, in file:// testing, and across strict CSP headers.

Try the Live App & Inspect the Source

If you've built client-side social cards with Path2D, OffscreenCanvas, or Web Workers, what font-loading or mobile-Safari gotchas did you hit?

Top comments (0)