setup()
setup() runs once when the sketch starts. It prepares the canvas and creates the HTML input and button elements that bridge user input into the p5.js environment. Notice how createInput() and createButton() are p5.js functions that create real HTML elements—p5.js can create and control DOM elements, not just draw shapes.
function setup() {
createCanvas(600, 400);
textFont("Arial");
inputBox = createInput();
inputBox.position(20, height - 60);
inputBox.size(200);
submitButton = createButton("Submit");
submitButton.position(inputBox.x + inputBox.width + 10, height - 60);
submitButton.mousePressed(handleSubmit);
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
inputBox = createInput();
Creates an HTML text input field that players type into
submitButton = createButton("Submit");
Creates an HTML button that triggers handleSubmit when clicked
createCanvas(600, 400);- Creates a 600-pixel-wide, 400-pixel-tall canvas where the game board displays
textFont("Arial");- Sets the default font for all text() calls to Arial, making the display consistent
inputBox = createInput();- Creates an HTML text input field and stores a reference to it so we can read its value later
inputBox.position(20, height - 60);- Positions the input box 20 pixels from the left and 60 pixels from the bottom of the canvas
inputBox.size(200);- Sets the input box width to 200 pixels
submitButton = createButton("Submit");- Creates an HTML button labeled 'Submit' and stores a reference to it
submitButton.position(inputBox.x + inputBox.width + 10, height - 60);- Positions the button 10 pixels to the right of the input box, aligned at the same vertical level
submitButton.mousePressed(handleSubmit);- Tells p5.js to call the handleSubmit() function whenever the button is clicked