setup()
setup() runs once when the sketch starts. It is the perfect place to initialize your canvas and create all the objects your animation will use. The loop here demonstrates a common pattern: repeat an action N times and store the results in an array.
function setup() {
createCanvas(windowWidth, windowHeight);
for (let i = 0; i < 100; i++) {
particles.push(new Particle(random(width), random(height)));
}
}
Line-by-line explanation (3 lines)
🔧 Subcomponents:
for (let i = 0; i < 100; i++) {
Creates 100 Particle objects at random positions and adds them to the particles array
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window—windowWidth and windowHeight are p5.js variables that update if the user resizes the browser
for (let i = 0; i < 100; i++) {- Loops 100 times, once for each particle you want to create
particles.push(new Particle(random(width), random(height)));- Creates a new Particle object with a random starting position (somewhere on the canvas) and adds it to the particles array using push()