ID2116_Week3: intro to p5.js

https://p5js.org/

What is p5.js ?

  • A JavaScript library for “Creative Coding”.
  • Created by Lauren McCarthy & Developed by Open-source community.
  • You can create web applications that run on a web browser.
    • graphic / sound / video / 3D / network

hello.p5.js

http://hello.p5js.org/

What can we create with p5.js?

Getting Started with p5.js

Create a p5.js account

  1. Open p5.js web editor
    https://editor.p5js.org/

  2. Click “Sign up” → Select Login with Google or Sign Up with your email address.

  3. Now you can save and share your sketches!!!

p5.js Web Editor

p5.js Fundamentals

p5.js Program Loop

  • preload():
    load large files(image,video,sound etc) before the page is loaded.
  • setup():
    run once when the script is loaded.
  • draw()
    repeatedly execute code at a refresh-rate specified with frameRate()
    (e.g. frameRate(30): 30 fps)

Program loop: micro:bit vs p5.js

on start → setup() : run once

forever → draw() : repeat forever

Untitled

p5*js special characters

Comments:

       //        single line comment
      /* */     multiple line comment

Block:

       { }        a chunk of code that consists of program statements. (e.g. function)

End of Statement (optional):

       ;           denotes the end of a program statement. (e.g. print(“hello”); )

p5*js graphic functions

https://editor.p5js.org/didny/full/K7jCPnm7l

Color / Fill / Stroke

p5*js graphic functions

https://editor.p5js.org/didny/sketches/K7jCPnm7l

2D Primitives

p5*js UI Elements

https://editor.p5js.org/didny/sketches/6PIgfbNXR

LOGGING

UI Elements

p5*js special variables

  • canvas related
    • width, height : width and height of the canvas
    • windowWidth, windowHeight: width and height of the browser window
    • frameCount: the number of frames since starting of the sketch
    • frameRate(10) : set the speed for how often the frame is drawn
    • millis(): the number of milliseconds since starting the sketch

p5*js special variables (cont.)

  • mouse related
    • mouseX, mouseY : xy coordinates of mouse pointer
    • pmouseX, pmouseY : xy coordinate of mouse pointer from previous frame
    • mouseIsPressed : boolean value if mouse if pressed
    • mouseButton : which button is pressed (left, right, middle)

p5*js CheatSheet

https://docs.google.com/document/d/12d8zkS8sLMzR_0oCEbfXAOM8GmB3X5LDrMvxU9ggp34/edit?usp=drivesdk

p5.js Programming Fundamentals

Week3 P5.JS Hands-On

H01: Drawing a Smiley

let's draw a smiley face with p5.js!

  • What steps do we need to go through to draw this smile?
  • What are the properties of the face?
  • Use the problem decomposition technique we learned last week and try to figure it out in a minute.

steps for drawing a face

- Draw the outline.
    - Paint the inside with color.
- Draw the eyes (right eye and left eye)
- Draw the mouth
- Draw the text

p5*js steps for drawing a face

  1. crete a drawing area: createCanvas(width,height);

  2. Set the background color of the canvas: background(color);

  3. Set the color and thickness of the lines stroke(color); strokeWeight(lineWeight);

  4. Set the Fill Color fill(color);

  5. Draw the outline: circle(x,y,d);

    1. Draw the eyes (right eye and left eye)
      line(x1,y1,x2,y2);

    2. Draw the mouth: arc(x,y,w,h,start,stop);

    3. Draw the text textSize(size); text(text, x, y);

p5*js smiley

https://editor.p5js.org/didny/sketches/d_QxCFCRy

function setup() {
  //create a drawing area
  createCanvas(400, 400);
}

function draw() {
  //set background color
  background(220);
 
  //set color and weight of lines
  stroke(0);
  strokeWeight(10);
  //set fill color
  fill(255,255,0);
  //draw the outline
  circle(200,200,200);
  
  //draw the eyes
  line(170,150,170,220);
  line(230,150,230,220);
  
  //draw the mouth
  arc(200,230,100,100,0,PI);
  
  //draw a text
  fill(0);
  textSize(50);
  text("YAY!!!",130,350);
}

H01: Challenges

  • the position and size of each part of the face is specified directly.
    Define variables for these so that they can be moved freely.

  • Once the variables are defined, let's try to create faces that represent other emotions by adjusting the values of the variables.

  • Create functions that draw faces representing different emotions, such as sadFace().

  • Referring back to the MicroBits exercise, define a new variable, the hunger value, and create a conditional that changes the emotion depending on its value.

