Advertisement
Scroll to top

p5.js is a JavaScript library for artists, designers, and educators, with a specific focus on the visual arts. It's an extremely easy way for you to create interactive pieces of art, animations and prototypes in the browser. 

It is heavily inspired by the programming language Processing, which refers to itself as a “flexible software sketchbook”. Processing was created in 2001 with the purpose of teaching non-programmers how to code, but since then it has become the language of choice for tens of thousands of artists, designers and students. 

p5.js, however, has a slightly different aim in mind. p5 brings the power and simplicity of Processing to the web. This tutorial will show you how to create your first p5 "sketch" and some fun things you can do with it.

Getting Started

Because p5 is designed for the web, we're going to need a webpage. Make a new directory on your computer and create an index.html file inside it. We don't need much in here, just the standard bits and bobs.

1
<!doctype html>
2
<html>
3
    <head>
4
        <meta charset="utf-8">
5
        <title>My first p5 sketch</title>
6
    </head>
7
    <body>
8
        
9
    </body>
10
</html>

Next, we'll need the p5 library itself, which we can easily get from the p5 download page. We only need the basic library, so just download the single file version of p5.

The Single Version of p5The Single Version of p5The Single Version of p5

Put the downloaded file in the same directory as your HTML file. We can then reference it in our HTML like so:

1
<!doctype html>
2
<html>
3
    <head>
4
        <meta charset="utf-8">
5
        <title>My first p5 sketch</title>
6
    </head>
7
    <body>
8
        <script src="p5.js"></script>
9
    </body>
10
</html>

We'll also need a JavaScript file for our sketch. A sketch is Processing speak for the drawing or animation we create with p5. Make another file, again in the same directory, and call it my-first-sketch.js. This needs to be referenced after the p5 library so our script knows all the methods provided by p5.

1
<body>
2
    <script src="p5.js"></script>
3
    <script src="my-first-sketch.js"></script>
4
</body>

That's all the setup there is! We're now ready to start creating our masterpiece.

Core Concepts

p5 gives us two methods that are essential when creating a sketch: setup() and draw(). You can probably guess what each of them are for, but they have an important hidden difference. Open up my-first-sketch.js and add the following:

1
// Setup code

2
function setup () {
3
    console.log('Hi from setup!');
4
}
5
6
// Drawing code

7
function draw () {
8
    console.log('Hi from draw!');
9
}

Now even though we have just defined these functions and done nothing else, because p5 was expecting us to do this, it is automatically going to execute them when we load the page. Open your index.html in your favourite browser and open the JavaScript console. Here's what I see:

The JavaScript Console

As you can see, both functions were called automatically, but the setup() function was called only once, while draw() was called over and over again—768 times within a few seconds! We'll see the importance of this a little later.

OK, to begin drawing, we'll require something that all artists need: a canvas. All we need to do is use p5's createCanvas() function and give it a width and height as arguments. Where should we call this function from? setup() of course.

1
function setup () {
2
    // Create a canvas 200px wide and 200px tall

3
    createCanvas(200, 200);
4
}

If you refresh your page, you'll see nothing different. This is because the canvas is transparent by default. Let's spruce it up with a bit of colour. How about a nice red? Stick this line into setup() as well.

1
background('red');

p5 is clever enough to know whether we've used an HTML colour name or a hex value, meaning background('#FF0000'); is equally valid.

Shapes

Let's get drawing. We have a few built-in shapes at our disposal. Let's start with a basic rectangle. In our draw function, we can write the following. Remember, all coordinates start at (0, 0), which is the top-left corner of the canvas. 

1
function draw () {
2
    rect(0, 0, 50, 50);
3
}

If you refresh your page, you should see this: a rectangle that starts at (0, 0) and is 50 px wide and 50 px tall (a square).

Red Square

This square can be coloured in as easily as our background. All we have to do is specify a fill colour before we draw the rectangle. Let's use some hex this time.

1
fill('#CC00FF');
2
rect(0, 0, 50, 50);

Now we have a purple square. Not exactly a masterpiece, but we're getting somewhere. How about another shape? A circle, I hear you say? No problem.

1
// Draw an ellipse that's 25px from the top and

2
// 25px from the left of the edge of the canvas.

3
// The ellipse is 25px tall and 25px wide making

4
// it a circle.

5
ellipse(25, 25, 25, 25);

You'll notice that our circle has not only been drawn on top of our rectangle, but it's also the same colour as the rectangle. 

