Jeremy Troy Suchanski                                   

Web Frontend Development II

Gary James                                                                  

May 14, 2022

L09 Readings Notes

Ch14: HTML5 APIs (Notes)

data-powers = 'flight superSpeed'

const superman = document.getElementById('hero');

const powers = superman.dataset.powers;

<< 'flight superSpeed'

Code for older browers:

const powers = superman.getAttribute('data-powers');

dataset string value restriction: this can be overcome by encoding any JavaScript object or value as a JSON string, then performing type-conversion later. Code Example

const maxLength = Number(element.dataset.maxLength);

setItem(): a basic example of storing information. Code Example:

localStorage.setItem('name''Walter White');

getItem(): to get the value. Code Example

localStorage.getItem('name'); 

<< "Walter White"

assignment: this can be used instead of using the getItem() and setItem() methods. i.e.:

localStorage.name = 'Heisenberg'

 

console.log(localStorage.name); 

<< "Heisenberg";

removeItem method() or delete operator: removes an entry from local storage. i.e:

localStorage.removeItem('name')

delete localStorage.name;

clear() method: used to completely remove everything stored in local storage. i.e:

localStorage.clear();

key property: tells the key of the item that changed.

newValue property: tells the new value to which it has been changed.

oldValue property: tells the previous value before it was changed.

storageArea property:  tells if it is stored in local or session storage.

