JAVASCRIPT

9.29.22 - Day 2
Agenda
what we're doing today:
  • ~JS Continued
  • ~How do you use canvas?
  • ~Working with JS libraries
  • ~JS Libraries: 2D
  • ~JS Libraries: Data Visualization
  • ~JS Libraries: Motion Graphics & Animation
  • ~JS Libraries: 3D & WebGL
  • ~JS Libraries: Physics Engines
  • ~JS Libraries: Text
  • ~JS Libraries: Audio
  • ~Group Assignment!
Checking in
sharing!
  • What is one way you have stepped outside of your comfort zone recently?
Get the code for today's class
Clone the repo here
Variable Scope
Reassignment
  • ~Be careful of where you reassign variables to new values
  •                   
                        <!-- /exercises/01-js-variables.html -->
                        let name = "David";
    
                        function greetTeacher() {
                          console.log("Hi, " + name);
                        }
    
                        name = "not David";
    
                        <!-- What will we see in the console? -->
                        greetTeacher();
                      
                    
Variable Scope
Local scope
  • ~Variables are scoped to where they are defined
  • ~In this case, movie and director are created inside createCollab()
  •                   
                        <!-- /exercises/02-js-scoping.html -->
                        let musicalArtist = "David Bowie";
    
                        function createCollab() {
                          let movie = "Labyrinth";
                          let director = "Jim Henson";
                          console.log("\"" + movie + "\" by " + director + " feat. " + musicalArtist);
                        }
    
                        createCollab();
    
                        <!-- This won't work. Why? -->
                        console.log(director);
                      
                    
Variable Scope
let vs var
  • ~var is from the older js days
  • ~However you'll still see var quite often, so you should know how it differs from let
  •                   
                        <!-- /exercises/03-js-scoping-let-var.html -->
                        function sayHelloVar() {
                          if (true) {
                            var phraseA = "Hello";
                          }
                          console.log("[ sayHelloVar() ] " + phraseA);
                        }
    
                        function sayHelloLet() {
                          if (true) {
                            let phraseB = "Hello";
                          }
                          console.log("[ sayHelloLet() ] " + phraseB);
                        }
    
                        <!-- This works! -->
                        sayHelloVar();
    
                        <!-- This won't work. Why? -->
                        sayHelloLet();
                      
                    
Arrays
Adding and removing
            
              <!-- /exercises/04-js-array-add-remove.html -->
              let fruits = ["Granny Smith Apple", "Honeycrisp Apple",  "Fiji Apple"  ];

              <!-- push() adds to the end of the array -->
              fruits.push("Gala Apple");

              <!-- pop() removes from the end of an array -->
              fruits.pop();

              <!-- unshift adds to the beginning of an array -->
              fruits.unshift("Jazz Apple");

              <!--
                splice() can add and remove at specified indices
                here is an example of removing at an index
                say we want to remove "Honeycrisp Apple"
                first, we find its index (handy for lengthy arrays)
              -->

              let index = fruits.indexOf("Honeycrisp Apple");

              <!-- if the array has "Honeycrisp Apple", we remove it -->
              <!-- if index is -1, it doesn't exist in the array -->
              if (index > -1) {
                fruits.splice(index, 1);
              } else {
                console.log("Honeycrisp Apple does not exist in the array.");
              }
            
          
Arrays
Indexing
            
              <!-- /exercises/05-js-array-indexing.html -->
              let fruits = ["Apple", "Fig", "Pomegranate", "Mulberry"];

              <!-- returning by index (recall that we start at 0) -->
              console.log("My favorite fruit is: " + fruits[2]);

              <!-- looping through an array -->
              <!-- arrays are objects! they have a property called length. -->
              for (let i = 0; i < fruits.length; i++) {
                console.log('fruits[' + i + '] is: ' + fruits[i]);
              }
            
          
