p5.js Session 2: Your First Sketch

How the canvas works, how coordinates behave, and how to draw your first shape with colour.

Session 1 set up the editor and introduced the default template. In this session you write something real: a shape, a colour, a canvas that is yours.

Canvas size

You already know the canvas is your piece of paper. Those two numbers inside createCanvas() are its width and height in pixels. Change them and the paper changes size.

function setup() {
  createCanvas(600, 300);
  noLoop();
}

function draw() {
  background(220);
}

A wider canvas, 600 pixels across and 300 tall. We need to change the default canvas size: the Japan flag we are drawing in this session is wider than it is tall. Let’s use 600 by 300.

The p5.js preview panel showing a 600 by 300 grey canvas

How coordinates work

Every point on the canvas has an x position and a y position. x goes left to right. y goes top to bottom. The top left corner is (0, 0).

Think of a grid pinned at the top left of your piece of paper. As you move right, x increases. As you move down, y increases. The centre of a 600 by 300 canvas is (300, 150).

Diagram showing the canvas coordinate system with (0,0) at the top left and axes labeled

Colour: fill and stroke

Before you draw a shape, you tell p5.js what colour to use. fill() sets the colour inside the shape. stroke() sets the colour of the outline. Both take RGB values: three numbers between 0 and 255, one for red, one for green, one for blue.

fill(220, 0, 0);   // red fill
stroke(0);         // black outline

To remove the outline entirely:

noStroke();

These settings stay in effect until you change them. Set the colour before the shape you want to colour.

Your first shape: ellipse

ellipse(x, y, w, h) draws an ellipse. x and y are the centre point. w is the width, h is the height. When width and height are equal, you get a circle.

The Japan flag is a useful shape to aim for: a red circle, centred on a white canvas. It uses everything covered above.

function setup() {
  createCanvas(600, 300);
  noLoop();
}

function draw() {
  background(255);
  fill(220, 0, 0);
  noStroke();
  ellipse(300, 150, 180, 180);
}

Run it. That is your first real sketch.

The p5.js preview panel showing the finished Japan flag sketch

Saving your sketch

File > Save, or Cmd/Ctrl + S. Give the sketch a name by clicking the pencil icon next to the title at the top. Once saved, it appears in your account under File > Open.


In Session 3 we add more shapes and look at what happens when you combine them on the canvas.