The setup() function runs when the program starts. It is used to set the initial environment properties such as text-color, screen size, background-color and load the media file such as images and fonts. The program contains only one setup() function. The setup() function can not be called again after its initial execution.
Note: The variable declaration within setup() function can not be access by other functions including draw() function.
Syntax:
setup()
Below examples illustrate the setup() function in p5.js:
Example 1:
function setup() {
createCanvas(400, 300);
}
function draw() {
background(220);
let c = color( 'green' );
fill(c);
rect(50, 50, 300, 200);
}
|
Output:

Example 2:
function setup() {
var cvs = createCanvas(600, 250);
}
function draw() {
background( 'green' );
var myDiv = createDiv( 'GeeksforGeeks' );
var myDiv1 = createDiv( 'A computer science portal for geeks' );
myDiv.child(myDiv1);
myDiv.position(150, 100);
myDiv.style( 'text-align' , 'center' );
myDiv.style( 'font-size' , '24px' );
myDiv.style( 'color' , 'white' );
}
|
Output:
