setup()
setup() runs once when the sketch starts. It's the perfect place to create your canvas and initialize any data that won't change during gameplay—like the starfield geometry.
function setup() {
createCanvas(windowWidth, windowHeight);
textFont('sans-serif'); // Use default system font (no preload needed)
// Precompute a simple starfield (static geometry, done once)
for (let i = 0; i < NUM_STARS; i++) {
stars.push({
x: random(width),
y: random(height),
r: random(1, 3),
twinkleOffset: random(TWO_PI)
});
}
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
for (let i = 0; i < NUM_STARS; i++)
Creates NUM_STARS star objects with random positions, sizes, and twinkle phases
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window; resizes dynamically if the window changes
textFont('sans-serif');- Sets the font for all text to use the system default sans-serif font (no external font loading needed)
for (let i = 0; i < NUM_STARS; i++) {- Loops NUM_STARS times (80 by default) to create each star object once
stars.push({- Adds a new star object to the stars array with four properties
x: random(width),- Random x position anywhere across the canvas width
r: random(1, 3),- Random radius between 1 and 3 pixels; controls the star's base size
twinkleOffset: random(TWO_PI)- Random phase offset (0 to 2π) so each star twinkles independently rather than all at once