← All lessons/Getting Started· Lesson 4 of 32

The draw loop

Define draw() to animate your sketch and respond to the mouse.

About 7 min

Code that repeats

So far your code has run once. To animate, define a function called draw. p5 runs the body of draw about 60 times per second, over and over.

Two special variables, mouseX and mouseY, always hold the mouse's current position on the canvas. Combine them with draw and you get interaction:

A circle that follows the mouse. Move your cursor over it!

Why background() inside draw()?

Calling background(220) at the start of every frame wipes the canvas clean. Remove it and the circles pile up into a trail — try it!

Your turn

Make a circle follow the mouse. Define a draw function that clears the canvas with background(220) each frame, then draws an ellipse at mouseX, mouseY.

Hints