genart.dev

p5.js

p5.js renderer — algorithm contract, template, and CDN dependencies

p5.js Renderer

The p5.js renderer uses p5.js in instance mode for 2D creative coding. It's the default renderer and the best choice for most generative art.

Algorithm contract

function sketch(p, state)
ArgumentTypeDescription
pp5p5.js instance (instance mode)
stateobjectRuntime state with canvas, params, colors, seed

State object

PropertyTypeDescription
state.WIDTHnumberCanvas width
state.HEIGHTnumberCanvas height
state.SEEDnumberRandom seed
state.PARAMSobjectParameter values keyed by name
state.COLORSobjectColor palette keyed by name

Required return

The sketch function must return an object with initializeSystem():

return {
  initializeSystem() {
    // Rebuild the visual system from current state
  }
};

initializeSystem() is called whenever parameters, colors, or seed change.

Validation

  • Must define function sketch(p, state) (function declaration, const/let/var, or arrow function)
  • Must assign p.setup

Template

function sketch(p, state) {
  const { WIDTH, HEIGHT, SEED, PARAMS, COLORS } = state;

  p.setup = () => {
    p.createCanvas(WIDTH, HEIGHT);
    p.randomSeed(SEED);
  };

  p.draw = () => {
    p.background(COLORS.background);
    // generative algorithm here
  };

  return {
    initializeSystem() {
      // rebuild from state
    }
  };
}

CDN dependency

LibraryVersionURL
p5.js1.11.3https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.3/p5.min.js

The CDN script is loaded automatically in the rendering iframe.

Renderer configuration

{
  "renderer": {
    "type": "p5",
    "version": "1.x"
  }
}

Tips

  • Use p.randomSeed(SEED) and p.noiseSeed(SEED) for reproducible output
  • Access parameters via state.PARAMS.paramName
  • Use p.draw for animated sketches or set p.noLoop() in p.setup for static output
  • The rendering runs in a sandboxed iframe with the CDN script injected