setup()
setup() runs once when the sketch starts. Here it prepares the canvas, text settings, and creates and styles a real DOM button using p5's createButton(), position(), size(), and style() methods - showing how p5.js sketches can mix canvas drawing with regular HTML elements.
function setup() {
createCanvas(windowWidth, windowHeight); textAlign(CENTER, CENTER); textSize(24); noStroke();
cB = createButton('Cancel'); cB.position(width/2-50, height/2+100); cB.size(100, 40);
cB.style('background-color','#f44').style('color','white').style('border','none').style('border-radius','5px').style('cursor','pointer');
cB.mousePressed(() => { cB.html('Nice try'); setTimeout(() => cB.html('Cancel'), 2000); });
}
Line-by-line explanation (9 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, using p5's built-in windowWidth and windowHeight variables.
textAlign(CENTER, CENTER);- Sets text to be drawn centered both horizontally and vertically around the x, y coordinates you give text().
textSize(24);- Sets a default font size of 24 pixels for any text drawn without a more specific textSize() call.
noStroke();- Turns off outlines on shapes so the rectangles drawn later have clean, flat edges.
cB = createButton('Cancel');- Creates a real HTML <button> element labeled 'Cancel' and stores a reference to it in the global variable cB.
cB.position(width/2-50, height/2+100);- Positions the button 50 pixels left of center horizontally and 100 pixels below the vertical center, placing it just under the progress bar and message text.
cB.size(100, 40);- Sets the button's width to 100px and height to 40px.
cB.style('background-color','#f44').style('color','white').style('border','none').style('border-radius','5px').style('cursor','pointer');- Chains multiple CSS style calls to make the button red with white text, no border, rounded corners, and a pointer cursor on hover.
cB.mousePressed(() => { cB.html('Nice try'); setTimeout(() => cB.html('Cancel'), 2000); });- Attaches a click handler: when clicked, the button's text changes to 'Nice try', and after 2000 milliseconds (2 seconds) a setTimeout callback changes it back to 'Cancel'.