setup()
setup() runs once when the sketch starts. It is the perfect place to create your canvas, build interactive controls, and set up initial data. The order matters—always create your canvas first, then add other elements.
function setup() {
createCanvas(windowWidth, windowHeight);
// Create input field for seed
inputSeed = createInput(mySeed);
inputSeed.attribute('type', 'number'); // Ensure it's a number input
inputSeed.attribute('min', '1'); // Optional: minimum seed value
inputSeed.attribute('max', '10000'); // Optional: maximum seed value
inputSeed.position(10, 10); // Position controls
inputSeed.style('width', '100px');
inputSeed.style('font-size', '16px');
inputSeed.input(updateSeedAndDraw); // Call function when input changes
// Create button to generate new random seed
buttonGenerate = createButton('Generate Random Pattern');
buttonGenerate.position(120, 10); // Position controls
buttonGenerate.style('font-size', '16px');
buttonGenerate.mousePressed(generateRandomPattern); // Call function on button press
// Precompute pattern for the initial seed
regeneratePatternData();
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that stretches to fill the browser window
inputSeed = createInput(mySeed);
Creates a text input field starting with mySeed value for users to type in a seed number
buttonGenerate = createButton('Generate Random Pattern');
Creates an interactive button that triggers random pattern generation when clicked
regeneratePatternData();
Computes the line endpoints for the starting seed value so the sketch is not blank on load
createCanvas(windowWidth, windowHeight);- Creates a p5.js canvas the size of the entire browser window, making it responsive to screen size
inputSeed = createInput(mySeed);- Creates an interactive text input field starting with the value of mySeed (initially 1)
inputSeed.attribute('type', 'number');- Tells the browser this input should only accept numbers, giving users a numeric keyboard on mobile
inputSeed.input(updateSeedAndDraw);- Connects the input field to the updateSeedAndDraw() function so it runs every time the user types a new number
buttonGenerate = createButton('Generate Random Pattern');- Creates an interactive button with the label 'Generate Random Pattern'
buttonGenerate.mousePressed(generateRandomPattern);- Connects the button to the generateRandomPattern() function so it runs when clicked
regeneratePatternData();- Precomputes all line endpoints for the starting seed before draw() ever runs, so the canvas shows a pattern immediately