setup()
setup() runs once and is the right place to request hardware access (webcam, microphone) and build any off-screen buffers you'll reuse every frame, like the WEBGL graphics object here.
function setup() {
createCanvas(windowWidth, windowHeight); // 2D canvas
angleMode(RADIANS); // For 3D rotations
// Webcam
cam = createCapture(VIDEO); // https://p5js.org/reference/#/p5/createCapture
cam.size(320, 240);
cam.hide(); // We'll draw it on the canvas manually
// Microphone + amplitude analyzer
mic = new p5.AudioIn(); // https://p5js.org/reference/#/p5.AudioIn
amp = new p5.Amplitude(); // https://p5js.org/reference/#/p5.Amplitude
amp.setInput(mic);
// Off-screen WEBGL buffer for 3D cube (uses WebGL2 where available)
g3d = createGraphics(260, 260, WEBGL);
textFont('sans-serif');
}
Line-by-line explanation (9 lines)
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the whole browser window, so the four quadrant panels can be sized from width/height.
angleMode(RADIANS);- Tells p5 that rotation values (like rotateX) are given in radians instead of degrees - important since rotationX/Y/Z sensor readings get converted with radians().
cam = createCapture(VIDEO);- Requests webcam access from the browser and returns a video element that updates automatically.
cam.size(320, 240);- Requests the webcam stream at 320x240 pixels, keeping the video light-weight to draw.
cam.hide();- Hides the raw HTML <video> element so only the version drawn manually with image() inside the canvas is visible.
mic = new p5.AudioIn();- Creates a microphone input object from the p5.sound library, ready to be started later on a user gesture.
amp = new p5.Amplitude();- Creates an analyzer that can report the overall loudness (0-1) of whatever audio source it's connected to.
amp.setInput(mic);- Connects the amplitude analyzer to the microphone so amp.getLevel() reports the mic's volume.
g3d = createGraphics(260, 260, WEBGL);- Creates a separate off-screen 3D drawing surface. Rendering the cube here keeps 3D code isolated from the main 2D canvas.