Sharvari Raut Computer Vision | Data Science | Technical Writer | AI Developer | Deep Learning | Developer

Creating animations with p5.js

5 min read 1645

P5.js is a JavaScript library focused on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! It is free and open source because they believe software, and the tools to learn it, should be accessible to everyone.

In this post, we’ll review the library, its functionality, and provide some examples of how to use it through the following sections:

What is p5.js?

P5.js is based on Processing, a creative coding platform founded by Ben Fry and Casey Reas. One of the main objectives of Processing (and Process-based projects) is to make it as easy as possible for beginners to learn to design interactive, graphic applications (while providing powerful tools for professionals).

P5.js is written in JavaScript, but initially was written with Processing. The advantage of using the JavaScript programming language is its widespread availability and support everywhere. Every web browser has an inbuilt JavaScript interpreter, which means that p5.js programs (usually) can work in any web browser.

Processing is a visual coding tool for visual arts. Interestingly, Processing is not only for developers, but also for artists, designers, researchers, and those who want to enjoy making art.

If you are new to p5.js, you can use the perfect online editor they provided to us, with no setup for anything at all. You can also use p5.js with HTML, CSS, and JavaScript code.

If you want to use p5.js in CodePen, you must add a few things. I will guide you through setting up p5.js in CodePen in the next section.

Getting started with p5.js in CodePen

To test out with p5.js in CodePen, begin by clicking on the Settings button in the top right corner of the page to bring up the settings menu.

Setting up p5.js in CodePen

Next, select the JS option and add your links in the Add External Scripts/Pens section. We will add the following links to libraries hosted on content delivery networks to load them in our project:

p5.min.js is a basic p5.js library, and p5.dom.js is an extra library that will let you create buttons and sliders.

After adding the links, click on Save & Close.

What are the benefits of using p5.js?

As we know, p5.js has a rich graphics library, which makes it easy to design anything on a canvas. There are many more benefits, including the following:

Firstly, the p5.js reference documentation on their official website is both thorough and exhaustive, fully and comprehensively covering all topics about the many facets of the framework.

Second, open-source programming language communities are generally happy to help and point someone in the right direction – and p5.js is no exception. If you get stuck, there is a robust community that can help.

The learning curve for p5.js is relatively easy – most people can design highly complex graphics after just a few days.

P5.js teaches other concepts that go beyond just creating visuals, like how to connect other electronic devices to your code, incorporate sound effects to accompany user interaction, embed live webcam feeds, and much more.

Finally, p5.js provides rich speech, sound, 2D, and 3D geometry libraries.

What’s the difference between Processing and p5.js?

You might be thinking Processing is the same as p5.js, but they are different!

Processing and p5.js are both versions of JavaScript, so some things are the same (like the set() and draw() functions), but some things (such as working within the embedded page) are pretty different.

With Processing, you need to declare a canvas area with a data source, which takes you to a PDE (source code) file. P5.js lets you write code directly to the editor to be executed.

P5.js also has additional library files, for example, the p5.dom.js library lets you add the option of creating and manipulating HTML elements with p5.js. The library provides sliders, buttons, form elements, and a lot more to your canvas.

More great articles from LogRocket:

How to create animations with p5.js

There are plenty of animations you can make with p5.js. The following are a few examples that you can try for yourself.

Background animations

star animation background

No Description

The background animations are mainly focused on the canvas. Typically, you can have it as a background over your other web elements on the webpage.

Here, in this example, we made a star background animation. In sketch.js, we have created a setup() function for our canvas and stars. According to our mouse hover, a draw() function adjusts our background stars’ speed. The Star.js file contains the function Star(), which includes the attributes required for the animation of our stars.

Spinning animations

spinner animation in p5.js

Add External Stylesheets/Pens Any URLs added here will be added as s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension. JavaScript Preprocessor Babel includes JSX processing.

The spinning animation is very popular, and it’s easy to make in p5.js. In the example above, we have functions for shapes through which we can draw other shapes. We are using circle() functions here to draw circles. For the spinning motion, we use the rotate() function on each circle.

3D animations

