setup()
setup() runs once when the sketch starts. Here it's used not just to create the visible canvas but also a second, hidden graphics buffer (pathLayer) - a common p5.js pattern for building up a drawing over time without redrawing everything each frame.
function setup() {
createCanvas(windowWidth, windowHeight);
colorMode(HSB, 360, 100, 100, 100); // HSB with alpha 0–100
smooth();
// Layer that accumulates the drawing over time
pathLayer = createGraphics(windowWidth, windowHeight);
pathLayer.colorMode(HSB, 360, 100, 100, 100);
pathLayer.background(0, 0, 0); // black
pathLayer.smooth();
pathLayer.strokeCap(ROUND);
initSpiroParams();
}
Line-by-line explanation (8 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window.
colorMode(HSB, 360, 100, 100, 100);- Switches the main canvas to Hue-Saturation-Brightness color mode with ranges 0-360 for hue and 0-100 for saturation, brightness and alpha, which makes it easy to cycle through rainbow colors by just changing the hue number.
smooth();- Enables anti-aliasing so lines and circles look smooth instead of jagged.
pathLayer = createGraphics(windowWidth, windowHeight);- Creates a separate, invisible-until-drawn graphics buffer the same size as the canvas - this is where the permanent spirograph trail will live.
pathLayer.colorMode(HSB, 360, 100, 100, 100);- Sets the same HSB color mode on the buffer, since each graphics object has its own independent color settings.
pathLayer.background(0, 0, 0); // black- Fills the buffer with black once, giving the drawing a dark background to build up on.
pathLayer.strokeCap(ROUND);- Makes the ends of every line segment rounded instead of flat, which helps the glowing strokes blend smoothly into each other.
initSpiroParams();- Calls the helper function that calculates the spirograph's geometry (circle sizes, pen offset, starting position) based on the current canvas size.