genart.dev

Canvas 2D

Canvas 2D renderer — algorithm contract and template

Canvas 2D Renderer

The Canvas 2D renderer uses the browser's native CanvasRenderingContext2D API. No external dependencies — lightweight and fast.

Algorithm contract

function sketch(ctx, state)
ArgumentTypeDescription
ctxCanvasRenderingContext2D2D drawing context
stateobjectRuntime state

State object

PropertyTypeDescription
state.canvas.widthnumberCanvas width
state.canvas.heightnumberCanvas height
state.seednumberRandom seed
state.paramsobjectParameter values
state.colorPalettestring[]Hex color array

Required return

return {
  initializeSystem() {
    // Rebuild drawing from current state
  }
};

Validation

  • Must define function sketch(ctx, state) with two arguments

Template

function sketch(ctx, state) {
  const { width, height } = state.canvas;

  function initializeSystem() {
    ctx.clearRect(0, 0, width, height);
    // generative algorithm here
  }

  return { initializeSystem };
}

CDN dependency

None — Canvas 2D is browser-native.

Renderer configuration

{
  "renderer": {
    "type": "canvas2d"
  }
}

Tips

  • Use a seeded PRNG (e.g., mulberry32) for reproducible randomness — Math.random() is not seedable
  • Canvas 2D is the lightest renderer with zero CDN overhead
  • Best for 2D graphics that don't need p5.js utilities
  • Access colors via state.colorPalette[index] (hex strings like "#FF6B35")
  • For animation, return an animate() method alongside initializeSystem()