Jeremy Troy Suchanski
Web Frontend Development II
Gary James
May 14, 2022
L09 Readings Notes
Ch14: HTML5 APIs (Notes)
-
HTML5: The W3C plans to develop future versions of HTML5 much more
frequently than previously, using smaller version increments. (i.e.:
HTML 5.1, HTML 5.2, etc)
Modules can be at different stages of maturity, from ideas to full
implementation. A useful site that checks to see if a specific feature
can be used is Can I Use. For more about the HTML5 standard – Link.
-
data- attribute: a way of embedding data in a web page using custom attributes that
are ignored by the browser.
Their sole purpose is to be used by a JavaScript program. This means
they’re perfect for adding data that can be used as a hook that
the program utilizes to access information about a particular element
on the page.
The names of these attributes can be decided by the developer, but
they must #1 start with data- #2 contain only lowercase letters,
numbers, hyphens, dots, colons or underscores #3 include an optional
string value. Their values can also be used to filter different
elements i.e., we could find all the elements that have a data-rating
value of 3 or more. Code Example:
data-powers = 'flight superSpeed'
-
dataset: To access the attribute, powers is used as if it’s a
property of the dataset object. If a data- attribute’s name
contains hyphens, they are replaced with camel-case notation, so
data-max-length would be accessed using dataset.maxLength. Any data-
attribute can be found using the standard getAttribute method. So,
the previous code could be replaced with the following if you still
need to support older browser. More info Code Examples:
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);
-
HTML5 APIs: a number of APIs that help to gain access to hardware, such as
cameras, batteries, geolocation, and the graphics card. Some of the
more popular APIs are supported in most modern browsers, but
it’s still best practice to use feature detection before using
any of the API methods.
-
HTML5 Web Storage API: provides a key-value store on the client’s computer
that is similar to using cookies but has fewer restrictions, more
storage capacity.
Storage capacity limit is much larger than the 4KB limit for cookies
(There is no actual limit in the specification, but most browsers have
a limit set at 5GB per domain.). Any data stored does not
automatically expire as it does with cookies. This potentially makes
cookies a better choice for something like showing a popup once a
day.
-
window object property “sessionStorage”: an object that works in the same way as localStorage, although the
data is only saved for the current session.
-
window object property “localStorage”: a native object with a number of properties and methods used to
store data. The information is saved in the form of key-value pairs,
and the values can only be strings. More info
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'));
-
Geolocation API: used to obtain the geographical position of the device. Because
of privacy concerns, permission to use this has to be granted by the
user first. It is a property of the navigator object. More
info - Link
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);
-
Web Workers: allow processes to be run in the background, adding support for
concurrency in JavaScript. The idea is that any processes that could
take a long time are carried out in the background.
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
-
Service Worker API: allows a worker script to run in the background with the added
benefit of being able to intercept network requests. This allows you
to take alternative action if the network is offline, and effectively
create app-like offline experiences. They also allow access to push
notifications and background syncing. Info Link
-
Websockets: allows two-way communication with a server – also known as
push messaging. This means that a connection is kept open and
responses are ‘pushed’ to the client as soon as they are
received. More info - websocket.org other 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);
-
Notification API: allows you to show messages using the system's
notifications. This is usually a popup in the corner of the screen,
but it changes depending on the operating system. An advantage of
using the system notification is that they will still be displayed
even if the web page that calls them isn't the current tab.
More info – Link1 Link2
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.
-
show event: when the notification appears.
-
close event: when the notification appears.
-
click event: when a user clicks on the notification. Code Example:
notification.addEventListener('click', () => {
window.open('https://sitepoint.com')
}, false);
-
Multimedia: Before HTML5, it was notoriously difficult to display audio and
video in browsers, and plugins such as Flash often had to be used.
HTML5 introduced the <audio> and <video> tags & a
Media API.
-
<audio> tag: used to insert audio clips into a page
using the src attribute.
Any content inside the <audio>tags will only display if the
browser does not support them. i.e.:
<audio src='/song.mp3' controls>
Your browser does not support the audio element.
</audio>
-
<video> tag: used to insert video clips into a page using the src attribute.
Any content inside the <video>tags will only display if the
browser does not support them. i.e.:
<video src='http://movie.mp4' controls>
Your browser does not support the video element.
</video>
-
Media API: for controlling the playback of the video & audio clips using
JavaScript. info
-
controls attribute: can be added (without any value) and will display the
browser’s native controls, such as play, pause, and volume
control
-
getElementsByTagName: this can be used to reference the audio or video element &
assign it to a variable. Code Example:
const video = document.getElementsByTagName('video')[0];
-
play() method: will start the clip playing from its current position.
Code i.e.:
video.play();
-
pause() method: will pause the clip at its current position.
Code Example:
video.pause();
-
volume property: a number that can be used to set the audio volume.
i.e.:
video.volume = 0.9;
-
muted property: a boolean value that can be used to mute the audio.
i.e.:
video.muted = true;
-
currentTime property: a number value used to jump to a part of the clip
i.e.:
video.currentTime += 10; // jumps forward 10 seconds
-
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
-
loop property: a boolean that set to true will make the clip repeat in a loop.
i.e.:
video.loop = true;
-
duration property: can be used to see how long the clip lasts.
Code Example:
video.duration;
<< 52.209
-
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); });
-
play event: fires when the clip starts and when it resumes after a pause.
-
pause event: fires when the clip is paused.
-
volumechange event: fires when the volume is changed.
-
loadedmetadata event: fires when all the video's metadata has loaded.
-
Other APIs: The API list is constantly growing, and includes APIs for accessing
a device’s camera, uploading files, accessing the battery
status, handling push notifications, building drag-and-drop
functionality, creating 3D effects with WebGL, and many more! A
comprehensive list of HTML5 APIs can be found at the Mozilla Developer Network.
-
Canvas Element: lets graphics be drawn on a web page in real time with
JavaScript.
It is a rectangular element on the web page. It has a coordinate system
that starts at (0,0) in the top-left corner.
Anything placed inside the tag will only display if the canvas
element is unsupported.
<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(130, 50);
context.lineTo(180, 50);
context.moveTo(155, 50);
context.lineTo(155, 90);
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.
-
Radian: about 57.2958 degrees. Code Example:
context.beginPath();
context.arc(200, 200, 30, 0, Math.PI * 2, false);
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.
-
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', 20, 200);
-
Shims and Polyfills: The terms shim and polyfill are often used interchangeably. They
are libraries of code that allow you to use the APIs as usual. They
then fill in the necessary code that's not provided natively by
the user’s browser.
-
Shim: a piece of code that adds some missing functionality to a browser,
although the implementation method may differ slightly from the
standard API.
-
Polyfill: a shim that achieves the same functionality, while also using the
API commands that would be used if the feature was supported
natively.
Ch12: Canvas, SVG, and Drag and Drop (Notes)
-
Canvas API:
can draw anything you can imagine (shapes and lines, arcs and text,
gradients and patterns) through JavaScript. This can improve the
performance of our websites by avoiding the need to download images.
In addition, canvas has the power to manipulate pixels in images and
even video.
Canvas was first developed by Apple.
It was then adopted by Mozilla and Opera, and then standardized by
the WHATWG (and subsequently picked up by the W3C, along with the rest
of HTML5).
-
Why not set width and height using CSS: If you don’t specify width and height, the canvas element
will default to a width of 300 and a height of 150. If you set the
width and height for a canvas only in CSS, the canvas element will be
300 by 150, and the CSS properties will simply determine how large the
box is that displays the image. Code i.e.:
<canvas id="myCanvas" class="myCanvas" width="200" height="200">
Sorry! Your browser doesn’t support Canvas.
</canvas>
-
Canvas default styling: has no default styling, so it’s difficult to see where it is
on the page unless you give it some kind of border in CSS.
-
CanvasRenderingContext2D: The object that’s returned by getContext is an instance of
this class.
-
CanvasPattern object: can be used as an alternate instead of a color for
fillStyle.
It
takes 2 parameters: the image to create the pattern with, and how
that image should be repeated:
The valid values (same in CSS): repeat, repeat-x, repeat-y, and
no-repeat. i.e.:
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"; }
-
onload property: property of image that communicates the event of the image being
fully loaded by the browser. Makes sure the image isn’t still
loading.
-
anonymous function: When an anonymous function is defined as an event listener, it
means that the anonymous function is being bound to that event. In
other words, the code inside that anonymous function will be run when
the load event is fired. Code Example:
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(10, 10, 100, 100);
context.strokeRect(10, 10, 100, 100); }; }
-
CanvasGradient object: can be used as an alternate instead of a color for
fillStyle.
To create a CanvasGradient, we call one of two methods:
createLinearGradient() or createRadialGradient(); then
we add one or more color stops to the gradient.
-
createRadialGradient() method: method of the Canvas 2D API creates a radial gradient using the
size and coordinates of two circles. To be applied to a shape, the
gradient must first be assigned to the fillStyle or strokeStyle
properties. It is specified by six parameters, three defining the
gradient's start circle, and three defining the end circle. (x0,
y0 and r0 represent the starting location and x1, y1 and r0 represent
the ending location)
-
createLinearGradient(): method of the Canvas 2D API creates a gradient along the line
connecting two given coordinates. It returns a linear CanvasGradient.
To be applied to a shape, the gradient must first be assigned to the
fillStyle or strokeStyle properties.
It is specified by four parameters defining the start and end points
of the gradient line. It has x0 and y0 that represent the starting
location of the gradient and x1 and y1 that represent the ending
location.
Code Example:
function drawGradient() {
var canvas = document.getElementById("demo3");
var context = canvas.getContext("2d");
context.strokeStyle = "red";
var gradient = context.createLinearGradient(0, 0, 0, 200); }
-
addColorStop() method: The offset is a value between 0 and 1. An offset of 0 is at the
start of the gradient, and an offset of 1 is at the end of the
gradient. The color is a string value that, as with the fillStyle,
can be a color name, a hexadecimal color value, an rgb() value, or
an rgba() value. Code Example:
function drawGradient() {
var canvas = document.getElementById("demo3");
var context = canvas.getContext("2d");
context.strokeStyle = "red";
var gradient = context.createLinearGradient(0, 0, 0, 200);
gradient.addColorStop(0, "blue");
gradient.addColorStop(1, "white");
context.fillStyle = gradient;
context.fillRect(10, 10, 100, 100);
context.strokeRect(10, 10, 100, 100); }
-
Other Shapes: there’s no built-in method for drawing circles or other
shapes. To draw other shapes, you must do three steps: layout the
path, stroke the path, and fill the path. Tutorial
Paths: create a blueprint for your lines, arcs, and shapes, but paths are
invisible until you give them a stroke.
-
beginPath() method: resets the default path for you to begin drawing a new
shape.
-
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.
-
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.
-
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.
-
anticlockwise: an optional argument. If you wanted the arc to be drawn
counterclockwise instead of clockwise, you would set this value to
true.
-
Code Example:
function drawCircle(canvas) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(50, 50, 30, 0, Math.PI*2, true); }
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.
-
fill() method: Not used with a rectangle. It is called to fill a
path.
fillStyle: gives the shape a fill color.
-
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(100, 100, 50, 0, Math.PI*2, true);
context.closePath();
context.strokeStyle = "red";
context.fillStyle = "blue";
context.lineWidth = 3;
context.fill();
context.stroke(); }
-
toDataURL() method: can be used to save the drawing, it creates a URL with the image in
it, (either a png or jpg, whichever is specified). You can then
right-click the image at this URL, and save it as a PNG or JPEG.
-
window.open(): opens the argument in a new tab.
Code Example:
function saveDrawing() {
var canvas5 = document.getElementById("demo5");
window.open(canvas5.toDataURL("image/png")); }
-
addEventListener() method: It is supported in all major, modern browsers, but not IE8.
There is an
old method called attachEvent(), that IE8 supports.
-
Drawing an Image to the Canvas: You can also draw images onto the canvas element.
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(image, 0, 0); }
-
Manipulating Images: Redrawing an image element from the page onto a canvas is really
no different from using an img element. Where it does become
interesting is how we can manipulate an image after we’ve
drawn it into the canvas.
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).
-
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.
-
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
-
for loop: use to iterate through each pixel in the image and change it to
grayscale.
Increment i by 4 instead of the usual 1 because each pixel takes up
four values in the imageData array—one number each for the R, G,
B, and A values.
-
grayscale mathematical formula: to convert RGB to grayscale
there’s a mathematical formula: red * 0.3 + green * 0.59 + blue
* 0.11
-
canvas putImageData() method: takes an image's data and writes it onto the canvas.
Code Example:
function manipulateImage() {
var canvas = document.getElementById("demo7");
var context = canvas.getContext("2d");
var image = document.getElementById("secondImage");
context.drawImage(image, 60, 60);
var imageData = context.getImageData(0, 0, 200, 200);
for (var i = 0; i < 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(imageData, 0, 0); }
Manipulating Video with Canvas
-
video element play event: communicates when the video begins playing.
Code Example:
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); }
-
anonymous function: allows you to pass several parameters to it from another function
if it is inside of that function.
-
video.paused || video.ended: checks to see if the video is paused or has ended.
i.e.:
function draw(video, context, canvas) {
if (video.paused || video.ended) return false;
drawOneFrame(video, context, canvas); }
-
pixelData variable: it saves several property lookups.
function drawOneFrame(video, context, canvas){
// draw the video onto the canvas
context.drawImage(video, 0, 0, canvas.width, canvas.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var pixelData = imageData.data;
// Loop through the red, green and blue pixels, turning them grayscale
var red, green, blue, grayscale;
for (var i = 0; i < 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(imageData, 0, 0); }
-
window setTimeout method: allows you to keep calling the draw function repeatedly, without
pause. The final parameter is the value for delay, which tells the
browser how long, in milliseconds, to wait before calling the
function. If it’s set to 0, it essentially runs draw
continuously. This goes on until the video has either ended, or been
paused.
function draw(video, context, canvas) {
if (video.paused || video.ended) return false;
drawOneFrame(video, context, canvas);
// Start over!
setTimeout(function(){ draw(video, context, canvas); }, 0); }
Displaying Text on the Canvas
-
try / catch block: catch the error.
-
canvas fillText() method: It takes the text to be drawn and the x,y coordinates where it
should be placed as arguments.
-
clearing the canvas: resetting the width or height of the canvas, clears the
canvas.
-
canvas.style.backgroundColor: transparent will set it to be a transparent background so the text
will be on top of the video.
-
fillStyle() and textAlign() methods: sets up the style of the text.
-
context object font property: It sets a specific font and font style & works the same way the
CSS font property does.
Code Example:
function drawOneFrame(video, context, canvas){
context.drawImage(video, 0, 0, canvas.width, canvas.height);
try {
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var pixelData = imageData.data;
for (var i = 0; i < 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(imageData, 0, 0);
} 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 ", 10, 20);
context.fillText("the video to the canvas.", 10, 40);
context.fillText("Perhaps you are viewing this page from", 10, 70);
context.fillText("a file on your computer?", 10, 90);
context.fillText("Try viewing this page online instead.", 10, 130);
return false; } }
-
return false: This lets you check in the draw function whether an exception was
thrown. If it was, you want to stop calling drawOneFrame for each
video frame, so it exits the draw function.
function draw(video, context, canvas) {
if (video.paused || video.ended) return false;
drawOneFrame(video, context, canvas);
// Start over!
setTimeout(function(){ draw(video, context, canvas); }, 0); }
-
Canvas Accessibility Concerns:
The canvas doesn’t create a DOM node, is not a text-based
format, and is thus essentially invisible to tools such as screen
readers.
The text is essentially no more than a bunch of pixels and is
therefore inaccessible―it’s just like an image that contains
text.
-
Scalable Vector Graphics (SVG): a specific file format that allows you to describe vector graphics
using XML. preserve their quality even as you blow them up or shrink
them down.
Unlike canvas, images created with SVG are available via the DOM.
This enables technologies such as screen readers to see what’s
present in an SVG object through its DOM node, as well as allowing you
to inspect SVG using your browser’s developer tools. Since SVG
is an XML file format, it’s also more accessible to search
engines than canvas.
-
eXtensible Markup Language (XML): Like HTML, it’s a markup metalanguage. In plain English,
it’s a system meant to annotate text. Just as we can use HTML
tags to wrap our content and give it meaning, so can XML tags be used
to describe data, such as the content of a file.
Drawing in SVG
-
viewBox attribute: defines the starting location, width, and height of the SVG
image.
-
circle element: defines a circle, with cx and cy the X and Y coordinates of the
center of the circle. The radius is represented by r, while fill
defines the fill style. Code Example:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">
<circle cx="50" cy="50" r="25" fill="red"/>
</svg>
-
<desc> tag: lets you provide a description for the image you’re going to
draw.
-
<rect> tag: Populate it with attributes that describe the rectangle. This
includes the X and Y coordinate where the rectangle should be drawn,
the width and height of the rectangle, the fill, the stroke, and the
width of the stroke. Code Example:
<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>
-
Inkscape: an open-source tool that you can use to make SVG images. (for more
complex shapes, the code begins to look scary in the HTML file).
-
openclipart.org: A website where images that are free to use and free of copyright. The
images have been donated by their creators for use in the public
domain, even for commercial purposes, without the need for
permission.
-
SVG Filters: Open the file in Inkscape. Select the object and then click on the
Filters menu, click Color, click Greyscale.
If you test out The HTML5 Herald in an older version of IE or Safari
that our black-and-white spinner is still ... in color. That’s
because SVG filters are only supported in IE10 and later, and Safari 6
and later as well as all recent versions of Chrome, Firefox,
Opera,
iOS 6.1+, Android browser 4.4+.
-
modify the color of the original image: A safer approach would be to avoid using filters because of browser
support. To do this select Object > Fill and Stroke. The Fill and
Stroke menu will appear on the right-hand side of the screen. Click
the Edit button. We can then change the red, green, and blue values to
0 to make our image black and white. (!!!I CANNOT FIGURE OUT HOW TO
GET THIS TO WORK!!!) It is different than what it says &
shows.
-
Raphaël Library: an open-source JavaScript library that makes drawing and animating
with SVG much easier.
Much as with canvas, you can draw images into a container that you
create using Raphaël.
-
div element: use this as the container for the SVG elements that we’ll
create using Raphaël. Code Example:
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>
-
div styling: style this div to be placed in the center of the parent mapDiv
using the following CSS (note that without this, the element
won’t be centered). Code Example:
CSS CODE
.spin {
position: absolute;
top: 8px;
left: 55px;
}
-
Raphael() method: turns our HTML element into a Raphaël container. So this by
calling he Raphael method and passing in the element we’d like
to use along with a width and height.
-
Raphaël image() method: It is called on a Raphaël container object and takes the path
to the image, the starting coordinates where the image should be
drawn, and the width and height of the image. It draws the spinner SVG
image into the container. Code Example:
-
transform property: first create an object that specifies how many degrees of rotation
you want.
-
r: indicates the transform is a rotation.
-
Raphaël animate method: pass in the object and specify how long the animation should last
in milliseconds.
JavaScript CODE
function determineLocation() {
if (navigator.onLine) {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(displayOnMap);
var container = Raphael(document.getElementById("spinner"), 125, 125);
var spinner = container.image("images/spinnerBW.png",0,0,125,125);
var attrsToAnimate = { transform: "r720" };
spinner.animate(attrsToAnimate, 60000);
-
display property: indicates how it should be displayed.
-
none: hides it – stopping it from remaining after the map has
loaded.
function displayOnMap(position) {
document.getElementById("spinner").style.display = "none"; }
-
Canvas verses SVG: Canvas is much faster than SVG, so canvas is generally the better
choice if you’re looking to design a game requiring lots of
animations.
-
Canvas immediate mode: This means that if you ever want to add more to the canvas,
you’re unable to simply add to what’s already there. Every
time you finish drawing a shape, the canvas no longer has access to
that shape, because it won’t persist as an object that you can
modify. So, if you want to add to what you’ve already drawn on
the canvas, you must redraw the new shape from scratch. If you need to
paint pixels to the screen and have no concerns about the ability to
retrieve and modify your shapes, canvas is probably the better
choice.
-
SVG retained mode: the structure of the image is preserved in the XML document that
describes it, so is accessible via the DOM. However, you can’t
manipulate SVG images the way you can manipulate pixels on canvas. It
would have been impossible, for example, to use SVG to convert our
color video to black and white as we did with canvas. If you need to
be able to access and change specific aspects of your graphics, SVG
might be more appropriate.
-
Drag and Drop API: allows us to specify that certain elements are draggable, and then
specify what should happen when these draggable elements are dragged
over or dropped onto other elements on the page. supported in: All
recent versions of Chrome, Firefox, Safari and Opera 12+ and is
partially supported in Internet Explorer 7.0+ (IE10 doesn’t
allow setting the drag image, but supports all other features) The API
is unsupported by Android. It is also unsupported by design in iOS, as
Apple directs you to use the DOM Touch API instead. Further Info on
Drag & Drop API – Link1 Link2
-
File API: interface provides information about files and allows JavaScript in
a web page to access their content.
-
draggable attribute: Set on any HTML elements you’d like to be draggable.
Draggable is not a Boolean attribute, so you have to explicitly set it
to true. i.e.:
<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">
-
dragstart event: an event to add an event listener on for any draggable HTML
elements. Code Example:
var mouse = null;
for (var i=0; i < mice.length; i++) {
mouse = mice[i];
mouse.addEventListener('dragstart', function (event) {
// handle the dragstart event
}); }
-
DataTransfer objects: one type of object outlined in the Drag and Drop API. These
objects allow us to set and get data about the elements that are
being dragged.
Specifically, #1 the type of data we’re saving of the
draggable element #2 the value of the data itself.
Code Example:
mouse.addEventListener("dragstart", function (event) {
event.dataTransfer.setData("text/plain", this.id); });
-
id: used to bind event handlers to an element.
Code Example:
<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">
-
dragover event: fires when you drag an item over an element. Add an event listener
to any element you want to be able to drag over.
The default prohibits you from dropping an element.
-
preventDefault(): prevents the default behavior and ensures that the element can
actually be dragged over the desired element.
Code Example:
var cat = document.getElementById("cat");
cat.addEventListener("dragover", function(event) {
event.preventDefault(); });
-
drop events: fires when you drop an item on an element. Add an event listener to
any elements that you want to have accept dropped items.
The default prohibits you from dropping an element.
-
Object: the first step is to declare an object.
Code Example:
cat.addEventListener("drop", function(event) {
var mouseHash = {};
-
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 ...' }; })
-
h2 element: equate a variable to it. Code Example:.
var catHeading = document.getElementById('catHeading');
-
getData() method: retrieves the ID of the dragged element from the DataTransfer
object. Code Example:
var mouseID = event.originalEvent.dataTransfer.getData("text/plain");
-
use id’s: to change the text to the appropriate response in the
h2 element.
catHeading.innerHTML = mouseHash[mouseID];
-
DOM removeChild() method: remove it from the dropped item from the page.
var mousey = document.getElementById(item);
mousey.parentNode.removeChild(mousey);
-
preventDefault(): prevents the default behavior of not allowing elements to be
dropped on the element.
event.preventDefault();