Developers2 of 7
p5.js sketches
One sketch.js, global mode. p5.js supplied.
One folder, one sketch.js declaring setup() or draw().
my-sketch/
sketch.js
Global mode, as the p5 web editor writes it. Operatour supplies p5.js: no
library, no index.html, works offline.
The smallest one that works
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(0);
circle(width / 2, height / 2, 100 + sialk.audio.level * 400);
}
Drag the folder on. Done.
Making it react
Everything is on window.sialk, the audio contract:
function draw() {
background(0, 0, 0, 40);
const r = 100 + sialk.audio.bass * 300;
stroke(255, 200, 120);
noFill();
circle(width / 2, height / 2, r);
// The spectrum, as 64 bars
const bins = sialk.audio.spectrum;
for (let i = 0; i < bins.length; i++) {
const h = bins[i] * height * 0.66;
rect((i / bins.length) * width, height - h, width / bins.length - 2, h);
}
}
To also run in a plain browser, guard for the contract:
const audio = window.sialk?.audio ?? { level: 0, bass: 0, spectrum: new Float32Array(64) };
More than one file
A p5 editor export has an index.html loading its scripts. Operatour reads it
for one thing only: which of the folder's own files load, in what order. Then
it loads them the same way.
- p5 itself is always Operatour's copy; a
libraries/p5.min.jsin the folder is ignored. - An addon beside it, such as
p5.sound.min.js, is yours and loads as asked. - Images in
assets/load by the same relative paths as in the editor.
Canvas size
Use createCanvas(windowWidth, windowHeight): Operatour sizes the surface,
the sketch fills it.
A canvas smaller than the layer is transformed to fit, not resized: the
sketch keeps its own coordinates, width and height.
Transparency
No background() call, transparent layer; often what you want in a stack.
For opaque, background(0). See layers.
Cost
p5 is resolution-independent. Cost is per vertex and per JavaScript statement: four times the pixels is close to free; a 60,000-point cloud runs the same at 4K as at 720p.
Cost is count. A quarter of a million points is slow at any resolution. Struggling sketch: reduce the number of things, not the frame size.
The exact opposite of GLSL. Knowing which you are writing is most of "will this run".
3D
createCanvas(w, h, WEBGL) works as in p5 everywhere else.