Tutorial

What is a function again?

In p5, there are two functions we always use in our sketches. These functions are setup() and draw() and we’ll return to the specifics of both a little later, but I just wanted to start off by defining a function.

We write functions as a set of instructions that we tell our computer to follow. A computer goes through these instructions line by line. In this case, in the setup, we’re creating the canvas, and then after running the code in the setup function, we jump down to the draw function and draw the background color. Functions are always written with the function name and parenthesis followed by curly brackets. Within the curly brackets is where we tell our function what to do.

To add images we need a new function called preload() this will make sure we have access to the media we want to add to our sketches before we draw them onto the canvas. Other examples of media you might add to the preload function include sound files, video files, or font files.

video of the uploading images to the p5.js editor

video of the uploading images to the p5.js editor

adding an image with the preload function

The first thing we need to do is upload our images to the p5.js editor.

In the editor you’ll click on this side arrow next to where it says sketch.js where your sketch files are. We’re going to hit the drop down menu and select ‘create folder’ and name it assets. Then, we’re going to upload our pngs to this folder, by clicking into the folder and using the drop down menu to select ‘upload file’. The navigate back to your sketch.js file.

To add an image to our p5.js sketch we need to first give it a memorable name. I’ll call mine pizzaSlice.

Next, I’ll tell p5 to loadImage and then I’ll say where to find that image. In parenthesis, I put quotes and the path to the image.

Now I’ll add a backslash to say, from the current directory, go to this directory, and then chose the image.

function preload(){
pizzaSlice = loadImage('/assets/pizza.png') // load an image with a transparent background from the assets folder
}
function setup(){
createCanvas(400, 400); 
}
function draw(){
background(220);
}

adding the image into draw

Now I can go to the draw function and add my image by writing image, followed by the name I chose and the x and y positions on the canvas and the width and height of the image. I want to start off by putting my image in the center of the canvas, so I’ll write 200, 200. I’ll also resize my image a bit smaller to 50, 75 so I know it will fit on the canvas.

function preload(){
 pizzaSlice = loadImage('/assets/pizza.png')
}
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  image(pizzaSlice, 200, 200, 50, 75);
}

variables