setup()
setup() runs once at the start of the sketch. Here it prepares two canvases (visible and offscreen), builds the DOM sliders, and kicks off the first pendulum layout.
function setup() {
// Create the main canvas
createCanvas(windowWidth, windowHeight);
// Use HSB color mode for easy gradient generation
colorMode(HSB, 360, 100, 100, 100);
// Create the offscreen graphics buffer for trails
trailGraphics = createGraphics(windowWidth, windowHeight);
trailGraphics.colorMode(HSB, 360, 100, 100, 100);
// Fill the trail buffer with a dark background initially
trailGraphics.background(0, 0, 0, 100);
// --- Create Sliders ---
// Pendulum Count Slider
pendulumCountLabel = createP('Pendulum Count: ');
pendulumCountLabel.position(10, 10);
pendulumCountLabel.class('p5js_label'); // Add class for styling
pendulumCountSlider = createSlider(5, 50, 25, 1); // Min 5, Max 50, Initial 25, Step 1
pendulumCountSlider.position(10, 40);
pendulumCountSlider.class('p5js_slider'); // Add class for styling
// Re-initialize pendulums whenever the slider changes
pendulumCountSlider.input(initializePendulums);
// Gravity Slider
gravityLabel = createP('Gravity: ');
gravityLabel.position(10, 70);
gravityLabel.class('p5js_label'); // Add class for styling
gravitySlider = createSlider(0.1, 2, g, 0.01); // Min 0.1, Max 2, Initial g, Step 0.01
gravitySlider.position(10, 100);
gravitySlider.class('p5js_slider'); // Add class for styling
// Set the initial pendulum count and initialize them
currentPendulumCount = pendulumCountSlider.value();
initializePendulums();
}
Line-by-line explanation (8 lines)
createCanvas(windowWidth, windowHeight);- Makes the main visible canvas fill the whole browser window.
colorMode(HSB, 360, 100, 100, 100);- Switches to Hue-Saturation-Brightness color mode so colors can be picked by rotating a hue value from 0-360, which is perfect for rainbow gradients.
trailGraphics = createGraphics(windowWidth, windowHeight);- Creates a second, invisible canvas the same size as the window - this buffer will hold the fading pendulum trails separately from the main canvas.
trailGraphics.background(0, 0, 0, 100);- Fills the trail buffer with a fully opaque black background so it starts clean.
pendulumCountSlider = createSlider(5, 50, 25, 1);- Creates a slider ranging from 5 to 50 pendulums, starting at 25, moving in steps of 1.
pendulumCountSlider.input(initializePendulums);- Registers initializePendulums as the callback that runs every time the user drags this slider.
gravitySlider = createSlider(0.1, 2, g, 0.01);- Creates a finer slider for gravity, from 0.1 to 2, starting at the current value of g, moving in 0.01 steps.
initializePendulums();- Builds the initial set of pendulum objects before the first frame is drawn.