Arrays
filter() and map()
Arrays
filter() and map()
  •                   
                        <!-- /exercises/06-js-array-functions.html -->
                        let fruits = [
                          "Granny Smith Apple",
                          "Honeycrisp Apple",
                          "Fiji Apple",
                          "Gala Apple",
                          "Strawberry",
                          "Blackberry",
                          "Raspberry",
                          "Yellow Nectarine",
                          "White Nectarine",
                          "Navel Orange"
                        ];
    
                        <!-- filter -->
                        let onlyApples = fruits.filter(function(fruit) {
                          return fruit.indexOf("Apple") > -1;
                        });
    
                        console.log(onlyApples);
    
                        <!-- map -->
                        let editedFruits = fruits.map(function(fruit) {
                          return fruit + "s are yummy";
                        });
    
                        console.log(editedFruits);
                      
                    
Objects
Revisited
  • ~Here's an example of an object with a function as a property
  • ~The key is the name of the function, its value is the function definition
  • ~this refers to this particular object
  •                     
                          <!-- /exercises/07-js-objects.html -->
    
                          let grammyWinner = {
                            name          : "Supernatural",
                            Artist        : "Santana",
                            age           : 23,
                            releaseDate   : "June 15, 1999",
                            grammyWins    : 9,
    
                            updateRecords : function(amt) {
                              <!-- What is 'this'? -->
                              this.grammyWins += amt;
                            }
                          };
    
                          grammyWinner.updateRecords(3);
                        
                      
Objects
Printing the to the console
            
              <!-- /exercises/07-js-objects.html -->

              let grammyWinner = {
                name          : "Supernatural",
                Artist        : "Santana",
                age           : 23,
                releaseDate   : "June 15, 1999",
                grammyWins    : 9,

                updateRecords : function(amt) {
                  <!-- What is 'this'? -->
                  this.grammyWins += amt;
                }
              };

              <!--
                If you try this in the console you'll notice it won't work as
                expected, you'll get grammyWinner: [object Object]
              -->

              console.log('grammyWinner: ' + grammyWinner);

              <!-- You can use JSON.Stringify() to print the contents as a string -->
              console.log(JSON.stringify(grammyWinner));

              <!-- Or you can use this to get an expandable object in the dev tools -->
              console.log('grammyWinner:', grammyWinner);
            
          
Objects
document, window, console
  • ~You've been working with objects all along
  • ~REFERENCE: MDN Web Docs: console, document, window
  •                   
                        console.log("hello");
                      
                    
                      
                        document.getElementById("myDiv");
                      
                    
                      
                        window.onload = function() {
                          init();
                        }
                      
                    
Event Handling & Interactivity
Web API Built-In Functions
  • ~Events are what enables interactivity on the web
  • ~onchange, onkeydown, onmouseover, onsubmit, onresize
  • ~There are many ways to capture events, but EventListeners are most flexible
  • ~What's the difference between event handlers & event listeners? [link]
Event Handling & Interactivity
Web API Built-In Functions
            
              <!-- /exercises/08-js-events.html -->
              <body>
                <div id="interactive-div">
                  <span id="click-text">Click to change my color!</span>
                </div>
              </body>
            
          
            
              <!-- /exercises/08-js-events.html -->

              let elem;
              window.addEventListener('load', init);

              function init() {
                elem = document.getElementById('interactive-div');
                elem.addEventListener('click', function() {
                  elem.style.background = getRandomColor();
                });
              }

              <!-- generate random hex values -->
              function getRandomColor() {
                var letters = '0123456789ABCDEF';
                var color = '#';
                for (var i = 0; i < 6; i++) {
                  color += letters[Math.floor(Math.random() * 16)];
                }
                return color;
              }
            
          
HTML5 Canvas API
Getting started with <canvas>
  • ~<canvas> is just another HTML element
  • ~Because of that, you can apply CSS to them
  • ~We use the canvas to draw graphics, both in 2D and 3D
  • ~You'll see in the p5.js week, with createCanvas(400, 400);
