Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Pure Browser Game Dev DSP & Pixel Tools: Writing a 16-Bit PCM WAV Synth & 4-Bit RPG Auto-Tiler With Zero Libraries

When you are mid-sprint inside Godot 4, Unity, or a custom HTML5 Canvas loop and need a crisp pickup chime or a 32×32 shoreline tilemap, launching a 2 GB DAW or external desktop suite kills momentum. Modern browsers alr

When you are mid-sprint inside Godot 4, Unity, or a custom HTML5 Canvas loop and need a crisp pickup chime or a 32×32 shoreline tilemap, launching a 2 GB DAW or external desktop suite kills momentum.

Modern browsers already ship two rock-solid deterministic engines out of the box:

  1. OfflineAudioContext — renders sample-accurate floating-point PCM audio faster than real time with zero hardware buffer underruns.
  2. HTML5 Canvas with ctx.imageSmoothingEnabled = false — locks pixel art to integer nearest-neighbor coordinates (16×16, 32×32) and exports clean PNGs and Tiled .tmj JSON directly.

Below are the exact zero-library implementations powering both workflows.

1. Part 1: Deterministic Game SFX + Raw 16-Bit PCM .wav Encoding in 35 Lines of JS

To keep SFX repeatable across builds and free of clipping pops when Godot or Unity triggers multiple overlapping hits:

  • Render at 44100 Hz mono inside an OfflineAudioContext(1, Math.ceil(44100 * durSec), 44100).
  • Shape pitch and gain with exponentialRampToValueAtTime (using 0.0001 instead of 0 to avoid Web Audio range errors).
  • Peak-normalize the rendered Float32Array to -0.8 dBFS (10 ** (-0.8 / 20) ≈ 0.912) so transients never clip Int16 (-32768..32767).
  • Write the standard 44-byte RIFF / WAVE / fmt / data header directly with DataView.
export async function synthCoinWav(durSec = 0.28) {
  const sr = 44100;
  const len = Math.ceil(sr * durSec);
  const ctx = new OfflineAudioContext(1, len, sr);
  const osc = ctx.createOscillator();
  const gain = ctx.createGain();

  osc.type = 'square';
  osc.frequency.setValueAtTime(987.77, 0);       // B5
  osc.frequency.setValueAtTime(1318.51, 0.065);  // E6 jump
  gain.gain.setValueAtTime(0.0001, 0);
  gain.gain.linearRampToValueAtTime(0.85, 0.005);
  gain.gain.exponentialRampToValueAtTime(0.0001, durSec);

  osc.connect(gain).connect(ctx.destination);
  osc.start(0);
  osc.stop(durSec);

  const samples = (await ctx.startRendering()).getChannelData(0);
  let peak = 0;
  for (let i = 0; i < samples.length; i++) peak = Math.max(peak, Math.abs(samples[i]));
  const norm = peak > 0 ? 0.912 / peak : 1; // -0.8 dBFS ceiling

  const buf = new ArrayBuffer(44 + samples.length * 2);
  const v = new DataView(buf);
  const wStr = (o, s) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); };
  wStr(0, 'RIFF'); v.setUint32(4, 36 + samples.length * 2, true); wStr(8, 'WAVEfmt ');
  v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
  v.setUint32(24, sr, true); v.setUint32(28, sr * 2, true); v.setUint16(32, 2, true);
  v.setUint16(34, 16, true); wStr(36, 'data'); v.setUint32(40, samples.length * 2, true);
  for (let i = 0; i < samples.length; i++) {
    const s = Math.max(-1, Math.min(1, samples[i] * norm));
    v.setInt16(44 + i * 2, s < 0 ? s * 32768 : s * 32767, true);
  }
  return new Blob([buf], { type: 'audio/wav' });
}

Because every envelope breakpoint uses explicit OfflineAudioContext sample timestamps rather than setTimeout, exporting the same preset twice produces bit-identical PCM waveforms.

2. Part 2: 4-Bit Cardinal Auto-Tile Bitmasking (N=1, E=2, S=4, W=8) for 16×16 RPG Maps

Manual edge painting on 16×16 pixel RPG tilesets is tedious and error-prone. A 4-bit cardinal bitmask maps every tile (x, y) cleanly to one of 16 (0..15) shoreline, cobblestone path, or dungeon wall variants in 10 lines of JavaScript:

// Bit weights: North = 1, East = 2, South = 4, West = 8
export function getCardinalMask(grid, x, y, targetId) {
  const h = grid.length;
  const w = grid[0].length;
  const same = (nx, ny) => ny >= 0 && ny < h && nx >= 0 && nx < w && grid[ny][nx] === targetId;

  let mask = 0;
  if (same(x, y - 1)) mask |= 1; // N
  if (same(x + 1, y)) mask |= 2; // E
  if (same(x, y + 1)) mask |= 4; // S
  if (same(x - 1, y)) mask |= 8; // W
  return mask; // 0..15 index into 4x4 or 1x16 tileset strip
}

Exporting Crisp PNGs & Valid Tiled 1.10 .tmj JSON

When rendering the 16×16 map onto an export <canvas> or zooming the editor viewport:

  • Always set ctx.imageSmoothingEnabled = false after resizing canvas.width / canvas.height (resizing a canvas resets its 2D context state back to bilinear smoothing!).
  • When exporting for Tiled 1.10 / Godot TileMapLayer, emit 1-based global tile IDs (gid = mask + 1, with 0 reserved for empty cells) inside a standard .tmj structure:
export function toTiledJson(grid, targetId, tileSize = 16) {
  const height = grid.length;
  const width = grid[0].length;
  const data = [];
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      data.push(grid[y][x] === targetId ? getCardinalMask(grid, x, y, targetId) + 1 : 0);
    }
  }
  return JSON.stringify({
    compressionlevel: -1, height, width, infinite: false, orientation: 'orthogonal',
    renderorder: 'right-down', tiledversion: '1.10.2', tileheight: tileSize, tilewidth: tileSize,
    type: 'map', version: '1.10',
    layers: [{ id: 1, name: 'Ground', type: 'tilelayer', visible: true, opacity: 1, x: 0, y: 0, width, height, data }],
    tilesets: [{ firstgid: 1, name: 'autotile_16', tilewidth: tileSize, tileheight: tileSize, tilecount: 16, columns: 4 }]
  }, null, 2);
}

3. Try Both Tools Live in Your Browser (Zero Login)

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.