p5.js draw() Function

The draw() function is called after setup() function. The draw() function is used to executes the code inside the block until the program is stopped or noLoop() is called. If the program does not contain noLoop() function within setup() function then draw() function will still be executed once before stopping it. It should always be controlled with noLoop(), redraw() and loop() functions.
Syntax:
draw()
Below examples illustrate the draw() function in p5.js:
Example 1:
| functionsetup() {       Â    // Create Canvas of given size      createCanvas(400, 300);  }   Âfunctiondraw() {       Â    background(220);       Â    // Use color() function      let c = color('green');   Â    // Use fill() function to fill color      fill(c);       Â    // Draw a rectangle      rect(50, 50, 300, 200);       Â}   | 
Output:
Example 2:
| functionsetup() {       Â    // Create Canvas of given size      varcvs = createCanvas(600, 250); }  Âfunctiondraw() {    Â    // Set the background color     background('green');     Â    // Use createDiv() function to     // create a div element     varmyDiv = createDiv('zambiatek');    Â    varmyDiv1 = createDiv('A computer science portal for zambiatek');    Â    // Use child() function     myDiv.child(myDiv1);    Â    // Set the position of div element     myDiv.position(150, 100);      Â    myDiv.style('text-align', 'center');    Â    // Set the font-size of text     myDiv.style('font-size', '24px');    Â    // Set the font color     myDiv.style('color', 'white');  Â}  | 
Output:
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					