(note that this example won't work locally as it needs to be running on a server)

addEventListener('storage', (event=> {

  console.log(`The ${event.key} was updated from ${event.oldValue} to ${event.newValue} and saved in 

  ${event.storageArea}`) }, false);

localStorage strings restriction: The fact that only strings can be saved might seem like a restriction at first, but by using JSON, we can store any JavaScript object in local storage. The following will save the hero object as a JSON string using the string 'superman' as the key. Code Example

localStorage.setItem('superman'JSON.stringify(hero);

localStorage strings to JavaScript object: the JSON string in the localStorage can be converted back into a JavaScript object. Code Example:

 superman = JSON.parse(localStorage.getItem('superman'));

getCurrentPosition() method: method of the navigator object that can be used with geolocation. It will return a position object to a specified callback function, called youAreHere(). Code Example:

navigator.geolocation.getCurrentPosition(youAreHere);

position object: has a coords property with a latitude and longitude property, which together give the coordinates of the device. Code Example:

function youAreHere(position) {

  console.log(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`); 

}

position.speed property: returns the ground speed of the device in meters per second.

position.altitude property: returns an estimate of the device’s altitude in meters above the WGS84 ellipsoid, which is a standard measurement for the center of the Earth.

position.heading property: returns the direction the device is moving in. This is measured as a bearing in degrees, clockwise from North.

position.timestamp property: returns the time that the position info was recorded.

position.accuracy property: returns the accuracy of the latitude and longitude properties in meters. The lower the returned value, the more accurate the measurements are. 

position.altitudeAccuracy: returns the accuracy of the altitude property in meters. The lower the returned value, the more accurate the measurements are.

watchPosition() method: call a callback function every time the position of the device is updated. This method returns an ID that can be used to reference the position being watched. Code Example:

const id = navigator.geolocation.watchPosition(youAreHere);

clearWatch() method: used to stop the callback being called, using the ID of the watch as an argument. Code Example:

navigator.geolocation.clearWatch(id);

Worker() constructor function: creates a new worker object. It takes the name of another JavaScript file as an argument. Code Example:

const worker = new Worker('task.js');

keyword self: is used to refer to the worker.

postMessage() method: used to send a message and start the worker working. The argument to this method can send any data to the web worker. It can also be used to post a message from the worker. Code Examples:

worker.postMessage('Hello');

//For message from worker

self.postMessage('Finished');

data property of the event object: When a message is posted, a message event is fired, so they can be dealt with using an event listener. The data sent with the message as an argument is stored in the data property of the event object that’s passed to the callback function. Code Example:

worker.addEventListener('message', (event=> {

  console.log(event.data);

}, false);

terminate() method or close() method: When a worker has completed its task, it can be stopped using the terminate() method from within the main script or using the close() method from inside the worker script. Code Examples:

worker.terminate();

self.close();

dedicated web workers: are linked to the script that loaded the worker, and are unable to be used by another script.

shared web workers: allow lots of different scripts on the same domain to access the same worker object. Info Link

output() function: is used to output messages to the screen. Code Examples

function output(message) {

  const para = document.createElement('p');

  para.innerHTML = message;

  outputDiv.appendChild(para);}

send() method: a method of the connection object that sends the message to the URL that the websocket is connected to.

connection object: When this message is received, the server will process it and send a response. The connection object waits for the response, and when it receives one, a 'message' event is fired.

event object: The event object contains a number of properties that describe the event that occurred.

close event: an event that the connection object responds to that occurs when the connection is closed, which can be done using the close() method. Code Example

connection.addEventListener('close', () => {

  output('DISCONNECTED'); }, false);

error event: an event that the connection object responds to that is fired when any sort of error occurs with the connection. The information about the error can be accessed in the data property of the event object. Code Example:

 connection.addEventListener('error', (event=> {  output(`<span style='color: red;'>ERROR: ${event.data}</span>`); }, false);

requestPermission() method: a method of a Notification global object used to get permission granted. Before you can send notifications, you need to get permission granted by the user. Code Example:

if(window.Notification) {

  Notification.requestPermission(); }

permission property: the requestPermission() method returns a promise with the permission property of the Notification object set to either 'granted' or 'denied'.

constructor function:  If the permission property is set to granted, you can create a new notification with this. The constructor function's first parameter is the title of the notification, and is required. The function also accepts a second parameter, which is an object of options. These include body that specifies any text that you want to appear below the title, and icon where you can specify a link to an image that will be displayed as part of the notification. Code Examples:

if(window.Notification) {

  Notification.requestPermission()

  .then((permission=> {

      if(Notification.permission === 'granted') {

      new Notification('Hello JavaScript!');  }  }); }

 

const notification = new Notification('JavaScript: Novice to Ninja',{

  body: 'The new book from SitePoint',

  icon: 'sitepointlogo.png' });

close() method: Depending on your browser and operating system, some notifications close automatically after a short period of time, and some stay on the screen until the user clicks on them. You can close the notification programmatically using this method. i.e.:

notification.close();

notification instance events: it has a number of events that it can react to.

  1. show event: when the notification appears.
  2. close event: when the notification appears.
  3. click event: when a user clicks on the notification. Code Example:

notification.addEventListener('click', () => {

  window.open('https://sitepoint.com')

  }, false);

<audio src='/song.mp3' controls>

Your browser does not support the audio element.

</audio>

<video src='http://movie.mp4' controls>

    Your browser does not support the video element.

</video>

const video = document.getElementsByTagName('video')[0];

  1. play() method: will start the clip playing from its current position. Code i.e.:

video.play();

  1. pause() method: will pause the clip at its current position. Code Example

video.pause();

  1. volume property: a number that can be used to set the audio volume. i.e.

video.volume = 0.9;

  1. muted property: a boolean value that can be used to mute the audio. i.e.

video.muted = true;

  1. currentTime property: a number value used to jump to a part of the clip i.e.

video.currentTime += 10// jumps forward 10 seconds

  1. playbackRate property:  is used to fast-forward or rewind the clip by changing its value. A value of 1 is playback at normal speed. Code Example: 

video.playbackRate = 8// fast-forward at 8 times as fast

  1. loop property: a boolean that set to true will make the clip repeat in a loop. i.e.:

video.loop = true;

  1. duration property: can be used to see how long the clip lasts. Code Example

video.duration;

<< 52.209

  1. Checking Properties Are Available: Some of the properties are only available once the browser has received all the metadata associated with the video, so ensure a value is returned by using an event listener that fires once the metadata has loaded. Code Example: 

video.addEventListener('loadedmetadata', () => { console.log(video.duration); });

  1. play event: fires when the clip starts and when it resumes after a pause.
  2. pause event: fires when the clip is paused.
  3. volumechange event: fires when the volume is changed.
  4. loadedmetadata event: fires when all the video's metadata has loaded.

<canvas> tag:  used to specify a height & width for the box put on the web page. i.e.:

<canvas id='canvas' width='400' height='400'>Sorry, but your browser does not support the canvas element</canvas>

document.getElementById() method: can access the canvas element. Code Example: 

const canvasElement = document.getElementById('canvas');

context: an object that contains all the methods used to draw onto the canvas in 2-D context. It’s possible to render in 3-D using WebGL.

getContext() method: used to access the context. Code Example

const context = canvasElement.getContext('2d');

fillStyle property: it’s colors can be changed by assigning a CSS color to it. The color assigned will be utilized for everything that’s drawn onto the canvas until it’s changed.

context.fillStyle = "#0000cc"// a blue fill color 

strokeStyle property: it’s colors can be changed by assigning a CSS color to it and that color will be utilized for everything that’s drawn onto the canvas until it’s changed.

context.strokeStyle = "#ccc"// a gray stroke color

lineWidth property: used to set the width of any line strokes drawn onto the canvas. It defaults to one pixel and remains the same until it’s changed. Code Example

context.lineWidth = 4;

fillRect() method: draws a filled-in rectangle. The 1st 2 parameters are the coordinates of the top-left corner, the 3rd parameter is the width, & the last parameter is the height. i.e.:

context.fillRect(10,10,100,50)

strokeRect() method: works in the same way as fillRect(), but produces a rectangle that is not filled in. Code Example

context.strokeRect(10,100,100,50);

beginPath() method: starts a new path by emptying the list of sub-paths.

moveTo() method: begins a new sub-path at the point specified by (x, y) coordinates.

lineTo() method: adds a straight line to the current sub-path by connecting the sub-path's last point to the specified (x, y) coordinates.

stroke() method: method of the Canvas 2D API strokes (outlines) the current or given path with the current stroke style. Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side. Nothing will be drawn onto the canvas until the stroke() method is called. Code Examples:

context.beginPath();

context.moveTo(13050);

context.lineTo(18050);

context.moveTo(15550);

context.lineTo(15590);

context.strokeStyle = '#c00';

context.lineWidth = 15;

context.stroke();

arc() method: used to draw an arc of a given radius from a particular point. The 1st 2 parameters are the coordinates of the center of the arc; the next parameter is the radius, followed by the start angle, then the finish angle (angles measured in radians). The last parameter is a boolean that says whether the arc should be drawn counter-clockwise.

  1. Radian: about 57.2958 degrees. Code Example

context.beginPath();

context.arc(200200300Math.PI * 2false);

context.strokeStyle = '#ff0';

context.lineWidth = 4;

context.stroke();

fillText() method: used to write text onto the canvas. The 1st parameter is the text to be displayed, while the next 2 parameters are the x and y coordinates, respectively.

  1. font property: can be used to set the font style used, otherwise the style is inherited from the canvas element’s CSS setting. Code Example

context.fillStyle = '#0c0'// a blue fill color

context.font = 'bold 26px sans-serif';

context.fillText('Hello'20200);

 

 

Ch12: Canvas, SVG, and Drag and Drop (Notes)

<canvas id="myCanvas" class="myCanvas" width="200" height="200">

    Sorry! Your browser doesn’t support Canvas.

</canvas>

function drawPattern() {

  var canvas = document.getElementById("demo2");

  var context = canvas.getContext("2d");

  context.strokeStyle = "red";

  var img = new Image(); 

  img.src = "../images/bg-bike.png"; }

function drawPattern() {

  var canvas = document.getElementById("demo2");

  var context = canvas.getContext("2d");

  context.strokeStyle = "red";

  var img = new Image();

  img.src = "../images/bg-bike.png";

  img.onload = function() {

  var pattern = context.createPattern(img"repeat"); 

  context.fillStyle = pattern;                        

  context.fillRect(1010100100);                  

  context.strokeRect(1010100100); }; }

function drawGradient() {

  var canvas = document.getElementById("demo3");

  var context = canvas.getContext("2d");

  context.strokeStyle = "red";

  var gradient = context.createLinearGradient(000200); }

function drawGradient() {

  var canvas = document.getElementById("demo3");

  var context = canvas.getContext("2d");

  context.strokeStyle = "red";

  var gradient = context.createLinearGradient(000200);

  gradient.addColorStop(0"blue"); 

  gradient.addColorStop(1"white"); 

  context.fillStyle = gradient

  context.fillRect(1010100100); 

  context.strokeRect(1010100100); }

Paths: create a blueprint for your lines, arcs, and shapes, but paths are invisible until you give them a stroke.

  1. beginPath() method: resets the default path for you to begin drawing a new shape. 
  2. closePath() method: method of the Canvas 2D API attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing.
  3.  

arc() method: The signature for the arc method is: arc(x, y, radius, startAngle, endAngle, anticlockwise). The x and y represent where on the canvas you want the arc’s path to begin. Imagine this as the center of the circle that you’ll be drawing. Radius is the distance from the center to the edge of the circle. The startAngle and endAngle represent the start and end angles along the circle’s circumference that you want to draw. The units for the angles are in radians, and a circle is 2π radians. If you want to draw a complete circle use 2π (JavaScript = Math.PI x 2) for the endAngle. 

  1. radians: a unit used to measure angles, and the symbol π denotes a measurement in radians. One radian is equal to 180 degrees. Two radians, or 2π, are equal to 360 degrees.  
  2. anticlockwise: an optional argument. If you wanted the arc to be drawn counterclockwise instead of clockwise, you would set this value to true.
  3. Code Example:

function drawCircle(canvas) {

  var canvas = document.getElementById("myCanvas");

  var context = canvas.getContext("2d");

  context.beginPath();

  context.arc(5050300Math.PI*2true); }

strokeStyle: gives the shape a border. By default, the width of the stroke is one pixel, which is stored in the lineWidth property of the context object.

  1. fill() method: Not used with a rectangle. It is called to fill a path. 

fillStyle: gives the shape a fill color.

  1. stroke() method: Not used with a rectangle. It is called to stroke a path.

Code Example:

function drawCircle(canvas) {

  var context = canvas.getContext("2d");

  context.beginPath();

  context.arc(100100500Math.PI*2true);

  context.closePath();

  context.strokeStyle = "red";

  context.fillStyle = "blue";

  context.lineWidth = 3;

  context.fill(); 

  context.stroke(); }

function saveDrawing() {

  var canvas5 = document.getElementById("demo5");

  window.open(canvas5.toDataURL("image/png")); }

window load event: Let’s you know the element has loaded.

canvas drawImage() method: provides different ways to draw an image onto the canvas. Code Example:

function drawImageToCanvas() {

  var canvas = document.getElementById("demo6");

  var context = canvas.getContext("2d");

  var image = document.getElementById("myImageElem");

  context.drawImage(image00); }

canvas getImageData() method: It returns an ImageData object, which contains three properties: width, height, and data. It allows you to examine a small section of a canvas. takes four parameters, corresponding to the four corners of a rectangular piece of the canvas we’d like to inspect. If we call getImageData on a very small section of the canvas, say context.getImageData(0, 0, 1, 1), we’d be examining just one pixel (the rectangle from 0,0 to 1,1). 

  1. Data property: contains info about the pixels in the ImageData object in the form of an array. Each pixel on the canvas will have four values in the data array, which correspond to that pixel’s R (red), G (green), B (blue), and A (alpha) values.
  2. Security Error: If you’re running the code locally on your computer, you’ll be using the file:// protocol to open local files. And files loaded with the file:// protocol are considered to come from different domains, which is deemed a security error (in this case it’s an unnecessary one). The true security issue that Chrome and Firefox are attempting to prohibit is a user on one domain manipulating images on another domain. Unfortunately, in Chrome and Firefox, this origin-clean flag is also set to false while you’re testing from files on your hard drive, as they’re seen as being files that live on different domains. If you want to test pixel manipulation using canvas in Firefox or Chrome, you’ll need to either test it on a web server running on your computer (http://localhost/), or test it online.

Converting an Image from Color to Black and White

Code Example: 

function manipulateImage() {

  var canvas = document.getElementById("demo7");

  var context = canvas.getContext("2d");

  var image = document.getElementById("secondImage");

  context.drawImage(image6060);

  var imageData = context.getImageData(00200200);  

  for (var i = 0i < imageData.data.length; i += 4) {

    var red = imageData.data[i];

    var green = imageData.data[i + 1];

    var blue = imageData.data[i + 2];      

    var grayscale = red * 0.3 + green * 0.59 + blue * 0.11;      

    imageData.data[i= grayscale;

    imageData.data[i + 1= grayscale;

    imageData.data[i + 2= grayscale; } 

  context.putImageData(imageData00); }

Manipulating Video with Canvas

function makeVideoOldTimey() {

  var video = document.getElementById("video");

  var canvas = document.getElementById("canvasOverlay");

  var context = canvas.getContext("2d");

  video.addEventListener("play"function() { 

  draw(video,context,canvas);               

  }, false); }

function draw(videocontextcanvas) {

  if (video.paused || video.endedreturn false;  

  drawOneFrame(videocontextcanvas); }

function drawOneFrame(videocontextcanvas){

  // draw the video onto the canvas

  context.drawImage(video00canvas.widthcanvas.height);

  var imageData = context.getImageData(00canvas.widthcanvas.height);

  var pixelData = imageData.data

  // Loop through the red, green and blue pixels, turning them grayscale  

  var redgreenbluegrayscale;  

  for (var i = 0i < pixelData.length; i += 4) {

  red = pixelData[i];

  green = pixelData[i + 1];

  blue = pixelData[i + 2];

  //we'll ignore the alpha value, which is in position i+3      

  grayscale = red * 0.3 + green * 0.59 + blue * 0.11;      

  pixelData[i= grayscale;

  pixelData[i + 1= grayscale;

  pixelData[i + 2= grayscale;  }          

  context.putImageData(imageData00); }

function draw(videocontextcanvas) { 

  if (video.paused || video.endedreturn false;  

  drawOneFrame(videocontextcanvas);  

  // Start over! 

  setTimeout(function(){ draw(videocontextcanvas); }, 0); }

Displaying Text on the Canvas

Code Example

function drawOneFrame(videocontextcanvas){

  context.drawImage(video00canvas.widthcanvas.height);

  try {

  var imageData = context.getImageData(00canvas.widthcanvas.height);

  var pixelData = imageData.data;

  for (var i = 0i < pixelData.length; i += 4) {

      var red = pixelData[i];

      var green = pixelData[i + 1];

      var blue = pixelData[i + 2];

      var grayscale = red * 0.3 + green * 0.59 + blue * 0.11;

      pixelData[i= grayscale;

      pixelData[i + 1= grayscale;

      pixelData[i + 2= grayscale; }  

  imageData.data = pixelData;

  context.putImageData(imageData00);

catch (err) {

  // clear the canvas 

  context.clearRect(0,0,canvas.width,canvas.height);

  canvas.style.backgroundColor = "transparent";

  context.fillStyle = "white";

  context.textAlign = "left";

  context.font = "18px LeagueGothic, Tahoma, Geneva, sans-serif";

  context.fillText("There was an error rendering "1020);  

  context.fillText("the video to the canvas."1040);

  context.fillText("Perhaps you are viewing this page from"1070);

  context.fillText("a file on your computer?"1090);

  context.fillText("Try viewing this page online instead."10130); 

  return false; } }

function draw(videocontextcanvas) {

  if (video.paused || video.endedreturn false;  

  drawOneFrame(videocontextcanvas);      

  // Start over!

  setTimeout(function(){ draw(videocontextcanvas); }, 0); }

Drawing in SVG

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">

  <circle cx="50" cy="50" r="25" fill="red"/>

</svg>

<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 400 400">

  <desc>Drawing a rectangle</desc>

      <rect x="10" y="10" width="100" height="100"  

          fill="blue" stroke="red" stroke-width="3"  />   

</svg>

HTML CODE

<article class="ad-ad4">

  <div id="mapDiv">        

  <h1 id="geoHeading">Where in the world are you?</h1>

  <form id="geoForm">

      <input type="button" id="geobutton" value="Tell us!">

  </form>    

  <div class="spin" id="spinner"></div

  </div>

</article>

CSS CODE

.spin {

  positionabsolute;

  top8px;

  left55px;

}

JavaScript CODE

function determineLocation() {

  if (navigator.onLine) {

  if (Modernizr.geolocation) {

      navigator.geolocation.getCurrentPosition(displayOnMap);  

      var container = Raphael(document.getElementById("spinner"), 125125);

      var spinner = container.image("images/spinnerBW.png",0,0,125,125);

      var attrsToAnimate = { transform: "r720" }; 

spinner.animate(attrsToAnimate60000);

function displayOnMap(position) {

  document.getElementById("spinner").style.display = "none"; }

<img data-src="https://learnable-static.s3.amazonaws.com/premium/reeedr/books/html5-css3-for-the-real-world-2nd-edition/images/computer-mouse-pic.svg" width="30" 

alt="mouse treat" id="mouse1" draggable="true">

<img data-src="https://learnable-static.s3.amazonaws.com/premium/reeedr/books/html5-css3-for-the-real-world-2nd-edition/images/computer-mouse-pic.svg" width="30" 

alt="mouse treat" id="mouse2" draggable="true">

<img data-src="https://learnable-static.s3.amazonaws.com/premium/reeedr/books/html5-css3-for-the-real-world-2nd-edition/images/computer-mouse-pic.svg" width="30" 

alt="mouse treat" id="mouse3" draggable="true">

var mouse = null;

for (var i=0i < mice.length; i++) {

    mouse = mice[i];

    mouse.addEventListener('dragstart'function (event) {

    // handle the dragstart event

    }); }

mouse.addEventListener("dragstart"function (event) {

  event.dataTransfer.setData("text/plain", this.id); });

<h1>Wai-Aria? HAHA!</h1>

  <h2 id="catHeading">Form Accessibility</h2>

  <img data-src="https://learnable-static.s3.amazonaws.com/premium/reeedr/books/html5-css3-for-the-real-world-2nd-edition/images/cat.png" id="cat" alt="WAI-ARIA Cat">

var cat = document.getElementById("cat");

cat.addEventListener("dragover"function(event) {

    event.preventDefault(); });

cat.addEventListener("drop"function(event) {

  var mouseHash = {};

  1. key/value pairs: associate each response with the ID of 1 of the images. i.e.:

cat.addEventListener("drop"function(event) {

  var mouseHash = {

  mouse1: 'NOMNOMNOM',

  mouse2: 'Meow',

  mouse3: 'Purrrrrr ...' }; })

  1. h2 element: equate a variable to it. Code Example:.

var catHeading = document.getElementById('catHeading');

  1. getData() method: retrieves the ID of the dragged element from the DataTransfer object. Code Example:

var mouseID = event.originalEvent.dataTransfer.getData("text/plain");

  1. use id’s: to change the text to the appropriate response in the h2 element.

catHeading.innerHTML = mouseHash[mouseID];

  1. DOM removeChild() method: remove it from the dropped item from the page.

var mousey = document.getElementById(item);

mousey.parentNode.removeChild(mousey);

  1. preventDefault(): prevents the default behavior of not allowing elements to be dropped on the element.

event.preventDefault();