setup()
setup() runs exactly once when the sketch starts. It's the right place to build data structures - like this array of star objects - that draw() will read and animate on every subsequent frame.
🔬 This loop fills the sky with 300 stars. What happens visually if numStars is changed to 50? To 1500?
for (let i = 0; i < numStars; i++) {
stars.push({
x: random(width),
y: random(height),
size: random(1, 4),
brightness: random(100, 255),
twinkleOffset: random(1000) // Unique offset for each star's twinkle
});
}
function setup() {
createCanvas(windowWidth, windowHeight);
// Initialize stars with random positions, sizes, brightness, and twinkle offsets
for (let i = 0; i < numStars; i++) {
stars.push({
x: random(width),
y: random(height),
size: random(1, 4),
brightness: random(100, 255),
twinkleOffset: random(1000) // Unique offset for each star's twinkle
});
}
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
for (let i = 0; i < numStars; i++) {
Creates numStars star objects with randomized position, size, brightness, and twinkle timing, storing each one in the stars array
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window, using p5's built-in windowWidth and windowHeight variables
for (let i = 0; i < numStars; i++) {- Repeats the code inside the loop numStars (300) times to build up the full array of stars
x: random(width),- Picks a random horizontal position anywhere across the canvas width
y: random(height),- Picks a random vertical position anywhere across the canvas height
size: random(1, 4),- Gives each star a random diameter between 1 and 4 pixels so they aren't all identical
brightness: random(100, 255),- Sets a base brightness value that draw() will later vary up and down for the twinkle effect
twinkleOffset: random(1000) // Unique offset for each star's twinkle- Gives each star its own starting point along the noise curve, so all 300 stars twinkle out of sync with each other instead of flashing in unison