What is p5.js and How to use it?

mhiratsuka
3 min readJan 30, 2018

--

Today I want to explain p5.js. I am also a p5.js beginner so let’s try to be familiar with p5.js together!

1. What is p5.js?

p5.js is written in JavaScript but originally it is Processing (https://processing.org/). Processing is a visual coding tool for visual arts. The interesting is that processing is not only for developers but also artists, designers, researchers and those who want to enjoy making arts. p5.js is used in JavaScript so we can use it with DOM.

The following is the p5.js official site.
https://p5js.org/

2. How to use p5.js

Let’s make a simple stuff today. Our goal is to know small tips and make an animation.

Step 1: Make one HTML file and create a link to p5.js and your own JavaScript file.

The easy way to get a link is to go to official site and find CDN. Copy something …/p5.min.js and paste it into your HTML.

Your HTML looks the above image.

Step 2: Make a circle

creativeCanvas(width of the canvas, height of the canvas) function sets the canvas size.

background() function sets a color of the canvas we make. * I use color parameter but you can use other parameters. Please refer to the official site (https://p5js.org/reference/#/p5/background).

noStroke() function means no outline of the ellipse.

ellipse(x location of the ellipse, y location of the ellipse, the width of the ellipse, the height of the ellipse) .function draws the ellipse.

Don’t forget to open your HTML in your browser!

Your script.js
Your browser looks like this

Step3: Let’s make your ellipse move!

draw() function loops forever. Thus, the only thing you have to do is to make y-location sets 0 and then increase it. Then, you get an animation that your ellipse moves from the top to the bottom of your canvas.

Your script.js
Demo of the Step 3

Step4: Make many dots and move them infinitely

Let’s do the final step here.

random() function makes a random floating number. In my code, I set “random(width)”. This means they would return 0 up to 500 that is the max width of the canvas. If it is just random(), it would sets from 0 up to 1. Then, you might already notice…If it is random(6, 10), it would return 6 up to 10. It is pretty easy to understand, isn’t it?

Demo of the Step 4

That is it today! I hope that you can get a tip from my post. I will try to do more complicated stuff and share my experience in here again later.

--

--