Introduction to p5.js

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.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first p5 sketch</title>
    </head>
    <body>
        
    </body>
</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 p5

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

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first p5 sketch</title>
    </head>
    <body>
        <script src="p5.js"></script>
    </body>
</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.

<body>
    <script src="p5.js"></script>
    <script src="my-first-sketch.js"></script>
</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:

// Setup code
function setup () {
    console.log('Hi from setup!');
}

// Drawing code
function draw () {
    console.log('Hi from draw!');
}

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.

function setup () {
    // Create a canvas 200px wide and 200px tall
    createCanvas(200, 200);
}

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.

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. 

function draw () {
    rect(0, 0, 50, 50);
}

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.

fill('#CC00FF');
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.

// Draw an ellipse that's 25px from the top and
// 25px from the left of the edge of the canvas.
// The ellipse is 25px tall and 25px wide making
// it a circle.
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.

fill('#66CC66');
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.

function draw () {
    // Offset the canvas
    // random(0, width) returns a value between
    // 0 and the width of the canvas.
    // As does random(0, height) for height.
    translate(random(0, width), random(0, height));
 
    // Existing code here
}

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.

function setup () {
    createCanvas(200, 200);
    background('red');
    frameRate(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.

angleMode(DEGREES); // uses global DEGREES constant
rotate(random(1, 360)); // rotate to random angle
fill('#CC00FF');
rect(0, 0, 50, 50);

rotate(random(1, 360));
fill('#66CC66');
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.

// Random positioned yellow triangle
rotate(random(1, 360));
fill('yellow');

// 3 pairs of triangle points
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:

function setup () {
    createCanvas(200, 200);
    background('red');
    frameRate(5);
}

function draw () {
    translate(random(0,width), random(0,height));

    angleMode(DEGREES);
    rotate(random(1, 360));
    fill('#CC00FF');
    rect(0, 0, 50, 50);

    rotate(random(1, 360));
    fill('#66CC66');
    ellipse(25, 25, 25, 25);

    rotate(random(1, 360));
    fill('yellow');
    triangle(25, 0, 50, 50, 0, 50);
}

Download Introduction to p5.js

Leave a Reply

Your email address will not be published. Required fields are marked *