rotating 3d box

Add External Stylesheets/Pens Any URLs added here will be added as s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension. JavaScript Preprocessor Babel includes JSX processing.

P5.js allows us to create objects and animations in a three dimensional plane. The best thing about p5.js is that it has inbuilt functions for creating basic 3D objects.

In the example above, we are placing a 3D object mathematically in an open space. The box() function takes at least one parameter to specify the size of our cube. These shapes are positioned by using the translate() function. We use the rotate() function for the X, Y, and Z axis shapes in the 3D plane for a spinning motion.

Sine and cosine animations

sine and cosine animation

Add External Stylesheets/Pens Any URLs added here will be added as s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension. JavaScript Preprocessor Babel includes JSX processing.

For these animations, you don’t need to be a master of trigonometry. P5.js provides few trigonometric functions, such as acos(), asin(), atan(), atan2(), cos(), sin(), tan(), degrees(), radians(), and angleMode().

Here, our example consists of four circles moving in a waveform motion.The sin() and cos() functions cause the movement in our animation. Numbers between 0 and 2π are included, and numbers between -1 and 1 are returned.

Animations using functions

See the Pen
white mouse trail p5.js
by Sharvari Raut (@sharur7)
on CodePen.

The array access operator (square brackets [] with an integer inside them) to reference the indices of an array. In this example, it creates a p5.Vector instance, and then calls its add() function. The push() function adds an element to the last index or in the end of the array. The splice() function takes an index as a parameter and removes the element from that index. The pop() function eliminates an element from the end of the array. The unshift() and shift() add and remove an element from the start of the array.

This code uses an array of p5.Vector instances to show a mouse trail that follows the mouse. Each time draw() is called, the code adds a new instance of p5.Vector to the end of our array. Then the code uses a for loop to draw each p5.Vector in the mouse trail.

Animations by creating classes

For class functions, defining a class needs the class keyword, then give your class a name. Inside curly brackets {}, write the body of the class. The body consists of a function and a constructor you want inside the class. A constructor is similar to a function, except that it has a special name: constructor.

Create a new instance of the circle inside the setup() function using the new keyword. The myCircle variable now points to an instance of Circle with variables x = 150, y = 150, xSpeed = 1, and ySpeed = 2.

To define a function inside your class, give it a name, and then list any arguments in parentheses (). The display() function draws the circle.The move() function handles moving and bouncing the circle.

Animation using colors

See the Pen
Saturated Bars
by Sharvari Raut (@sharur7)
on CodePen.

Using basic functions like color(), colorMode(), and fill() we can create graphics in p5.js. Here, in this example, a “saturated” color is a true, pure color, and an “unsaturated” color has a large amount of gray. If you move the cursor vertically over each bar, the saturation is altered. Similarly, you can do this for Hue and Grayscale as well.

Animations using typography

See the Pen
by Sharvari Raut (@sharur7)
on CodePen.

In p5.js, typography is basically the same as creating interactive text graphics in p5.js. These include some pre-defined functions, which operate on the text. With these functions, we can add interactive text animations. For example, the functions like: textToPoints() and textFont() are used for text modifications and can also be used for creative animations. Here, in this example we have text(int(angleRotate)) function for our text rotation.


If you have been working as a web developer, you will feel very comfortable using p5.js, as it is a JavaScript library that you can easily add to your projects. It can be expanded with a few additional libraries, a few of which are built in with p5.js. In addition to the libraries provided in p5.js by default, you can get most of the audio and speech, 2D and 3D functionality, and other useful tools by exploring additional libraries.

Are you adding new JS libraries to improve performance or build new features? What if they’re doing the opposite?

There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.

LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.

LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.

Build confidently — .

Sharvari Raut Computer Vision | Data Science | Technical Writer | AI Developer | Deep Learning | Developer

One Reply to “Creating animations with p5.js”

  1. I’m not sure where you got that info but Processing has never been JS based as far as I’m aware. Processing runs on Java and needs its own IDE and .pde files like you described, whereas p5.js is a JavaScript library and can run on the web, etc

Leave a Reply