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)| Argument | Type | Description |
|---|---|---|
ctx | CanvasRenderingContext2D | 2D drawing context |
state | object | Runtime state |
State object
| Property | Type | Description |
|---|---|---|
state.canvas.width | number | Canvas width |
state.canvas.height | number | Canvas height |
state.seed | number | Random seed |
state.params | object | Parameter values |
state.colorPalette | string[] | 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 alongsideinitializeSystem()