Get Started with P5.js

There are a number of ways to write p5.js sketches. In theory you can write code in any simple text editor on your computer however most designers use code editors which are specifically designed for write code.  The official getting started tutorial also suggests downloading a code editor (like Sublime Text 2,  BracketsAtomTextWranglerBrackets or Notepad++) and working with your p5.js source code just like any other programming language. For this Unit however we will be using the P5.js editor which is slightly less overwhelming and is actually visually quite similar to the Arduino software you used in Unit 2. Note: The p5.js editor is still in development (beta) but works good enough for the activities you will do in this unit. However if you find an issues or bugs help the P5 community by posting feedback here. Click (Mac OS XWindowsLinux to download the p5 editor to your computer.

NOTE: On OSX, you may get an error that says that the application can’t be launched because it’s from an unknown developer. This is a feature of OSX which is designed to keep casual users from accidentally running malware that they download from the Internet. The p5.js editor isn’t malware, though. Go to Security and Privacy setting in your System preferences. Under the General tab, click the lock and fill in your username and password. You can now pressed the "Open anyway" button. P5 should now open as usual. Remember to move it from your download folder into your application folder.

Once you’ve launched the application successfully, you should see something like this:

It looks very similar to the Arduino software you used in Unit 2.

Anatomy of an editor

There are three main parts of the editor you need to be familiar with. The play button at the top (to run you sketch into a browser window). All the typing happens in the white central window. And the little window below is the console, where error messages will show up. Get used to seeing many errors messages while your trying things out. But don’t get frustrated or give up easily, learning to code is all about trial and error.

Your first sketch

Okay, now that is out of the way let’s get a-programming!. Copy the source code from the example below and paste it into your p5.js editor. Press the “Play” button; a window will open, and you should see something that looks like what you see on the right-hand side below.


Congratulations! You’ve made your first P5.js sketch! But what exactly happened? Here’s a little breakdown (simplifying a little):

  • ellipse(50, 50, 60, 60); is an example of a function call. p5.js comes with several dozen built-in “functions” that perform various tasks, like drawing shapes to the screen or calculating values using mathematical formulas. Learning how to program in p5.js is mostly about understanding these commands and what they do. The ellipse function, in case you hadn’t guessed, draws an ellipse to the screen.
  • ellipse is the function’s name. Functions are always followed by a pair of parentheses; inside these parentheses are a comma-separated list of values. These values are called the function’s parameters. Every function uses its parameters in a slightly different way, and part of learning a function is learning what its parameters mean.
  • In the case of ellipse, the first parameter is the X coordinate of the ellipse, the second parameter is the Y coordinate, the third parameter is the width of the ellipse and the last parameter is the height of the ellipse.
  • The function call ends with the semicolon (;). You should put a semicolon at the end of every function call.
  • You can put as many function calls as you want in between the line that reads function draw() { and the } that follows it. (We won’t talk about what function draw() means for now, or what the curly braces mean. Just know that you can put more stuff in between those curly braces if you want more stuff to happen.)

It important to mention now that you don’t need to remember all the different function available. You can find all p5.js functions in the p5.js reference. Which are extremely well documented and I would suggest you keep this page open while playing around with code in the P5.js editor.   For now, we’re going to focus just on the most simple functions for drawing shapes to the screen. As the course progresses, we’ll learn about other functions that do more interesting things.

Add another shape

This is pretty boring so far. Let’s add another shape.


The rect() function draws a rectangle to the screen. The parameters to the rectangle function have the following meaning (which you can also find on the P5.js references page

  • parameter 1: the X position of the rectangle’s upper left-hand corner
  • parameter 2: the Y position of the rectangle’s upper left-hand corner
  • parameter 3: the rectangle’s width
  • parameter 4: the rectangle’s height

And as mentioned above this is also well documented on the P5.js reference page. Do have a look as its shows some additional parameters to this particular function. Notice that the functions are called in the same order as they’re drawn. That means that the rectangle gets drawn on top of the ellipse. If you reversed the order of the commands, the ellipse would be drawn on top instead:


Background color The background() function sets the background color for the entire sketch. Call it first in the draw() block, like so:


As with the  rect() function the background function is followed by a set of parameters (). In this example we only use one parameter (50) which is a greyscale value between 0 and 255. The value determines the shade of grey that the background will appear. 0 means black, and 255 means white; other values refer to all of the intervening shades of grey. If you call the background function with three values, you can set the background to a color of your choice (not just a shade of grey). The three parameters correspond to the red, green and blue components of the given color. (See the Processing color tutorial for an explanation of why the color is specified with red, green and blue, and why the numbers range from zero to 255.) Have a look at the reference page on background to explore all the functions and try them out in your own P5 sketch.

Coordinates

By now you’re asking yourself: now that I can set the background of my sketches, they seem awful… small. Can I made it any bigger? Also, those numbers in a call to ellipse or rect specify positions and dimensions. But what are the units? If 50 is some shape’s X position, what’s the unit? Distances in P5.js are measured in pixels.

Nearly all digital displays are broken up into tiny squares called pixels. Normally, each pixel is itself an actual, tiny, physical device that can display a color. The screen on your device right now likely has hundreds of thousands if not millions of these tiny devices. Each one is exactly the same size, and together they form a “grid.” Every p5.js sketch has a size in pixels—the number of pixels wide it is, and the number of pixels tall. By default, the sketch is 100 pixels by 100 pixels. The original Game Boy’s screen, for example, was 160×144 pixels. But in this contemporary era of “retina” displays, it’s not much.



The p5.js canvas works like a piece of graph paper. When you want to draw something, you specify its coordinates on the graph. For example, we can draw a 100x100 pixel rectangle at the point (60, 60).

The pixel in the far upper left-hand corner is designated as the pixel at coordinate 0, 0. As you move further left, the X coordinate increases. As you move further down, the Y coordinate increases, so that the coordinate of the middle of the sketch is 50, 50 and the coordinate at the lower right-hand corner is 100, 100. (If you’re used to Cartesian coordinates, this seems weird, since normally the Y value decreases as you move down. But you’ll just have to get used to the way P5 does it for the purposes of this Unit. For more information and diagrams, see the Processing coordinate system tutorial.

Change the size of your sketch

Up until now we haven’t talked about that strange function setup() { thing up at the top of the sketch’s source code. There’s one special function that you can put inside of there, called createCanvas(). This function sets the size (in pixels) of your sketch. Let’s take the example above and give it some room to breathe. Copy and paste the code below into your P5.js sketch.

The first parameter to the createCanvas() function specifies the width of the sketch, and the second specifies its height (again, in number of pixels). Now that our canvas is bigger, let’s spread our shapes out a little bit! Use the code below or (even better) start typing it in yourself by simply changing the parameters like size, background color and position on the screen.

Fill and stroke

p5.js lets you control not just the shapes that you draw but also two critical aspects of those shapes’ appearance: what color they are, and what color their outline is. You can set the color of a shape with the fill() function. Just as with background(), you can call fill with either one parameter to set its greyscale color, Or you can call it with three values, to set the color using RGB values.

Notice that the color in the fill() command applies to every shape that gets drawn after it’s called. To change the color for subsequent shapes, include a second call to fill() right before you call the function for the shape whose color you want to be different: You can change the color of the outline of the shapes using the stroke() command. Again, like background() and fill(), you can use stroke() either to set the greyscale value, or to set an RGB color. Also like fill(), a call to stroke() sets the stroke color for all shapes that follow, unless you call the stroke() function again: There’s also a function called strokeWeight() which allows you to set the width of the stroke. The width is measured in pixels, and like fill() and stroke() it applies to every function called after it: Here’s an example that puts it all together!

Other shapes

Here are some other functions that draw shapes. Each of them works a little bit differently from the next, so consult the reference page for information and instructions.

When something goes wrong

Programming is pernickety work, and it’s easy to get the syntax wrong. Computers (in contrast to us Human) are extremely good at following complex instructions, over and over, in a high speed and without any complaining. However they can’t and won’t understand your instructions is they are uncleer or full off misstakes. While learning to code you will get many errors, especially as you aren’t that familiar with the syntax yet. But this is part of coding and even the most advance coders still do get errors. If you don’t get any errors while working writing code, you are likely doing something familiar, unchallenging and possibly boring. So do embrace the challenge, if you want to do something truly amazing it will take time and many trial and error. The most important thing is not to panic and use simple reasoning to find the problem in your code. When you are frustrated, tired and upset, you are not in a good frame of mind to learn or solve a problem.

If something goes wrong in P5, you’ll get an error message. The error message will appear in that little box beneath the source code editing area. This area is also called the console.

Can you see the error in the sketch above? Don’t worry, the error message will give you some hints. The number at the beginning of the error (8 in this case) tells you the number of the line that p5.js thinks the problem is on. (Sometimes it’ll be off by a line or two, so you’ll have to hunt around.) The message gives you some idea of what the problem is, although the description is filtered through the weird language of programming language parsers. In this case, “Unexpected number” means that… p5.js found a number when it was expecting something else. On line 8, we can see that a comma is missing. Whoops! The “unexpected number” message indicates that p5.js was expecting a comma but got something else (a number) instead. This problem is easily fixed: just add the comma back in, and you’re ready to go. As a beginner its most likely that your error will related to a missing (or to many) commas, Semicolons, Brackets curly brackets. If you have been staring at it to long and still can’t find the error, ask a peer as a fresh pair of eyes normally spots the missing comma from a miles away. The P5 foundation has written a brilliant article on debugging which is worth reading! Many tips and tricks to prevent frustration in the future. https://p5js.org/tutorials/debugging.html

©2017 Jaap de Maat. All right reserved. Use for educational purpose only. Note: These tutorials are designed with support from many amazing people within the P5 community. Incl. Lauren McCarthy, Allison Parrish, Rune Madsen, Daniel Shiffman, Taeyoon Choi and Golan Levin to name a few.