H02: micro:Tamagotchi p5*js version

Next, let's try loading images instead of the drawing with graphic functions.

To do so, we need to follow the steps below.

  1. Upload image(s) to p5.editor.
  2. Specify the image path and load the image into the variable.
  3. Read the image drawing function and display the image.

H02: Upload Image

  • download emoji.zip
  • create folder "img"
  • upload images under the folder.

H02: Create variables to load images


// define global variables for image
let sadFaceImage;
let neutralFaceImage;
let happyFaceImage;

function preload() {
  // load images 
  sadFaceImage = loadImage("img/sad.png");
  neutralFaceImage = loadImage("img/neutral.png");
  happyFaceImage = loadImage("img/happy.png");
}


H02: Define functions to draw faces

//sad face
function sadFace() {
  imageMode(CENTER);
  image(sadFaceImage, width / 2, height / 2);
}
//happy face
function happyFace() {
  imageMode(CENTER);
  image(happyFaceImage, width / 2, height / 2);
}
//neutral face
function neutralFace() {
  imageMode(CENTER);
  image(neutralFaceImage, width / 2, height / 2);
}

H02: Define a variable to change the face

  • define a emotionState variable
  • create if-else statement to change face drawing function.
let emotionState = "happy";

function draw() {
  background(250);

    textSize(32);
    text("emotion: " + emotionState, 100, 320);

    if (emotionState == "sad") {
        sadFace();
    } else if (emotionState == "neutral") {
        neutralFace();
    } else if (emotionState == "happy") {
        happyFace();
    }  
}

[Challenge]
Define a variable "hungerLevel"
Try to change the "emotionalState" according to the "hungerLevel".

Now how can we reduce the hunger level at regular intervals?

Thre are two options

Update "hungerLevel" using millis() timing.

  • Record the millis() value at a certain time in prevTime.
  • Compare the difference between the current mills() value
    and prevTime in the draw() loop.
  • If the mills() value and prevTime are greater than the specified updateInterval value (= three seconds), execute the code.
  • Record the millis() value in prevTime after the code is executed.

Update "hungerLevel" using millis() timing. 2

 let prevTime = 0;
 let updateInterval = 3000; //every 3000ms

 function draw(){

  if (millis() - prevTime > updateInterval) {
    hungerLevel = hungerLevel - 1;

    if(hungerLevel < 0){
        hungerLevel = 0;
    }

    prevTime = millis();
 }

 }

Update "hungerLevel" using setInterval()

 let prevTime = 0;
 let updateInterval = 3000; //every 3000ms
 let hungerLevel = 100;

  function setup(){
      createCanvas(400,400);
      setInteval(updateHunger, updateInterval);
  }

  function updateHunger(){
    hungerLevel = hungerLevel - 1;

    if(hungerLevel < 0){
        hungerLevel = 0;
    }
  }

 function draw(){
    textSize(40);
    fill(0);
    text("hunger: " + hungerLevel, 100, 100);
 }

H02: Final Code

p5Tamagtchi code:
https://editor.p5js.org/didny/full/iNvHxQeRQ

microTamagotchi code:
https://makecode.microbit.org/_0aVhkJPps9UM

H02: Final Code
(graphic function ver.)

p5Tamagotchi code:
https://editor.p5js.org/akbar/sketches/wXDnKRx6S

microTamagotchi code:
https://makecode.microbit.org/_McrEPpXguc6h

H02: more challenges

  • Add Feed Button
  • Add Hunver Value Slider
  • Add more emotional states
  • Animate Emoji Face

Next week:

Interface micro:bit with p5*js

Things to Bring:

  • An object from home that you could attach a micro:bit LED face to and animate.
  • AAA batteries or USB PowerBank.
  • ID1115 Arduino Kit (if you have one)

References 1/2:

p5*js cheat sheet

https://docs.google.com/document/d/12d8zkS8sLMzR_0oCEbfXAOM8GmB3X5LDrMvxU9ggp34/edit?usp=drivesdk

p5.js Refereces:

https://p5js.org/reference/

Coding Train by Daniel Shiffman

https://thecodingtrain.com/beginners/p5js/

References 2/2:

w3school: JavaScript Tutorial

https://www.w3schools.com/js/

CodeAcademy JavaScript tutorial

https://www.codecademy.com/learn/introduction-to-javascript

p5.play

https://molleindustria.github.io/p5.play/

What you will be able to create after wk3 and wk4

Annotate the program to tell what the code is intended to do. Can also be used to temporarily prevent code from being executed.

https://editor.p5js.org/didny/sketches/d_QxCFCRy