Skip to Content
Learn
Animation with p5.js
Frames

In p5.js, multiple frames can easily be shown in a sequence using the draw() loop. By default, any code in the draw() function will repeat over and over again, many times per second. This function’s endless repetition is ideal for making an animation because we can write code in the draw() function that slightly alters our image each time it runs.

As a quick recap, the draw() function is similar to an endless for-loop that repeatedly runs the code block inside from top to bottom. The draw() function runs after the setup() function that runs only once at the program’s start.

function setup(){ // Code inside setup() function runs once when you start the program } function draw(){ // Code inside draw() function loops infinitely after setup() is run }

It is helpful to think of an animation as a series of frames, like a film roll. By showing the series of frames fast enough, our brain is tricked into thinking the sequential images are an animation. The example below shows a series of frames shown like a film roll.

Series of Frames

To create a smooth animation with code, p5.js runs the draw loop at 60 frames per second. Below is an example of how each frame is overriding the previous one to create this animation.

Series of Frames

With p5.js, one frame is the equivalent to one loop through the draw() function. To keep track of the number of frames rendered, p5.js provides a built-in variable called frameCount. This variable counts the number of frames that have been displayed since the program started. The frameCount variable updates with every frame. The first time the draw() loop runs, the value of the frameCount is one; the second time the draw() loop runs, the frameCount is two; and so forth.

Instructions

1.

Below the line of code that sets fill color to white, draw an ellipse using the frameCount variable as the x position. Let the y position be height / 2. Set the width and height to be 300 pixels. See how the ellipse moves from the left to right because the frameCount value increases with every frame.

2.

In the last line within the draw() function, draw text using the text() function. Set the first parameter to be the frameCount variable. Set the second parameter, which is the x location, to be width / 2. Set the third parameter, which is the y location, to be height / 2.

Notice how p5.js keeps track of the number of frames run since the program begins.

Folder Icon

Take this course for free

Already have an account?