setup()
setup() runs once and is the perfect place to configure the canvas, precompute values like gradientColors that never change, and create any HTML UI elements you need before the animation loop starts.
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke(); // Disable outlines for shapes
colorMode(RGB); // Use RGB color mode
// Define gradient colors (dark blue/black) for the background
gradientColors = [
color(0, 0, 20), // Darkest blue/black
color(0, 0, 40), // Slightly lighter
color(0, 0, 60), // Even lighter
color(0, 0, 80) // Lightest blue/black
];
generateStars(); // Populate the stars array
// Create UI elements
clearButton = createButton('Clear Constellations');
clearButton.position(20, 20); // Position button in top-left
clearButton.mousePressed(clearConnections); // Attach clear function
clearButton.addClass('p5-button'); // Add CSS class for styling
infoDiv = createDiv(`Stars: ${starCount} | Lines: ${lineCount}`);
infoDiv.position(20, 60); // Position info below button
infoDiv.addClass('p5-info'); // Add CSS class for styling
}
Line-by-line explanation (8 lines)
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window.
noStroke();- Turns off shape outlines globally so circles and rects draw with fill only by default.
colorMode(RGB);- Explicitly sets the color mode to RGB (the default), used for clarity.
gradientColors = [ ... ];- Builds an array of four color() objects that go from very dark blue to lighter blue, used later to paint the sky gradient.
generateStars();- Calls the helper function that fills the stars array with new Star objects at random positions.
clearButton = createButton('Clear Constellations');- Creates an HTML button element using p5's DOM API.
clearButton.mousePressed(clearConnections);- Wires the button up so clicking it calls clearConnections(), wiping all constellation lines.
infoDiv = createDiv(`Stars: ${starCount} | Lines: ${lineCount}`);- Creates a text div showing the current star and line counts, using a template literal to insert the numbers.