Basics of p5.js

Welcome to the p5.js tutorial page! In this guide, you'll learn the basics of p5.js and make a snowman who's scared of the dark.

A snowman with a pink party hat and bowtie sitting on a blue sky with a grassy field, smiling but frowning when the sky turns dark

What is p5.js?

p5.js is a beginner-friendly and free-to-use art tool that extends Javascript, a programming language that websites use. In technical terms, p5.js is a Javascript library, which means it contains a bunch of code, and bunch of blocks of code (functions) that specialize in making web graphics.

p5.js can be used to make art, animations, and even games! Their website, p5js.org, has many tutorials, guides, and a large, active community.

Environment setup

There are two ways to code with p5js:

  1. p5.js web editor (online text editor): record time working with Lapse
  2. p5.js with VSCode (local text editor): record time working with Hackatime

The p5.js tutorial page has a good guide for setting up both these environments. For beginners, I reccomend using the p5js web editor.

Basic commands

A p5.js project is a website containing 3 files:

sketch.js is where we'll be coding our p5.js animation. By default, sketch.js contains the following code:

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
}

There are two functions in sketch.js:

Inside these functions are two lines of code:

Make the background blue by changing the number in background(220) to a 3-value rgb color:

background(56, 161, 206); // or any blue you want

Code runs from top to bottom. To make the grass for our snowman, we'll run the rect() function after background() to make a green block of grass:

function draw() {
  background(56, 161, 206); // or any blue you want

  // grass
  fill(123, 201, 97); // or any green you want
  rect(
    0, // x-position
    300, // y-position
    400, // width
    100 // height
  );
}
A blue sky with a grassy field

Documentation

There isn't much you can do with only 2 lines of code, but if you don't already know p5.js, how do you code with p5.js? The solution is to read the documentation.

Documentation is text that explains how software works or how to use it. In our case, the p5.js documentation contains a list of all its functions with examples; it can be found at p5.js.org/reference.

Place 3 circle() functions after the grassy field (rect()) to create the body.

Solution iconShow solution // snowman
fill(255);
//   x   y   diameter
circle(200, 300, 100); // bottom snowball
circle(200, 250, 100); // middle snowball
circle(200, 200, 100); // top

Now give the snowman a carrot nose with the triangle() function.

Solution iconShow solution // nose
fill(255, 153, 51); // or any orange you want
triangle(
  200, 200, // point 1
  200, 225, // point 2
  275, 212 // point 3
);

Finally, add a smiley face using the arc() function!

Solution iconI need help with the arc() function!

The arc() function has 6 input values (parameters):

Here's an example of an arc() function:

arc(20, 30, 80, 50, PI, 2PI); Visual explainer on how to use the arc() function in p5.js Unit circle marked with radians
Solution iconShow solution // mouth
fill(255);
arc(200, 225, 50, 25, 0, PI);
A white snowman with a nose and mouth sitting on a blue sky with a grassy field

Getting mouse input

Let's code the snowman's eyes to follow our mouse pointer and blink when we click the screen! We'll need to two 'drawings' for the eyes: one open, and one closed.

Start with open eyes using the circle() function:

Solution iconShow solution // open eyes
fill(0);
circle(180, 180, 5);
circle(220, 180, 5);

Then make the closed eyes with the line() function.

Solution iconShow solution // closed eyes
//   x1  y1  x2  y2
line(168, 180, 176, 180);
line(208, 180, 216, 180);

To get the location of our mouse, we can pass the mouseX and mouseY variables (data values) as parameters (function input values) for circle(). Dividing these numbers keeps the eyes near their original position.

// open eyes
circle(172+mouseX/40, 180+mouseY/40, 5);
circle(212+mouseX/40, 180+mouseY/40, 5);

Try making the closed eyes follow the mouse position the same way!

Solution iconShow solution // closed eyes
//   x1        y1        x2        y2
line(168+mouseX/40, 180+mouseY/40, 176+mouseX/40, 180+mouseY/40);
line(208+mouseX/40, 180+mouseY/40, 216+mouseX/40, 180+mouseY/40);
A white snowman looking around sitting on a blue sky with a grassy field

