Week 4: February 18: p5.js DOM Interactions

Itinerary

  • Discuss readings
  • Portfolio Critique
  • Sign up for p5.js web editor
  • Introduce p5.js/DOM interactions/console.log()
  • Variables/Functions/Reference
  • Basic mouse events in webpage
  • Integrate JavaScript/p5.js libraries into your own page
  • Studio

The DOM

DOM stands for the Document Object Model. The DOM represents the document as nodes and objects, so that programs can change the document structure, style, and content. .This way, programming languages can connect to the page through accessing specific elements (EG: <p>,<div>,<footer>  tags) , IDs (EG: #khalo), and classes (EG .painting).

Image result for DOM

JavaScript allows us to dynamically select any object inside the DOM, and attach an event to it. An event from the mouse written in p5.js can be (among others):
mousePressed()
doubleClicked()
mouseWheel()
mouseReleased()
mouseClicked()
mouseMoved()
mouseOver()
mouseOut()

Psuedocode

Before we start programming, it can often be really helpful to think about writing code in simple instructions. This can be helpful for determining exactly what we want. For example, if I want to access a class named ‘box’ in an HTML document, and give it an additional class of “green”, I might think about it like this:

Start program

Open Document

Search through objects and find the one with a class named 'box'

When the object is found, append the class of green

End Program

p5.js web editor

We’ll be using the p5.js web editor during class today for working with p5.js examples.

Sign up for an account here.

References

Declaring Variables

When programming, you will need to declare a variable so you can reuse that same information over and over again in multiple places. Variables in JavaScript can be named anything – but as with CSS – there are a few guidelines to follow.

  • Avoid using numbers and spaces.
  • Variables are case sensitive
    • the variable bike is different than a variable called Bike
  • In JavaScript, we declare using a function by putting the word let in front of it. All of the methods below are valid
//this is a comment
//there is no declaration or type on this variable, can be declared later
let dog;

//this is equal to a string
let dog = "dog";

//this is equal to the integer five
let dog = 5;

//this is equal to the boolean true
let dog = true;
  • Declaring a variable at the very top of your javascript sketch is a global variable. This means it can be accessed anywhere inside your file. Notice that I can use bg inside the setup function, even though it was declared at the top.
    //make a global variable for the slider
    let bg=100;
    
    function setup() {
      // create canvas
      createCanvas(200, 200);
     
      //set the background color
      background(bg);
    
    }
  • Declaring a variable inside a function means it can only be accessed inside that function. Notice that the variable bgM is declared inside the draw function. This means I can only access and use it inside this function.
    function draw() {
    
    //let bg be the value of the mouseX position.
    let bgM = mouseX;
    
    //set the background color to the value of mouseX.
    background(bgM);
    
    //write the value of bg to the console
    console.log(bgM);
    }

Syntax

In JavaScript, almost ever line must end with a semicolon, and variables will be declared with a semicolon at the end. This tells the interpreter to go to the next line.

let x = 0;
select('.big');
createCanvas(500,500);

Functions

Functions are a built in set of instructions within code. These allow our code to run faster and work behind the scenes in the browser or embedded library. When you call :hover inside CSS this is a function that tells the browser to change the element when it sees the mouse. The p5.js library has a ton of built in functions which make our lives as designers easier for accessing and changing elements within the webpage, such as mousePressed() or setup().

Functions must be declared using this method, where curly brackets close open and close around each function. The parenthesis after the function can have an argument passed to it or not.  To declare a function, we write the word function in front, give it a name, use parenthesis, and then use curly brackets to contain the instructions for the function.

function myFunction(){
   do something;
}

To use a function by itself, we could do this:

myFunction();

or, often times we can nest functions inside other functions, and we don’t need to add the parenthesis:

mousePressed(myFunction);

We can create our own functions as well. For example, if I wanted to make a function that adds two numbers together, I would write:

function addMe(a,b){
       return a + b;
}

addMe is the name of the function. It takes two arguments, a and b. Using another built in function called return, this will give back an answer when the program runs. To run the program, I have to give it some variables.

function setup(){
     addMe(5,7);
}

function addMe(a,b){
       return a + b;
}

We wouldn’t however see the results here. In order to see the results of 5+7, we would need to either use it somewhere, or write the result to the console (which shows up in the inspector, or the bottom of the web editor). We can do this two ways.

  console.log(addMe(5,7));

or we can declare a variable to be equal to the value of addMe(5,7), and ask console.log to print that to the terminal.

  let x = addMe(5,7);
  console.log(x);

Using console.log() is a good way to debug your programs. It will show what is happening at certain points in your program. For example, if you want make sure you found the correct class, you could write to the console that the class was found. Notice that “found” is written with quotations around it. That is because this is a String. If it didn’t have quotations, console.log would look for a variable named class and variable named found.

console.log("found");
let found = 10;

function setup(){
console.log(found);
console.log("found");
}

In the second example, the console would print 10, and then print found.

More information about console.log();

Arrays

Arrays! These are a variable methods of storing large quantities of information. They can store numbers, text, and even other objects! We will use them here to store different strings of words, and in Project 2 we will use them to store lines of numbers and other objects of data.

An array is initialized like this:

let data = [5, 10, 15, 20];

To access the first element of the array, we would type

data[0];

This would return a value of 5. Arrays work where the first thing inside starts at the position of 0, and then increases to 1, then 2, and so on.

The above example has 4 pieces of data inside of it. If I wanted to access the last one, I would type:

data[3];

This would return a value of 20.

We can also use arrays to store text, which we’ll do today. The method for writing this is:

let greeting= ["hello","my", "friend"];

Notice that each piece of text has quotes around it, this is because they are strings.

To access the second element of this array I would type:

greeting[1];

This would return my. 

Randomly [access]

If I wanted to randomly choose a number, I would use the random function. It works by giving it two values, separated by a comma.

random(0,5);

This would return a float – a number with a decimal place. If I wanted to store that as a variable, I would write:

let x = random(0,5);

However, what this means is if I wanted to randomly choose an element from an array, like the example above, I would get an error:

let greeting= ["hello","my", "friend"];
let x = random(0,2);
data[x];

UNDEFINED!!

What this means is we need another function to round the random function down to an integer. The method we use for this is floor()

let greeting= ["hello","my", "friend"];
let x = floor(random(0,2));
data[x];

THIS WILL WORK!!

Accessing Elements, IDs, and Classes via p5.js

Select a specific class, element, or id

Adding a class to an object

Removing a class from an object

Adding a style to an object

Adding a position to an object

Replacing Text using html()

Examples

We’re going to go through a bunch of examples as a class of things you can do with p5.js.

Click to add Paragraph

Click to add Paragraph where you click


Change Background Color on HTML

Change Background Color via p5.js Canvas

createP + Button + mousePressed event

Using a Slider to change an element

Accessing an Array of Text + Button + mousePressed Event

Background Behind HTML

Image Random Rotate

Image Rotate Not Random

Adding JavaScript + p5.js Libraries to your websites and html pages

Just like we linked to an external CSS page and external Google Fonts, we will do the same for linking to JavaScript libraries and scripts. Working within the web editor – all of this is conveniently done for us. But, to add to our own pages, you will have to go through a few steps.

Example File Folder – This contains a javascript sketch file, the necessary libraries, html, and linked css

Folder Structure:

Below is what you should have in the <head> tag of each html file. Notice above that the libraries are located in a folder called lib.  Below you can see that each one is imported into the html file using a script tag.

<!DOCTYPE html>
<html>

<head>
<title>Example p5.js Template</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="lib/p5.min.js"></script>
<script src="lib/p5.dom.min.js"></script>
<script src="lib/p5.sound.min.js"></script>
<script src="sketch.js"></script>
<meta charset="utf-8">
</head>

<body>
</body>

</html>

In the example below, notice that the source for the libraries is through a webpage. This allows you to not have to worry about finding and downloading the library on your server. You can use a statically hosted library file from here, but you must be connected to the internet for these pages to work correctly.

<head>
<title>Example p5.js Template</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.sound.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
<script src="sketch.js"></script>
<meta charset="utf-8">
</head>

Your code that you write has to be linked into the page, just like a CSS file. Make sure this comes AFTER your CSS file. It will get information from your CSS file, and we want to make sure that it is loaded before the script.

<script src="sketch.js"></script>

You can store this in your assets > js folder, or you can keep it with the same file example folders you are working with. It’s up to you, but will overall be easier and more organized to keep them inside your js folder.

If you are creating a new sketch file inside Brackets, you need to make sure to save it as a file with
the .js extension. 

Additionally, you can develop your code using the p5 web editor, and download it as a zipped file which you can use directly. File > Download file.

<iFrame> Embedding

Often times when you click the share button on a YouTube video, you’ll see the option to embed. This is used using an iframe. This allows you to embed content directly into your page. For example, if you wanted to embed a p5.js sketch from the web editor directly into your page. Go to the File > Share > Embed and copy this code into your page. An example from mine is:

<iframe src="https://editor.p5js.org/jarivkin/embed/9-BMW9iiX"></iframe>

Homework

  • Complete your Portfolio. We will do a full critique next week.
    • All links must work.
    • Consistent navigation between pages.
    • Consistent Design
  • Complete Maxims – you should have ten of these which link back and forth to each other.
    • Stylize your own navigation from Maxim to Maxim.
  • Try to integrate one JavaScript interaction into your portfolio
  • Post six images to Are.na