setup()
setup() runs once when the sketch starts. It's where you initialize your canvas size, prepare sound objects, and set default drawing properties. Using windowWidth and windowHeight makes sketches responsive to any screen size.
function setup() {
createCanvas(windowWidth, windowHeight);
// Tip: Use windowWidth/windowHeight for responsive canvas
// Initialize the sound effect
clickSound = new p5.Oscillator('sine'); // A simple sine wave
clickSound.freq(440); // A-note frequency
clickSound.amp(0); // Start with 0 amplitude
clickSound.start();
// Set text properties
textSize(24);
textAlign(CENTER, CENTER);
fill(0); // Black text
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire browser window, enabling responsive layout
clickSound = new p5.Oscillator('sine');
Creates a sound generator using a sine wave, ready to play beep sounds
textAlign(CENTER, CENTER);
Sets all text drawn later to be centered both horizontally and vertically
createCanvas(windowWidth, windowHeight);- Creates a canvas matching the full browser window size, so the sketch uses all available space
clickSound = new p5.Oscillator('sine');- Creates a sound oscillator using a smooth sine wave—the building block for our beep sound
clickSound.freq(440);- Sets the oscillator to play at 440 Hz, which is the musical note A4—a pleasant tone for UI feedback
clickSound.amp(0);- Starts with amplitude 0 (silent) so the sound is ready but not playing until we click the button
clickSound.start();- Starts the oscillator running continuously in the background—we control its volume to trigger the beep
textSize(24);- Sets a default text size (though draw() will override this with responsive sizing)
textAlign(CENTER, CENTER);- All text will be drawn centered around its x,y coordinate instead of starting from top-left