HTML5 Canvas API
Coordinate Systems
HTML5 Canvas API
Getting the context
  • ~To get started with using the <canvas> we need to get its rendering context
  •                 
                      <!-- /exercises/09-js-canvas-intro.html -->
                      <body>
                        <canvas id="my-canvas"></canvas>
                      </body>
                    
                  
                    
                      <!-- /exercises/09-js-canvas-intro.html -->
                      let canvasElement = document.getElementById('my-canvas');
                      let ctx = canvasElement.getContext('2d');
                    
                  
HTML5 Canvas API
2D Drawing in the Canvas
            
              <!-- /exercises/09-js-canvas-intro.html -->
              canvasElem.width = 500;
              canvasElem.height = 500;

              function draw() {
                <!-- to set a background, we create a rect and fill it -->
                ctx.fillStyle = "#520086";
                ctx.fillRect(0, 0, canvasElem.width, canvasElem.height);

                <!-- draw a circle -->
                ctx.beginPath();
                ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
                ctx.fillStyle = "black";
                ctx.fill();

                ctx.lineWidth = 2;
                ctx.strokeStyle = "#cfcfff";
                ctx.stroke();
              }
            
          
HTML5 Canvas API
2D Drawing in the Canvas
  • ~If you have prior experience with p5.js, you'll notice how similar or familiar this is
  • ~Working with Canvas API can be tedious; it's a good idea to use libraries
  • ~However, it's still good to have an understanding of what's happening behind the scenes
Generative Art on Canvas
Resources
Intro to Using JS Libraries
Working with external libraries
  • ~Libraries are a file or set of files made up of functions
  • ~They typically help speed up development, especially if they 'wrap' other code
  • ~Some examples of utility libraries: JQuery, Moment(legacy), Dayjs
  • ~We'll cover more libraries on Thursday
Intro to Using JS Libraries
How do you use them in your code?
  • ~You typically link to them with <script> tags in your HTML
  • ~You may also see import or include or require
  • ~These typically occur when JS files need to include functions from other JS files
  • ~We'll see some of this in Week 5, when we cover NodeJS
Intro to Using JS Libraries
How do you use them in your code?
  • ~Depending on your dev needs, you might choose to have the libraries locally in your code
  • ~It's also common for libraries to be available via a Content Delivery Network, or a CDN
  • ~Because you're getting these files from the cloud, it will decrease load time
  • ~Possible concerns: security, complexity
Optional: Intro to JQuery
more code
Clone the repo here
Javascript Libraries
2D
Javascript Libraries
Data Visualization
Javascript Libraries
Motion Graphics & Animation
Javascript Libraries
3D & WebGL
Javascript Libraries
Physics Engines (2D & 3D)
Javascript Libraries
Text & Effects
Javascript Libraries
Audio
Assignment Ideation
Let's get our brains moving
  • ~Grab something to draw/write with/on
Design a website about an art piece/artist/art style
You have 2 minutes
Bob Ross
Design a website about nature
You have 2 minutes
Trees & stuff
Design a website about heat
You have 2 minutes
yummmm...
Design a website about the color Yellow
You have 2 minutes
insert yellow here!
Design a website about Change
You have 2 minutes
the only constant
Design a website about something not covered by this list
You have 2 minutes
?
Assignment Ideation
breathe for a sec
  • ~Look over your designs – choose your favorite
GROUP ASSIGNMENT
Yes, groups
  • ~Share your favorite design(s) with your group
  • ~Create a single page website based off of some of your favorite ideations
  • ~This can be one you all gravitated towards, a combination, or something different altogether
  • ~Maybe make it generative?
  • ~Discuss: how do you want to work? How can you support each other?
GROUP ASSIGNMENT
REQUIREMENTS
  • ~Use at least one JS library
  • ~Incorporate some level of interactivity (it doesn't need to be complex!)
  • ~Each person must have a role and be prepared to talk about it
  • ~Create a Git repo for your project, and publish to a Github page
GROUP ASSIGNMENT
More on Git requirement:
  • ~Only one person needs to create the repo
  • ~Everyone else will be a contributor to that repo
  • ~We haven't covered collaborative Git practices, so you will need to coordinate
GROUP ASSIGNMENT
Resources: