Introduction to p5.js - skyrockprojects/p5js-intro GitHub Wiki

https://github.com/skyrockprojects/javascript-intro/blob/master/img/free_fall.png


Table of contents:


Welcome to Introduction to p5.js! In this tutorial, you will learn the basics of P5 and create some cool pet projects.

Prerequisites:

Familiarity with JavaScript and HTML

Topics:

  • What is p5.js and what is it for?
  • p5 Canvas
  • Two important functions: setup() and draw()
  • Basic Shapes
  • Basic Color theory
  • Animations
  • Vectors

What is p5.js and what is it for?

p5.js is a JavaScript library that provides a set of tools that make it very easy to create interactive animations using little code. It does all the hard (and boring) work of rendering graphics on one's screen and allows one to focus on the creative aspect of their work. For example, if you want to draw a circle on a screen, you simply have to provide the center and radius of the circle. You need not worry about how to 'draw' it on the screen. p5.js will take care of it.


p5 Canvas

Canvas is the container that contains all the objects one draws on screen. One can actually find many analogies between a painter's canvas and p5 canvas. Just like an actual canvas, a p5 canvas has

  • a width and a height &
  • background color

Before you draw anything, you need to create a canvas. A canvas with width 800 and height 600 can be created using the command as shown below:

createCanvas(800, 600);

But where do we write this command? This takes us to the next step: learning about setup() and draw() functions


Two important functions: setup() and draw()

Before you continue, make sure you have downloaded the p5 folder. Open the folder and go to p5/empty-example/ folder. Open sketch.js file. You will find two functions which are currently empty: setup() and draw()

setup() function

setup() function is called once every time the HTML web page is loaded or refreshed. In this function, you can put anything that needs to be set once. For example, you need to draw a canvas only once. Hence, it is in this function that you will put the code for creating canvas:

createCanvas(800, 600);

Type in the above line of code inside setup() function and open index.html in a browser. Do you see anything? You probably just get a white screen. This is because the canvas you created has the same background color as the rest of your HTML page. You can change the background color of the canvas after creating the canvas:

function setup() {
    createCanvas(800, 600);
    background(0);
}

Reopen the HTML page and now you should see a black canvas. How is background(0) related to black color? We will talk about it in the next section.

draw() function

draw() function is called sixty times per second non-stop. As you may have guessed, this function can be used to draw things that move in time. In other words, all the animation related code is put inside this function. We will return to this function in a later section.


Basic Color theory

Let's get back to the question of how did background(0) translate into black background.

If you provide a single value to background function, it is mapped to a shade of gray (including black and white). A value of 0 corresponds to black and 255 to white. Any value in between corresponds to a shade of gray depending on how close the value is to 0 or 255. Try out providing different values to background() inside the setup() function and see how it works.

What if we want a more colorful background? Every color you see on a digital screen is composed of three components - red, green and blue (often abbreviated as RGB). Each component can have a value between 0 and 255. Different combination of R,G and B give different colors. To create a background something other than gray, you need to pass three values to the background() function, corresponding to values of red, green and blue components. You can create a red background by:

background(255,0,0)

You can play with different values of R,G and B and see how they work.


Basic Shapes

Now that we have learnt how to draw a canvas and how to give it any color that we want, let's start drawing new shapes on the canvas.

Point

The simplest shape that we can draw is a point on the canvas. We can draw a point using a point() function. A point function takes two parameters - the x and y co-ordinates on the canvas. Let's create a canvas of size 300 X 300 and create a point at (100,200):

function setup() {
    createCanvas(300, 300);
    background(240);
    
    point(100,200);
}

Open the index.html file and you must see a tiny point at (100,200). Please note that the top left point of the canvas is considered the origin. The x-coordinate increases as you move to the right and y-coordinate increases as you move to the bottom.

Let's plot many points on the canvas and see how it works:

function setup() {
    createCanvas(300, 300);
    background(240);
    
    for (var i = 10; i < 200; i++){
        point(i,i);
    }
}

The points are all lined in a straight line.

Rectangle

You can draw a rectangle by using the rect() function. Four parameters are required to be passed to the function: x-coordinate of top-left point, y-coordinate of top-left point, width and height of the rectangle. Let's draw a rectangle with top-left point at (100,150) and with dimensions (100,50):

function setup() {
    createCanvas(300, 300);
    background(240);
    
    rect(100,150,100,50);
}

Open index.html again and you should see a rectangle with black outline and white background. It is that simple to create a new shape.

Ellipse

You can draw an ellipse by using the ellipse() function. Four parameters are required to be passed to the function: x-coordinate of center, y-coordinate of center, width and height. Let's draw an ellipse with top-left point at (20) and with dimensions (200,40):