This is because the order in which we call these functions is extremely important. If we had drawn the rectangle after the ellipse, we wouldn't see the circle at all as it would have been painted over. As for the circle's fill colour, it's the same as the square because any shape drawn after the fill() function is called will use that colour. To change the colour of the circle, simply call the fill colour again with a different value.

1
fill('#66CC66');
2
ellipse(25, 25, 25, 25);

We now have this:

Hmm, still not that exciting. Let's see what we can do. Now, remember the majority of our code here is contained within the draw() function, and as we saw before, anything in the draw function gets called over and over again. So essentially our square and circle are being drawn over and over again on top of the square and circle that were drawn in the previous call of the draw function. 

What if we were to draw our shapes in a different place each time?

Different Time, Different Place

In order to draw your shapes in a different place, you may be tempted to change their coordinate values. This is perfectly acceptable and a great way to have complete control over your drawing. 

There is also an alternative. We can change the offset of the entire canvas, meaning that we can change the origin, the top-left coordinates (0, 0) to something else. The outcome of this is that our shapes are drawn with this offset. If we were to write translate(10, 10); we'd end up with this.

Our Updated Square

Note that our shapes are now drawn 10 px from the left and 10 px from the top.

This hasn't really fixed our original problem of the shapes being drawn over each other repeatedly, but what if we were to change the origin of the canvas with each draw() call? The shapes would be drawn in a different position each time. But what position? And how would we come up with a different one each time draw() is called? Luckily, p5 has us covered with the random() function—an easy way to generate a random number. We'll use this to randomly change the offset of our canvas.

1
function draw () {
2
    // Offset the canvas

3
    // random(0, width) returns a value between

4
    // 0 and the width of the canvas.

5
    // As does random(0, height) for height.

6
    translate(random(0, width), random(0, height));
7
 
8
    // Existing code here

9
}

This gives us an animated version of this:

Animated Block

Whee! You may find this animation a bit fast. This is because p5 is drawing our shapes as fast as it can, with draw() being called again and again. If you want to slow this down a bit, you can change the frame rate to reduce the frequency in which draw() is called. Put a call to frameRate() in your setup function.

1
function setup () {
2
    createCanvas(200, 200);
3
    background('red');
4
    frameRate(5);
5
}

That's better. Again it's a bit boring with the square and circle always being on top of each other. Let's try rotating our shapes to make things more interesting. So, how do we do that? Yup, you guess it, p5 has us covered yet again. First we tell p5 we want to rotate using degrees instead of radians, and that we want to rotate randomly before we draw each shape.

1
angleMode(DEGREES); // uses global DEGREES constant

2
rotate(random(1, 360)); // rotate to random angle

3
fill('#CC00FF');
4
rect(0, 0, 50, 50);
5
6
rotate(random(1, 360));
7
fill('#66CC66');
8
ellipse(25, 25, 25, 25);

We've created a monster.

A variation on a square

I'm pretty sure I had a shirt back in 1991 with this same pattern on it...

No, my mistake, it had some yellow triangles on it. Let's go all in and add some.

1
// Random positioned yellow triangle

2
rotate(random(1, 360));
3
fill('yellow');
4
5
// 3 pairs of triangle points

6
triangle(25, 0, 50, 50, 0, 50);

Lovely. Bad 90s shirt or modern-day Jackson Pollock? That's up to you. Art is in the eye of the beholder, as they say.

Jackson Pollock-inspired

Summary

I hope you've seen from this tutorial how easy it is to start drawing in the browser with p5.js. p5 has many more helpful, convenient methods to help us draw shapes, animate and handle user input. If you're interested in learning more, visit the p5 reference page, or check out my Envato Tuts+ course Interactive Art With p5.js.

For reference, here's the complete source for our p5 sketch:

1
function setup () {
2
    createCanvas(200, 200);
3
    background('red');
4
    frameRate(5);
5
}
6
7
function draw () {
8
    translate(random(0,width), random(0,height));
9
10
    angleMode(DEGREES);
11
    rotate(random(1, 360));
12
    fill('#CC00FF');
13
    rect(0, 0, 50, 50);
14
15
    rotate(random(1, 360));
16
    fill('#66CC66');
17
    ellipse(25, 25, 25, 25);
18
19
    rotate(random(1, 360));
20
    fill('yellow');
21
    triangle(25, 0, 50, 50, 0, 50);
22
}
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.