To check if the mouse is clicked, we need to use an if statement. An if statement executes different lines of code depending if a statement is true or false. Here's what an if statement looks like:

if ( x ) {
  // this code runs if x is true
} else if ( y ) {
  // this code runs if x is false, but y is true
} else {
  // this code runs if both x and y are false
}

The mouseButton object has a left property that's set to true or false depending if the left mouse-click button is down. Use the mouseButton.left property in an if-statement to change the eyes from open to closed.

Solution iconShow solution if (mouseButton.left) {
  // closed eyes
  //   x1        y1        x2        y2
  line(168+mouseX/40, 180+mouseY/40, 176+mouseX/40, 180+mouseY/40);
  line(208+mouseX/40, 180+mouseY/40, 216+mouseX/40, 180+mouseY/40);
} else {
  // open eyes
  circle(172+mouseX/40, 180+mouseY/40, 5);
  circle(212+mouseX/40, 180+mouseY/40, 5);
}

You now have a blinking snowman! Great job!

A white snowman blinking and looking around sitting on a blue sky with a grassy field

Loading images

Pick up your pencil and draw a hat and bow for your snowman! I like to draw using Krita, but you can use any drawing program you'd like.

If you're not in the mood to draw, download the example hat.png and bow.png files.

To upload your hat and bowtie pictures in the p5.js web editor, click the arrow under the play button to expand the left menu. Then click the plus button next to 'Sketch Files' and click 'Upload File'.

Uploading an image into p5.js's web editor

On Visual Studio Code, open the Explorer panel, then right-click on the empty space and click "Open Containing Folder". Upload your images into the folder and re-open VS Code.

Right-click menu next to the VS Code explorer panel

Before drawing images onto the canvas, you need to load them into p5.js with loadImage().

Run loadImage() in the setup() function: p5.js can crash if you try to load your images 60 times a second in the draw() function!

async function setup() {
  hat = await loadImage("hat.png");
  bow = await loadImage("bow.png");
}
Solution iconWhat's async and await?

Javascript runs its code one line at a time, so if one line of code takes a long time to execute, then the entire website has to wait for that line of code to run. Asynchronous functions run in the background so that Javascript can run multiple lines of code at once.

To make a function asynchronous, add async in the front of the function. To run an function asynchronously, add await before the function.

Now that your images are loaded, you can call the image() function in the draw() function to insert the pictures into the canvas.

// hat and bow
image(hat, 165, 75);
image(bow, 175, 245);

To scale the image down, divide the width and height properties:

image(hat, 165, 75, hat.width/4, hat.height/4);

Add the bow using another image() function.

Solution iconShow solution image(bow,175,245, bow.width/4, bow.height/4);

Your snowman now has a fire fit!

A snowman with a pink party hat and bowtie sitting on a blue sky with a grassy field

Getting keyboard input

We'll have the space key turn the background to night and make the snowman sad. Check if the space key is pressed by passing "Space" in the keyIsDown() function.

Solution iconI need more help!

Make an if statement that checks if keyIsDown("Space") is true. If the space key is pressed, color the background black. Otherwise, color it blue.

Solution iconShow solution if (keyIsDown("Space")) {
  background(0);
} else {
  background(56, 161, 206); // or any blue you want

}

(Want to use a different key? Take a look at the KeyboardEvent.key list!)

For the smiley face, turn that smiley face into a frown by setting its start and stop values as 0 and PI.

Solution iconShow solution if (keyIsDown("Space")) {
  arc(200,230,50,25,PI,0);
} else {
  arc(200,225,50,25,0,PI);
}
A snowman with a pink party hat and bowtie sitting on a blue sky with a grassy field, smiling but frowning when the sky turns dark

You've finished the tutorial! Congrats on making it this far! Now it's time to make your own animation- don't forget to set up time tracking before working on your project!

If you need inspiration, check out OpenProcessing for lots of great examples. Good luck and have fun!

White rabbit with a bowtie and bucket hat grins in front of the camera, saying 'Thanks for following the tutorial!'. Bottom text contains a signature.