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:
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.
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.
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:
https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.2/p5.min.js https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.2/addons/p5.dom.js
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.
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.
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.
There are plenty of animations you can make with p5.js. The following are a few examples that you can try for yourself.
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.
spinner animation in p5.js
No Description
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.
rotating 3d box
No Description
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 animation
No Description
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.
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.Vecto
r in the mouse trail.
https://codepen.io/sharur7/pen/bGLgqYg
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.
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.
See the Pen
typography 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.
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 — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowSOLID principles help us keep code flexible. In this article, we’ll examine all of those principles and their implementation using JavaScript.
JavaScript’s Date API has many limitations. Explore alternative libraries like Moment.js, date-fns, and the new Temporal API.
Explore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
2 Replies to "Creating animations with p5.js"
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
Great article!