setup()
setup() runs once when the sketch starts. It initializes the canvas, creates the background gradient, and spawns all 100 birds with random positions and directions. Using createGraphics for the sky gradient is efficient because we only draw it once, then reuse it in draw() with transparency to create motion trails.
function setup() {
createCanvas(windowWidth, windowHeight);
// Create sky gradient once
skyGraphic = createGraphics(windowWidth, windowHeight);
drawSkyGradient(skyGraphic);
// Initialize flock
for (let i = 0; i < NUM_BOIDS; i++) {
boids.push(new Boid());
}
// Smoother visuals
frameRate(60);
}
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that matches the window dimensions
skyGraphic = createGraphics(windowWidth, windowHeight);
drawSkyGradient(skyGraphic);
Creates an off-screen graphics buffer and draws the blue gradient once for efficiency
for (let i = 0; i < NUM_BOIDS; i++) {
boids.push(new Boid());
}
Creates 100 Boid objects with random positions and velocities, adding them to the boids array
frameRate(60);
Sets the animation to run at 60 frames per second for smooth motion
Line by Line:
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window. windowWidth and windowHeight are p5.js variables that automatically update when the window is resized
skyGraphic = createGraphics(windowWidth, windowHeight);- Creates an off-screen graphics buffer (like a hidden canvas) the same size as the main canvas. This is used to store the sky gradient so we don't have to redraw it every frame
drawSkyGradient(skyGraphic);- Calls the function that draws the blue gradient into the skyGraphic buffer once during setup
for (let i = 0; i < NUM_BOIDS; i++) {- Loops 100 times (NUM_BOIDS = 100) to create each bird in the flock
boids.push(new Boid());- Creates a new Boid object with random starting position and velocity, then adds it to the boids array
frameRate(60);- Tells p5.js to run the draw() function 60 times per second, creating smooth animation