setup()
setup() runs once when the sketch starts. WEBGL mode enables device sensors (rotationX, rotationY) and 3D transformations; ortho() projects 3D space onto a 2D canvas centered at the origin. The p5.sound library (osc and amp) must be initialized here before draw() references them.
function setup() {
// Create a canvas that fills the window, using WEBGL for potential 3D features
createCanvas(windowWidth, windowHeight, WEBGL);
// Switch to orthographic (2D) projection within the WEBGL context
// This makes drawing 2D shapes like circle() behave more predictably
ortho();
noStroke(); // No outlines for the shapes
// Initialize a sine wave oscillator
osc = new p5.Oscillator('sine');
osc.amp(0); // Start with 0 amplitude (silent)
osc.start(); // Start the oscillator, but it won't be heard until amplitude increases
// Initialize an amplitude object to measure the oscillator's sound level
amp = new p5.Amplitude();
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight, WEBGL);
Creates a canvas that fills the window and enables WEBGL mode for 3D capabilities and device sensor access
osc = new p5.Oscillator('sine');
Creates a sine wave oscillator that will generate sound when amplitude is increased
amp = new p5.Amplitude();
Creates an object that measures the oscillator's real-time sound level for visual feedback
createCanvas(windowWidth, windowHeight, WEBGL);- Creates a WEBGL canvas (not the default 2D) that fills the entire browser window; WEBGL enables 3D rotations and better sensor integration
ortho();- Switches from perspective 3D projection to orthographic (2D-like) projection; this centers (0,0) at the canvas middle and makes circle() behave predictably
noStroke();- Disables outlines on all shapes so only the fill color is visible
osc = new p5.Oscillator('sine');- Creates a new oscillator object that generates a smooth sine wave; the argument 'sine' specifies the wave shape (other options: 'square', 'triangle', 'sawtooth')
osc.amp(0);- Sets the oscillator's amplitude (volume) to 0, so it produces no audible sound initially
osc.start();- Starts the oscillator; it begins producing audio signal, but remains silent because amplitude is 0
amp = new p5.Amplitude();- Creates an amplitude meter that continuously samples the oscillator's output and tracks its volume level