Bash.tv → GitHub → itch.io

Draw 2D games fast and cleanly with the HTML5 Canvas 2D API. Frame structure, world vs screen space with transforms, sprites and sprite sheets, crisp pixel art, text, layers and offscreen caching, culling, batching state changes, blend modes, clipping, and what's slow (shadowBlur, filters, getImageData, huge canvases). Use for any plain-canvas game, "my canvas game is slow / blurry", drawing sp...

Download skill (.zip) Files on GitHub

Canvas 2D rendering

Frame structure

function render(alpha) {                                   // alpha = interpolation from a fixed-step loop (optional)
  ctx.setTransform(dpr * scale, 0, 0, dpr * scale, offX, offY);   // from screen.js (resize)
  ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H);           // clear by filling: cheaper than clearRect + bg draw
  ctx.save();
  ctx.translate(Math.round(-camera.x + W / 2), Math.round(-camera.y + H / 2));   // world space
  drawWorld(ctx);                                          // tiles, entities, particles (culled)
  ctx.restore();
  drawHUD(ctx);                                            // screen space: score, buttons, touch controls
}

Render reads state only. Never change game state while drawing.

Sprites

const img = await loadImage("assets/img/hero.png");        // new Image(); img.decode() before first use
// sheet frame (fx, fy) of size fw×fh at x, y, flipped when facing left:
ctx.save(); ctx.translate(x, y); if (flip) ctx.scale(-1, 1);
ctx.drawImage(img, fx * fw, fy * fh, fw, fh, -fw / 2, -fh / 2, fw, fh);
ctx.restore();

Speed rules

Fast Slow (avoid per frame)
drawImage of cached canvases / sprites shadowBlur, ctx.filter (pre-render glows to an offscreen canvas instead)
fillRect, simple paths getImageData / putImageData
Grouping draws by fillStyle / image Changing font, fillStyle, globalCompositeOperation every item
Culling off-screen objects Drawing the whole level every frame (cache static layers)
One canvas, dpr capped at 2 Several full-screen stacked canvases, or 3× dpr on phones

Cache static things: draw tilemaps, backgrounds and text labels that rarely change into an OffscreenCanvas (or a hidden canvas) once, then drawImage it. Redraw the cache only when it changes. For big maps, cache in chunks (e.g. 512×512).

Culling: skip anything whose bounds are outside camera ± W/2, H/2 plus a margin.

Text

Effects without WebGL

When to switch

Thousands of moving sprites, many particles, or shaders → PixiJS (pixijs-game-development) or Phaser (phaser-game-development, or the space’s game-kit-2d). Canvas 2D comfortably handles a few hundred to ~1–2k simple sprites at 60 fps on mid phones.