Creative Coding · Session c01

Your First Canvas

Shapes, colours, and the blank page.

Every p5.js sketch starts with two functions: setup() runs once when the page loads, and draw() runs over and over — up to 60 times per second. For today's first sketch we tell it to stop after one frame, so we can focus on placing shapes.

Here is a night scene built entirely from basic shapes. Look at the live result below, then read the annotated code underneath it.

Live sketch — Night at the Stable

function setup() { createCanvas(420, 260); // width × height in pixels noLoop(); // draw once — our scene doesn't move yet } function draw() { background(20, 20, 60); // dark blue sky (red, green, blue) fill(255, 240, 100); // yellow-white moon noStroke(); circle(80, 70, 70); // x, y, diameter fill(255); // white stars circle(180, 40, 8); circle(280, 25, 5); circle(350, 60, 6); circle(200, 90, 4); fill(40, 30, 20); // dark ground rect(0, 200, 420, 60); // x, y, width, height fill(60, 40, 30); // barn walls rect(150, 130, 120, 70); fill(80, 50, 30); // barn roof (triangle) triangle(140, 130, 270, 130, 205, 88); // x1,y1, x2,y2, x3,y3 fill(255, 200, 50); // lit window rect(196, 155, 28, 24); }

How coordinates work

The top-left corner of the canvas is (0, 0). X increases to the right; Y increases downward. So (420, 260) is the bottom-right corner of our canvas. This surprises most people — it's the opposite of a maths graph!

Colour: three numbers (RGB)

Every colour is a mix of Red, Green, and Blue — each from 0 to 255. fill(255, 0, 0) is pure red. fill(0) is black (all three channels the same shorthand). fill(255) is white.

Challenges — try these in order
  1. Change the sky colour to deep purple. What RGB values make purple?
  2. Add five more stars at different positions.
  3. Move the moon to the top-right corner.
  4. Add a fence in front of the barn — use several narrow rect() calls.
  5. Draw a simple horse silhouette using rectangles for the body and legs.
  6. Open challenge: Build your own night scene with at least 8 shapes.

Go to editor.p5js.org — paste the code, press ▶, and keep building!

Next session → c02: Colour You'll learn the HSB colour model (hue, saturation, brightness), how computers mix colours, and you'll build an interactive colour mixer that responds to your mouse.
← All lessons
Focus 25:00

Ask your tutor