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() { // Create Canvas of given size createCanvas(400, 300); } function draw() { 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:
function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250); } function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv = createDiv('GeeksforGeeks'); var myDiv1 = createDiv('A computer science portal for geeks'); // 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:

Recommended Posts:
- AWS EC2 Instance Setup with Apache Server
- Environment setup for JSP
- Setup API for GeeksforGeeks user data using WebScraping and Flask
- Angular CLI | Angular Project Setup
- ES6 | Environment Setup
- How to Setup View Engine in Node.js ?
- How to Setup Handlebars View Engine in Node.js ?
- How to Setup Sublime Text 3 for Python in Windows?
- How to Setup Atom Editor with all the required Packages?
- How to Setup Browsersync for Web Development in Ubuntu?
- How to get the function name from within that function using JavaScript ?
- How to call a function that return another function in JavaScript ?
- How to get the function name inside a function in PHP ?
- How to Check a Function is a Generator Function or not using JavaScript ?
- PHP | imagecreatetruecolor() Function
- p5.js | year() function
- D3.js | d3.utcTuesdays() Function
- PHP | ImagickDraw getTextAlignment() Function
- PHP | Ds\Sequence last() Function
- Function to escape regex patterns before applied in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


