Ensimmäinen ohjelma

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

function draw() {
  fill(0);
  stroke(255);

  // aaltosulut: alt+shift+8 ja alt+shift+9
  // puolipilkku: shift+,
  if (mouseIsPressed) {
    circle(mouseX, mouseY, 50);
  }
}

Sommitelma

https://p5js.org/learn/coordinate-system-and-shapes.html

https://p5js.org/learn/color.html

function setup() {
  createCanvas(500, 500);
  background(255);

  strokeWeight(50);
  stroke(30, 50);
  noFill();

  rect(30 + 80, 30 + 80, 80, 80);
  rect(30 + 40, 30 + 40, 160, 160);
  rect(30 + 40, 30 + 40, 160, 160);
  rect(30 + 80, 30 + 80, 240, 240);

  rect(30 + 280, 30 + 280, 40, 40);
  rect(30 + 320, 30 + 320, 80, 80);
}

function draw() {}

Sattumanvaraisuus

https://www.ryojiikeda.com/project/testpattern/

https://p5js.org/reference/#/p5/random

function setup() {
  createCanvas(400, 400);
  background(255);
  noStroke();
  frameRate(10);
}

function draw() {
  fill(random(255));
  var w = random(1,50);
  var x = random(width-w);
  rect(x, 0, w, height/2);

  fill(random(255));
  w = random(1,50);
  x = random(width-w);
  rect(x, height/2, w, height/2);
}

Noise

https://p5js.org/reference/#/p5/noise

function setup() {
  createCanvas(600, 600);
  background(255);
}

function draw() {
  //139, 39, 214
  //39, 170, 214
  var r = 39 + noise(frameCount * 0.005) * 100; //39-139
  var g = 39 + noise(frameCount * 0.005 + 50) * 131; //39-170
  var b = 214;
  stroke(r, g, b, 10);
  let x1 = noise(frameCount * 0.005) * width;
  let y1 = noise(frameCount * 0.005 + 100) * width;
  let x2 = noise(frameCount * 0.005 + 200) * width;
  let y2 = noise(frameCount * 0.005 + 300) * width;
  line(x1,y1,x2,y2);
}

Blend modes

https://p5js.org/reference/#/p5/blendMode

function setup() {
  createCanvas(600, 600);
  noStroke();
}

function draw() {
  blendMode(BLEND);
  background(255);

  blendMode(MULTIPLY);
  fill(255, 0, 0, 100);
  rect(noise(frameCount * 0.01) * (width-300), noise(frameCount * 0.01 + 100) * (height - 300), 300);

  fill(0, 255, 0, 100);
  rect(noise(frameCount * 0.01 + 1000) * (width-300), noise(frameCount * 0.01 + 2000) * (height - 300), 300);

  fill(0, 0, 255, 100);
  rect(noise(frameCount * 0.01 + 10000) * (width-300), noise(frameCount * 0.01 + 100) * (height - 300), 300);
}

Häivytys

'Häivytys' efektin voi toteuttaa esimerkiksi läpinäkyvällä background -värillä:

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

function draw() {
  background(220, 10); // here a slightly transparent backgound results in a 'fade' effect
  rect(random(width), random(height), 50);
}

Koodieditorin käyttö

Koodieditorin käyttö omalla koneella selaimen sijaan:

https://p5js.org/get-started/ kohta 'Setting up p5.js with an editor on your own computer'

https://timrodenbroeker.de/how-to-use-p5-js-with-visual-studio-code/