setup()
setup() is called once when the sketch starts. It's where you prepare your canvas size, initialize variables, and set default styling. Everything you do here happens before the first frame draws.
🔬 These lines set the ball's starting speed. What happens if you change 5 to 10? To 0.5? How does the initial velocity range affect the animation?
ballVX = random(-5, 5); // Random horizontal speed between -5 and 5
ballVY = random(-5, 5); // Random vertical speed between -5 and 5
function setup() {
// Create a canvas that fills the entire window
createCanvas(windowWidth, windowHeight);
// Initialize the ball at the center of the canvas with a random initial velocity
ballX = width / 2;
ballY = height / 2;
ballVX = random(-5, 5); // Random horizontal speed between -5 and 5
ballVY = random(-5, 5); // Random vertical speed between -5 and 5
// Set styling for the ball
noStroke(); // No border for the ball
fill(255, 100, 100); // Reddish color for the ball
// Set styling for the loading bar text
textSize(16); // Font size for the loading text
textAlign(LEFT, CENTER); // Align text to the left and vertically center
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire browser window using windowWidth and windowHeight variables
ballX = width / 2;
Places the ball at the horizontal center of the canvas
ballVX = random(-5, 5);
Gives the ball a random starting horizontal velocity between -5 and 5 pixels per frame
fill(255, 100, 100);
Sets the fill color to a soft red (RGB: 255, 100, 100) for all shapes drawn after this line
createCanvas(windowWidth, windowHeight);- Creates a drawing canvas that automatically matches the current browser window size using p5.js global variables
ballX = width / 2;- Sets the ball's starting horizontal position to the exact center of the canvas (width divided by 2)
ballY = height / 2;- Sets the ball's starting vertical position to the exact center of the canvas
ballVX = random(-5, 5);- Picks a random velocity between -5 and 5 for horizontal movement, giving the ball a unique starting direction each time
ballVY = random(-5, 5);- Picks a random velocity between -5 and 5 for vertical movement, creating unpredictable diagonal motion
noStroke();- Removes the black outline that p5.js normally draws around shapes
fill(255, 100, 100);- Sets the color for all filled shapes to a soft red by specifying RGB values
textSize(16);- Sets the font size for any text drawn later to 16 pixels
textAlign(LEFT, CENTER);- Aligns text so its left edge starts at the x position and it centers vertically around the y position