setup()
setup() runs once when the sketch starts. It initializes the canvas, captures the webcam, and prepares all the variables the game needs. Notice how it calls helper functions (calculateLayoutDimensions, calculateVideoBounds) to keep the code organized and reusable.
function setup() {
createCanvas(windowWidth, windowHeight);
// Tip: Use windowWidth/windowHeight for responsive canvas
// Calculate layout dimensions for sidebar and main area
calculateLayoutDimensions();
// Create a capture object to access the webcam
video = createCapture(VIDEO);
video.hide(); // Hide the default HTML video element
// Start the audio context. This is good practice for any media
userStartAudio();
// Set up text properties for displaying the click count and upgrade info
textSize(24);
textAlign(CENTER, CENTER);
fill(255);
noStroke();
// Calculate the video position and size once in setup
// and update it in windowResized
calculateVideoBounds();
// Create an off-screen graphics buffer for the circular mask
maskBuffer = createGraphics(videoDiameter, videoDiameter);
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-window canvas that will hold the game area and sidebar
video = createCapture(VIDEO);
Accesses the user's webcam and stores the live feed in the video variable
maskBuffer = createGraphics(videoDiameter, videoDiameter);
Creates an invisible off-screen graphics buffer that will hold the circular mask
createCanvas(windowWidth, windowHeight);- Creates a canvas sized to fill the entire browser window, making the game responsive
calculateLayoutDimensions();- Calls a helper function that calculates how much width the sidebar and main area should occupy
video = createCapture(VIDEO);- Requests access to the user's webcam and creates a video object that captures the live feed
video.hide();- Hides the default HTML video element so only the circular masked version appears on the canvas
userStartAudio();- Initializes the audio context for p5.sound; this is best practice when using media
textSize(24);- Sets the default text size to 24 pixels for all text drawn on the canvas
textAlign(CENTER, CENTER);- Centers text both horizontally and vertically around the coordinates where text is drawn
calculateVideoBounds();- Calls a helper function that calculates the position and diameter of the circular video
maskBuffer = createGraphics(videoDiameter, videoDiameter);- Creates an invisible graphics buffer the same size as the circular video to hold the mask