The Road Ahead
In this first set of lessons, we’ll jump right in and cover the drawing features of p5.js including colour, animation, and mouse interactivity. Following this, we will discuss some of the nuts and bolts of programming such as variables, arithmetic, and decision-making.
What is p5.js?
p5.js is based on another language called Processing. Processing was created about 20 years ago to teach programming concepts to digital/visual designers in a graphical way. Processing was designed with a very “low floor” (it’s super easy for beginners/non-programmers to learn) and a “high ceiling” (you can do some very powerful interactive animations with it).
p5.js was created in 2013 and basically repackages Processing such that the programs run completely within a web browser, and it includes a free online editor. p5.js has a very vibrant and supportive online community, excellent online reference, and lots of cool examples to check out. Bookmark these pages for easy access in the future!
Everything that we’ll cover in these notes is real programming. p5.js uses all of the same concepts, structures, and design principles of other modern programming languages (like Python and Java) so learning p5.js is a great foundation for further study. Even if you decide not to learn another language, having some understanding of coding will serve you well in the future.
What is a Programming Language?
In Computer Science, a programming language must support 3 features:
-
- Sequence: When a program is run, the statements are executed in order, from top to bottom.
- Decision Making: There needs to be a way to run different branches of code depending on some condition. More formally, this is called selection in Computer Science.
- Repetition (a.k.a. “looping”): There needs to be a way to repeat a set of statements over and over a specific number of times or until some condition is satisfied.
By the way, according to the requirements above, HTML and CSS are not really considered programming languages. What do they lack?
p5.js supports all of these features, as well as a modern approach to software design called Object-Oriented Programming (OOP). We’ll cover sequence and decision-making in this first set of lessons. In the next set of lessons (2.x) we’ll talk about repetition and OOP.
What is an Algorithm?
An algorithm is a step-by-step set of instructions that solve a particular problem. Computer programs are essentially algorithms. You design a program to solve a particular problem. It could be as simple as taking input and producing the result of a calculation, or as complex as a video game with thousands of lines of code.
My favourite analogy for an algorithm is a recipe. As recipe includes a series of tasks that need to be performed in a specific order. A recipe will not work out if you miss a task or perform a task out of sequence. Similarly, in coding the order of statements is just as important as what each statement does. If you make an error with one or the other your program will not give the desired result.
Computers are not magic boxes, they are actually just “dumb” machines that only understand very simple commands. Their power comes from an ability to perform billions of simple commands per second without fail.
Try this! Think of a routine task that you perform each day; e.g., brushing your teeth, getting dressed. Write a step-by-step algorithm explaining how to perform that task to someone who has never done it before and needs every step explained in painstaking detail; e.g., “move toothbrush 2cm to the right”.
Order matters, so number each step in your algorithm. Try to incorporate some decision making (e.g., “If the water is too hot, increase the cold water. Otherwise, increase the hot water.” and repetition (e.g., “Go back to step 5, until teeth are shiny”, or “Move the brush left and right, repeat 10 times.”).
You might find this a little comical, but it’s very similar to how you write a program. A computer is nothing more than a machine that is brilliant and following very simple instructions but knows nothing about the real world.
Getting Started with p5.js
Before we go any further you need to create a (free!) account to access the p5.js online editor:
-
- Login to your Google account. Use the account provided by your school (if you are a student).
- Go to the p5.js online editor: https://editor.p5js.org/
- Click the Sign up link at the top-right corner.
- Click the Login with Google button at the bottom of the Sign Up page.
That’s it, you’re good to go, and should see the editor page with some starting code.
Starting Code
All p5.js programs start with the following code by default:
1 2 3 4 5 6 7 |
function setup() { createCanvas(400, 400); } function draw() { background(220); } |
Delete the default code and try typing it out yourself in the p5.js editor to better familiarize yourself with it. The semi-colons (;) on lines 2 and 6 are actually not required, and we will not bother typing them in future examples.
To run (or “execute”) the program, click the play button at the top-left of the window. When the program runs, you will see the result of the code in the Preview area on the right side of the window. At the moment it’s just a gray background, not too exciting, but we have to start somewhere!
The code above defines 2 functions, each of which performs a specific role in our program. A function consists of its name and some code related to the purpose of the function. To define a new function you start with the keyword function followed by the name you’d like to use (this line is called the function header). The code related to each function is enclosed in curly { braces } called a block. Notice that the code inside each { block } is indented 2 spaces, this helps to make the code easier to read.
When you click the play button, the p5.js environment runs the code in the setup() function one time only. The purpose of the setup() function is to configure a drawing area (called the canvas) for our program. In this case, the createCanvas() function call on line 2 specifies that we’d like our canvas to be 400 pixels (i.e., dots) wide by 400 pixels high. Technically you can use any size you like, but I’ll use these dimensions for all of my tutorial examples because it leaves enough room in your browser to see the code alongside the canvas.
It may not look like much else is happening, but after setup() is finished, the p5.js environment automatically runs the draw() function over and over again (~60 times/second on most computers) until you click the pause button. The number of times per second that the draw() function to update the canvas is called a frame rate. Line 6 instructs p5.js to fill the canvas with a shade of gray every time draw() is called.
Try this! Try changing the canvas dimensions and background darkness (a number between 0 and 255).
Coordinate Systems
This is a critical concept in computer graphics! In math class, you were taught to use what is called the Cartesian coordinate system when graphing functions. In this system, the origin (0,0) is at the lower-left, the x-coordinate increases as you move right, and the y-coordinate increases as you move up. Why? Because your math teacher told you so!
Coordinates in computer graphics work differently, and this will take some time for you to get used to. For computer graphics, the origin (0,0) is at the top-left of the canvas, the x-coordinate increases as usual to the right, but the y-coordinate increases as you move down. Why? Well, to make a long story short, early computer screens were designed to display pixels (dots) from left to right and top to bottom (the way we read). So for historic reasons the origin is at the top-left and y-coordinates increase as you move down in the world of computer graphics.
Pixels
I’ve mentioned the word “pixel” a few times. A pixel (picture x element) is a single dot on the screen with an (x,y) coordinate. To draw a pixel (dot) on the canvas we need to add a new line to the draw() function:
point(100,200)
Try inserting this line after line 6 in the code above. Can you see a small black dot about 1/4 of the way across the canvas and 1/2 way down? That’s a pixel! SO cute!
This line is an example of a function call. The name of the function we are calling is “point” and it requires 2 positive whole numbers (a.k.a. integers) to do its work, these are called function arguments. The first number is the x-coordinate, and the second is the y-coordinate for the point to be drawn.
Try this! Draw a few more points to get the hang of how the coordinate system works. Try to draw a short diagonal line by calling the point() function many times.
Drawing Simple Shapes
Drawing with individual pixels is a lot of fun! However, if you need to draw a shape like a square or a circle using the point() function the party ends pretty quickly. Fortunately, p5.js includes many other functions to simplify the process of drawing shapes. Below is a quick summary — click each function below to view the online reference for each function:
Being able to search and understand the information in the p5.js online reference is a very useful skill! You’ll find that the online reference is very well-written and includes a lot of short code samples to help illustrate how various functions work. You may even find more advanced versions of functions that I am not covering in these notes, but that you might find useful in the future.
You Try!
-
- Experiment with the line(), rect(), and ellipse() functions to figure out how they work. For each function, what do the arguments represent? Try drawing some shapes! Can you draw a perfect circle using the ellipse() function?
- Draw a triangle by calling the line() function three times. Is there an easier way to do this? Search the online reference and demonstrate a more efficient way.