setup()
setup() runs once at the very start of your sketch. Use it to initialize the canvas, set up objects like the oscillator, and precompute values that never change. p5.sound oscillators must be created and started in setup() before they can be used in draw().
function setup() {
createCanvas(windowWidth, windowHeight);
// Initialize p5.sound
osc = new p5.Oscillator();
osc.setType('sine'); // Sine wave for a smooth sound
osc.amp(0); // Start with 0 volume
osc.start(); // Start the oscillator
userStartAudio(); // Required to allow audio playback
tigerColor = color(255, 165, 0); // Orange
dragonColor = color(0, 150, 200); // Blue
noStroke();
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
osc = new p5.Oscillator();
Creates a new sine wave oscillator object that will generate the sound controlled by mouse position
userStartAudio();
Enables audio playback by requesting user permission, required by modern browsers for sound to work
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, making the animation fullscreen
osc = new p5.Oscillator();- Creates a new oscillator object from the p5.sound library that will produce sound waves
osc.setType('sine');- Sets the oscillator to produce a sine wave, which sounds smooth and pure without harsh edges
osc.amp(0);- Starts the oscillator at 0 volume so sound doesn't blast immediately when the sketch loads
osc.start();- Begins the oscillator running; it is now ready to play sound but stays silent at amp(0)
userStartAudio();- Requests permission from the browser to play audio; without this, the oscillator cannot produce sound
tigerColor = color(255, 165, 0); // Orange- Pre-computes the tiger's color (orange) so it does not get recalculated every frame in draw()
dragonColor = color(0, 150, 200); // Blue- Pre-computes the dragon's color (blue) for efficiency
noStroke();- Disables outlines on all shapes so only filled colors are drawn, giving a smoother appearance