How to create a sketch app in JavaScript using P5.JS

I have been learning P5.JS for a while now and though it would be nice to share the process and progress in form of a tutorial, which will motivate me to continue learning and give others access to it.

We will learn how to create a sketch app. I have kept it as basic as I can, this makes it easy to understand and quick to create.

To follow this tutorial you need to know basics of HTML and JavaScript.

Let’s start with What is P5.JS?

P5.JS is a javascript library based on Processing which was originally written in Java, for creating interactive applications, the reason to create such a framework was to make coding accessible for artists, educators, and beginners, over the years there have been many ports of this framework in different languages and P5 is one of them.

First, we need to get P5.JS(minified version), we are going with minified version because it contains the complete library in the smallest footprint possible.

Creating the bare-bone structure of the project

index.html lib/p5.min.js

We will then create run.js, this file will contain all the code we will be writing.

As you can see above we have the p5.js library before run.js, since web browsers read code line by line it is important that the library is interpreted before run.js, otherwise all the code we have written will contain error because the web browser does not know what we are trying to do.

In P5.JS all the naming convention is followed based on what the function does and what it contains, this makes it easy to understand to a beginner.

It’s time to edit the run.js file.

The first function will be setup(). This will contain all the code that will initialize the program more like rules and instruction to follow.

function setup() { }

We will create the draw() function below setup(). The draw function will contain all the drawing tasks that will be running inside the canvas element that we will create in the next step.

function draw() { }

The code should look something like this.

function setup() { }
function draw() { }

Creating the canvas inside setup() using createCanvas() function.

The createCanvas() element takes two parameters, width, and height.

function setup() {
createCanvas(800, 800); // width, height
}

If you open the web page you will see a white box with a size of 800 x 800 surrounded by a border of 2px.

You can change the background color using the background() function that takes one parameter.

As you can see in the above code we have an if statement that has the mouseIsPressed function, this function checks if the mouse is pressed, using the if statement we are telling it to draw a rectangle with the rect() function on the X axis and Y while maintaining a width and height of 2px.

With the fill() function, we will make rect have its interior have white color.