02: Introductin to p5.js - Kreativ Kodning



Kreativ Kodning

02: Introductin to p5.js

First contact with code

What you will learn


Getting started

Open: https://editor.p5js.org

Create an account to save your work.


The basic structure

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(255, 0, 0);
  ellipse(200, 200, 50, 50);
}
Function When It Runs
setup() Once at the start
draw() 60 times per second

Understanding the Code

createCanvas(width, height)

Creates a drawing surface of the specified size in pixels.

background(grayValue)

Fills the canvas with a color. 0 = black, 255 = white.

ellipse(x, y, width, height)

Draws an oval or circle at position (x, y) with specified size.


The coordinate system

(0,0)─────────────────► X increases

  │    (200, 200) = center of 400x400 canvas


  Y increases

(0, 0) is the top-left corner. Y increases going down.


Exercise: change the numbers

Try these one at a time. Predict before running.

// Canvas size
createCanvas(600, 300);
createCanvas(200, 400);

// Background color
background(0);
background(255);
background(0, 255, 0);

// Circle position
ellipse(0, 0, 50, 50);
ellipse(400, 400, 50, 50);

// Circle size
ellipse(200, 200, 100, 100);
ellipse(200, 200, 100, 50);

Resources