setup()
setup() runs exactly once when the sketch starts, making it the ideal place for expensive one-time work like building a color palette. By precomputing barColors here instead of inside draw(), the sketch avoids calling lerpColor() 32 times every single frame - a good performance habit to learn early.
🔬 This loop builds the gradient array once at startup. What happens if you swap the arguments so it reads lerpColor(cyan, purple, t) instead - does the gradient direction flip?
for (let i = 0; i < NUM_BARS; i++) {
const t = i / (NUM_BARS - 1);
barColors[i] = lerpColor(purple, cyan, t);
}
function setup() {
createCanvas(windowWidth, windowHeight);
rectMode(CENTER);
noStroke();
colorMode(RGB);
// Precompute a horizontal gradient from purple to cyan for the bars
// https://p5js.org/reference/#/p5/lerpColor
const purple = color(180, 50, 255);
const cyan = color(0, 255, 255);
for (let i = 0; i < NUM_BARS; i++) {
const t = i / (NUM_BARS - 1);
barColors[i] = lerpColor(purple, cyan, t);
}
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
for (let i = 0; i < NUM_BARS; i++) {
Calculates one interpolated color per bar, from purple to cyan, and stores them so draw() never has to recompute them every frame.
createCanvas(windowWidth, windowHeight)- Creates a canvas that fills the entire browser window.
rectMode(CENTER)- Changes rect() so its x/y arguments describe the shape's center instead of its top-left corner - important because bars are positioned by their middle point.
noStroke()- Turns off outlines on shapes so bars appear as solid, clean blocks of color.
colorMode(RGB)- Explicitly sets the color system to red/green/blue (this is actually p5's default, so this line is mostly for clarity).
const purple = color(180, 50, 255);- Defines the starting color of the gradient as a vivid purple.
const cyan = color(0, 255, 255);- Defines the ending color of the gradient as bright cyan.
const t = i / (NUM_BARS - 1);- Converts the bar index into a 0-to-1 fraction, so the first bar gets 0, the last bar gets 1, and everything in between is spread evenly.
barColors[i] = lerpColor(purple, cyan, t);- Blends purple and cyan by the fraction t and stores the result, so each bar gets its own step along the gradient.