setup()
setup() runs once when the sketch starts, and is the right place to configure the canvas, color settings, and initial values for any variable the rest of the sketch depends on.
function setup() {
// Create a canvas that fills the entire browser window
createCanvas(windowWidth, windowHeight);
// Set color mode to HSB for more vibrant and intuitive color control
// HSB: Hue (0-255), Saturation (0-255), Brightness (0-255)
colorMode(HSB, 255);
// Initialize ball position to the center of the canvas
x = width / 2;
y = height / 2;
// Initialize velocity with random values for varied movement
// The ball will move between -5 and 5 pixels per frame in both x and y directions
vx = random(-5, 5);
vy = random(-5, 5);
// Initialize the ball's color with a random vibrant hue, high saturation, and full brightness
// HSB ensures colors are consistently bright and saturated.
currentColor = color(random(255), 200, 255); // Random hue, high saturation (200/255), full brightness (255/255)
// Disable drawing outlines around shapes for a cleaner look
noStroke();
}
Line-by-line explanation (8 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that exactly matches the browser window's current width and height.
colorMode(HSB, 255);- Switches p5's color system from default RGB to Hue-Saturation-Brightness, with each channel ranging 0-255, making it easy to generate vibrant colors just by randomizing hue.
x = width / 2;- Places the ball's starting x-position exactly in the horizontal center of the canvas.
y = height / 2;- Places the ball's starting y-position exactly in the vertical center of the canvas.
vx = random(-5, 5);- Picks a random horizontal speed between -5 and 5, so the ball starts moving in an unpredictable direction.
vy = random(-5, 5);- Picks a random vertical speed between -5 and 5 for varied initial motion.
currentColor = color(random(255), 200, 255); // Random hue, high saturation (200/255), full brightness (255/255)- Builds a color object with a random hue but fixed high saturation and full brightness, guaranteeing the color always looks vivid rather than washed out or dark.
noStroke();- Turns off shape outlines so circles are drawn as solid fills without a border line.