We learned about the structure of a p5.js sketch and that p5.js will automatically call the setup() function! There’s only one more built-in function to learn about before we start programming our own graphics—the draw() function!

The draw() function is similar to the setup() function in that p5.js will automatically execute it at the right time. The draw() function will run after all the code in the setup() function is complete. Note that like the setup() function, the draw() function should not be explicitly called.

Unlike the setup() function, the draw() function will repeatedly execute in what is known as the draw loop. The draw() function is also referred to as the draw() loop because the code block in the function will execute infinitely until the sketch ends by closing the browser window or navigating away from the sketch. The draw loop will also terminate when the noLoop() function is called.



The background color is currently set once at the beginning of the program in the setup() function. Move the background() function in the setup() function into the draw() function.


Instead of the static gray value of 200, set the background color to be a random integer between 0 and 255. Use JavaScript’s Math.random() function to generate a decimal number between 0 and 255 and the Math.floor() function to convert the generated decimal number to an integer.

Run the code to see the background color of the canvas constantly change to a random gray value!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?