setup()
setup() runs once when the sketch starts. It prepares the canvas, records the starting time, and initializes all variables the draw loop will need. Notice how millis() is called here to create a reference point for calculating elapsed time throughout the animation.
function setup() {
createCanvas(windowWidth, windowHeight);
startTime = millis(); // Record the start time when the sketch begins
remainingTimeMs = TIMER_DURATION_MS;
// Initialize ball properties
ballRadius = min(width, height) / 10; // Ball size relative to canvas
ballX = width / 2;
ballY = height / 2;
ballSpeedX = random(3, 7) * (random() > 0.5 ? 1 : -1); // Random speed and direction
ballSpeedY = random(3, 7) * (random() > 0.5 ? 1 : -1);
textAlign(CENTER, CENTER); // Center align text
textSize(32); // Set text size for the timer
}
Line-by-line explanation (10 lines)
🔧 Subcomponents:
ballRadius = min(width, height) / 10; // Ball size relative to canvas
Sets the ball's size proportionally to the canvas dimensions so it scales responsively
ballSpeedX = random(3, 7) * (random() > 0.5 ? 1 : -1); // Random speed and direction
Picks a random speed between 3 and 7 pixels/frame and randomly chooses left or right direction
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, making the timer fullscreen
startTime = millis(); // Record the start time when the sketch begins- millis() returns milliseconds since the sketch started—storing it now lets us calculate elapsed time later
remainingTimeMs = TIMER_DURATION_MS;- Initializes remaining time to the full duration (5 minutes in milliseconds)
ballRadius = min(width, height) / 10; // Ball size relative to canvas- Calculates ball size as 1/10 of the smaller canvas dimension, so it scales on different screen sizes
ballX = width / 2;- Places the ball's center at the horizontal midpoint of the canvas
ballY = height / 2;- Places the ball's center at the vertical midpoint of the canvas
ballSpeedX = random(3, 7) * (random() > 0.5 ? 1 : -1); // Random speed and direction- Creates a random horizontal velocity between 3 and 7 (or -3 to -7), so the ball moves left or right unpredictably
ballSpeedY = random(3, 7) * (random() > 0.5 ? 1 : -1);- Creates a random vertical velocity, making the ball bounce at a varied angle
textAlign(CENTER, CENTER); // Center align text- Centers all text both horizontally and vertically around the x,y coordinates you pass to text()
textSize(32); // Set text size for the timer- Sets the font size to 32 pixels for displaying the countdown