setup()
setup() runs once when the sketch starts. It's where you initialize your canvas, set p5.js modes, create interactive elements, and call initial calculations. The noLoop() at the end is a key optimization: instead of redrawing 60 times per second regardless of whether anything changed, the sketch only redraws when a slider moves.
function setup() {
createCanvas(1000, 1000);
angleMode(DEGREES);
noFill();
rectMode(CENTER);
// Sliders
nPointsLabel = createElement('label', 'Number of Points: ');
nPointsLabel.position(10, 10);
nPointsSlider = createSlider(3, 60, 24, 1); // Min 3, max 60, default 24, step 1
nPointsSlider.position(nPointsLabel.width + 15, 10);
nPointsSlider.style('width', '200px');
nPointsSlider.input(updateSketch); // Call updateSketch when this slider changes
sqSideLengthLabel = createElement('label', 'Rosette Size: ');
sqSideLengthLabel.position(10, 40);
sqSideLengthSlider = createSlider(width / 8, width / 2, width / 4, 1); // Min ~125, max ~500, default ~250, step 1
sqSideLengthSlider.position(sqSideLengthLabel.width + 15, 40);
sqSideLengthSlider.style('width', '200px');
sqSideLengthSlider.input(updateSketch); // Call updateSketch when this slider changes
// Initial calculation and drawing
updateSketch();
noLoop(); // Draw once, then only redraw on slider input
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
createCanvas(1000, 1000);
angleMode(DEGREES);
noFill();
rectMode(CENTER);
Creates the drawing surface, sets angles to degrees instead of radians for readability, disables automatic fill, and centers rectangle origins
nPointsSlider = createSlider(3, 60, 24, 1);
nPointsSlider.position(nPointsLabel.width + 15, 10);
nPointsSlider.input(updateSketch);
Creates interactive slider elements and connects them to updateSketch() so any change triggers a redraw
noLoop(); // Draw once, then only redraw on slider input
Stops the draw loop from running every frame—now it only runs when a slider changes, saving CPU
createCanvas(1000, 1000);- Creates a 1000×1000 pixel canvas—a square is ideal for symmetrical rosette designs
angleMode(DEGREES);- Switches angle measurement from radians (0–2π) to degrees (0–360), making geometry easier to visualize
noFill();- All shapes drawn after this will have no interior fill—only stroked outlines
rectMode(CENTER);- Sets the origin point of rectangles to their center instead of top-left (not used here but standard practice)
nPointsSlider = createSlider(3, 60, 24, 1);- Creates a slider ranging from 3 to 60 petals, starting at 24, with step size 1
nPointsSlider.input(updateSketch);- Connects the slider so every value change immediately calls updateSketch()
updateSketch();- Calls updateSketch() once at startup to generate and draw the initial rosette pattern
noLoop();- Disables the default 60-fps draw loop—now draw() only runs when redraw() is explicitly called by a slider