function setup() {
    createCanvas(300, 300);
    background(240);
    
    rect(100,150,100,50);
    ellipse(100,20,200,40);
}

Open index.html again and you should see a rectangle and an ellipse with black outline and white background. It is that simple to create a new shape.

Question: What happens if the newly drawn ellipse happens to overlap with the rectangle that was drawn earlier? Try to change the parameters of ellipse() function above so as to make it overlap with the rectangle and see what happens.

Line

You can draw a line by using the line() function. Four parameters are required to be passed to the function: x-coordinate of starting point, y-coordinate of starting point, x-coordinate of end point and y-coordinate of end point. Let's draw a line with starting point as (20, 50) and end point as (100, 250):

function setup() {
    createCanvas(300, 300);
    background(240);
    
    rect(100,150,100,50);
    ellipse(100,20,200,40);
    line(20, 50, 100, 250);
}

stroke and fill

In the last section, we learnt how to create basic shapes. But all of them have white background and black border. Wouldn't it be nice if we could make them more colorful? p5.js provides two functions that can be used to control that border color as well as background color (also known as fill color) of any shape: stroke() and fill(). Just like background() function, both these functions accept either one or three parameters corresponding to grayscale and RGB values. Any shape drawn after setting border or fill color will use the colors mentioned for drawing out shapes.

To see how it works, we will make a few changes to the shapes we just drew:

  • Change the canvas background to black
  • Change the rectangle border color to white
  • Change the rectangle fill color to gray
  • Change the ellipse fill color to red
  • Draw the line using green color

Below is the code:

function setup() {
    createCanvas(300, 300);
    background(0);
    
    stroke(255);
    fill(100);
    rect(100,150,100,50);
    
    fill(255,0,0);
    ellipse(100,20,200,40);
    
    stroke(0,255,0);
    line(20, 50, 100, 250);
}

Notice how the border color of ellipse also turns out to be white.


Animations

We learnt how to draw shapes and use colors. But how do we animate whatever we just drew? Let's take a look at the draw() function now. We are going to define a variable called radius and increment it by one inside the function draw. We will then draw a circle with radius equal to the value of radius. This is what the entire file looks like:

var radius;

function setup() {
    createCanvas(300, 300);
    radius = 0;
}


function draw() {
    radius++;
    fill(0);
    ellipse(150, 150, radius);
}

Voila! We have a circle expanding in size continuously. It is that simple to animate objects. So what exactly is happening?

Note that you just incremented radius only once inside the draw function. You might have guessed already - draw() function is called repeatedly at a rate called frameRate and everything inside the function is implemented repeatedly.

Let's get a bit more creative with animation here. We will build a series of expanding circles with background colors alternating between black and white:

var radius;

function setup() {
    createCanvas(600, 600);
    radius = 0;
    frameRate(30);
}


function draw() {
    clear();
    radius += 0.5;
    fill((radius % 20) * 255);
    var i = radius;
    if(radius % 20 != 0){
      while(i > 5){
        i -= 20;
        ellipse(300, 300, i, i);
      }
    }
}

Vectors

In this last section, we will learn how to use vectors. Vectors can make calculations much easier and much more elegant. This section assumes that you are familiar with vectors and basic vector arithmetic.

You can create a vector by using the function createVector(). It takes two or three arguments depending on the number of dimensions you are working on. In this section, we will work with two dimensional vectors only.

You can also get a dot product of two vectors u and v using the function dot() in the following manner:

var dotProduct = u.dot(v);

Let's take a look at an example. In this example, we will draw two vectors which rotate at different rates. We will also draw a circle the radius of which is proportional to the absolute value of the dot product of the two vectors. Also note the usage of function translate() that we haven't covered in this tutorial. The function translate() is used if you want to change the default origin from top left corner to one of your choice.

var r;
var u;
var v;
var theta;
function setup() {
    createCanvas(600, 600);
    r = 100;
    theta = 0;
    frameRate(30);
    u = createVector(0,r);
    v = createVector(0,r);
    fill(0);
    stroke(0);
}


function draw() {
  clear();
  translate(300,300);
  theta += 0.01;
  u = createVector(r * cos(theta), r * sin(theta));
  v = createVector(r * cos(2*theta), r * sin(2*theta));
  clear();
  line(0,0,u.x,u.y);
  line(0,0,v.x,v.y);
  var rad = pow(abs(u.dot(v)),0.5);
  ellipse(0,0,rad,rad);
}

You should see two rotating lines and a circle that changes size as the angle between the lines changes.