HTML5
Lecture
Notes
Objective #1: Be familiar with the background of HTML5 and the fact that it is the combination of HTML, CSS, & JavaScript.
- Read the wikipedia entry on HTML5
- Review the tutorials and the API-like reference section at http://www.w3schools.com/html5. Also, use the "Try it yourself" online editors to practice many HTML5 techniques.
- HTML5 is really a combination of HTML (Hypertext Markup Language), CSS (Cascading Stylesheets), and JavaScript, which are all free. It is cross-platform which means that it works on various operating systems such as Windows, MacOS, Linux and even mobile operating systems like Android and iOS.
- HTML5 includes video and audio integrati so Flash browser plug-ins aren't required. It includes Video, Audio, Embed, Track, and Canvas elements that eliminate the need for Flash or Silverlight.
- HTML5 has built-in semantics that will allow search engines to analyze and organize web pages better.
- HTML5 includes WebSockets using PUSH technology so it is more synchronous than Ajax (Asynchronous Javascript and XMLHttpRequest) method of awkwardly updating web pages.
- HTML5 uses Web Storage to allow for session data to be stored while a user is browsing a website or, more permanently, with LocalStorage that can store key-value pairs to the client's hard drive permanently.
- HTML5 works with the Geolocation API to allow for GPS, IP addresses, Bluetooth, etc. connections to help identify the user's device.
- Best of all, when you use HTML5, your code will work in many different contexts such as the Web and smartphones, without having to rewrite or tweek it
- Here's an article summarizing the benefits of HTML 5 and that contains helpful links: http://www.pcworld.com/businesscenter/article/257556/8_reasons_to_gear_up_for_html5_now.html
- Mrs. Pirmann has a great HTML 5 reference site here - sites.google.com/site/html5forstudents
Objective #2: Create an empty web page.
- A web page is composed of HTML (hypertext markup language) tags such as <html></html> where text is placed inside an opening tag (e.g. <html>) and its matching closing tag that includes a forward slash (e.g. </html>). For example, the word Wyomissing would appear as bold in a web page when it is typed like this <strong>Wyomissing</strong> since the <strong> tag is used to make text bold on a web page.
- A basic web page includes <html> </html> tags along with <head></head> and <body></body> sections. The <head> section always appears before the <body> section.
- A title can be specified to show up in the browser's title bar by typing text between <title></title> tags in the <head> section.
Objective #3: Add a section for JavaScript code.
- JavaScript is a scripting language (as opposed to a full-blown programming language like Java, Visual Basic, or C++) that is used to make HTML web pages interactive. The syntax of JavaScript is similar to that of Java but not exactly the same.
- JavaScript code should be placed inside of <script type="text/javascript"></script> tags that are nested in the <head></head> section.
- Variables are declared and functions are typed out and implemented in the <script> section of the web page. The functions can be typed in any order. Variables are often declared at the top of the <script> section.
Objective #4: Use JavaScript variables and functions.
- Use the keyword var to declare variables and optionally initialize them to certain values. Variables are not typed in JavaScript which means that you do not specify a datatype for each variable like you do in Visual Basic or Java.
- Examples:
var score;
var playerLeft = 0;
var name = "";
var golfScores = [73, 80, 92]; // one-dimensional array
var ticTacToeBoard = [["", "", ""],["", "", ""],["", "", ""]]; // two dimensional-array with 3 rows and 3 columns of empty strings
- Functions (aka methods) can be used in JavaScript. The keyword function must be typed, followed by the function's name and a set of parentheses with optional parameters and a set of curly braces wrapped around the body statements. Here is an example of a function named init
function init()
{
drawMaze();
window.addEventListener('keydown', getkeyAndMove, false); // getkeyAndMove is function below
}
Objective #5: Use an init method to set up your web page.
- Though it is optional, you should place code that you want to initialize the web page in a method that is named something like init. Here is an example
function init()
{
drawMaze();
window.addEventListener('keydown', getkeyAndMove, false); // getkeyAndMove is function below
}
Here is another example of a function that draws an X on a tic tac toe board where the top, left corner of the X has the (x, y) position that is specified by the parameters left and top
function drawX(left, top)
{
context.moveTo(left, top);
context.lineTo(left + 100, top + 100); // downward sloping part of X
context.moveTo(left + 100, top);
context.lineTo(left, top + 100); // upward sloping part of X
context.stroke(); // draw specified lines
}
- You can call this method by calling it in the HTML <body> tag like this
<body onLoad="init();">
This will cause the function init to be executed as soon as the web page loads.
- The other option is to place code into the window's onload method such as
window.onload = function()
{
drawMaze();
window.addEventListener('keydown', getkeyAndMove, false); // getkeyAndMove is function below
}
Objective #6: Use the canvas and context elements to draw and manipulate objects.
- The canvas is an HTML element (like an object) that defines a rectangular area on the web page where you can draw graphics and place graphic files.
- You should use the <canvas> tag to create a canvas in your web page like this:
<canvas id="myCanvas" width="300" height="400">Your browser doesn't support the HTML5 element canvas.</canvas>
The canvas should be given an id which is essentially a name. You can set its width and height in pixels. The text "Your browser doesn't support the HTML5 element canvas" will appear to user's who are using an old-fashioned web browser such as Internet Explorer version 8 or earlier that doesn't support HTML5.
- There a many JavaScript methods such as lineTo, moveTo, fillRect, etc. that can be used to draw shapes and graphics on a canvas. However, you often need to get a context object from the canvas element in order to use those methods. For many interesting methods that draw shapes and symbols, you need to use a context object that is derived from the web page's canvas element.
In your JavaScript code (i.e. the <script> section of your web page), you would type
var canvas = document.getElementById("myCanvas");
to get the canvas from the HTML document. The HTML canvas id might by "myCanvas" while you purposefully name that canvas variable in your JavaScript code as canvas so that you don't confuse the two even though they are really the same thing but just two different identifiers.
To obtain the context object from the canvas, you would type
var context = canvas.getContext("2d");
However, you can usually combine the two statements
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
into one statement
var context = document.getElementById("myCanvas").getContext("2d");
in most situations where you only need the context object and you don't need the canvas object later in your code.
- There are many interesting methods that can be used with a context object. Many are similar to methods with the same name in Visual Basic and Java. Learn how to use them at w3schools.com or many other online HTML5 resources and tutorials.
- moveTo
- lineTo
- fillRect
- strokeRect
- stroke
- arc
- clearRect
- fillStyle
- font
- fillText
Objective #7: Use listeners to add interaction to a web page.
- You can allow a user to click the canvas to make a web page interactive. First, you must add a listener that detects the mouse clicks. This is usually done with a line of code in an init or load method. Example:
canvas.addEventListener("mouseup", getMouseClick, false); // listen for mouseclicks
any time the mouse button is let up by the user, a function named getMouseClick is being called. The programmer can use any function name in place of getMouseClick.
The function getMouseClick would look something like this:
function getMouseClick(event)
{
var x = clientX;
var y = clientY;
// something would be done here with the x, y coordinates
}
Notice that an event object is being passed to this function.
- You can allow the user to press keys to make a web page interactive. First, you must add a listener that detects key presses on the canvas. This is usually done with a line of code in an init or load method such as
window.addEventListener('keydown', getKey, false);
Any time a key is pressed down, a function named getKey is being called. The programmer can create and use any function name in place of getKey
The function getKey would look something like this:
function getKey(event)
{
var keyCode; // user's keypress
if(event == null) // protect against exception errors
{
keyCode = window.event.keyCode;
window.event.preventDefault();
}
else
{
keyCode = event.keyCode;
event.preventDefault();
}
if (keyCode == 37) // left arrow
{
playerLeft -= 10; // move player left
}
else if (keyCode == 39) // right arrow
{
playerLeft += 10; // move player right
}
else // ignore other keys
{
window.removeEventListener('keydown', getkeyAndMove, false);
}
Notice how the method removeEventListener is being used to ignore other keypresses. Also note that press of the key generates and passes an event parameter to the function. The event object is accessed by using the built-in window object.
Objective #8: Use timers to add interaction to a web page.
- You can use the setInterval function to specify that a given function be executed over and over again on a periodic interval. The statement below will cause the drawScreen function to execute every 1 second:
setInterval(drawScreen, 1000);
The second parameter determines the number of milliseconds between each time that the function with the drawScreen is executed.
- To stop a function from executing after it had been started with a setInterval call, you can use the clearInterval method. For example, if you are animating a bullet across the screen with a function named moveBullet then the following line of code would start the animation and cause the bullet to move 10 pixels up the screen every 100 milliseconds
moveBulletHandle = setInterval(moveBullet, 100);
.......
function moveBullet()
{
bulletY -= 10; // move bullet 10 pixels upwards
}
then you would stop it with the statement
clearInterval(moveBulletHandle);
In this example, moveBulletHandle is a variable name (aka "handle") that is being used to keep track of the timer that is set up behind the scenes. To stop this timer you must pass that handle name to the clearInterval function.
Objective #9: Miscellaneous topics.
- To compare strings and words in JavaScript you can use the == rather than the equals method.
- Pseudo-random numbers can be generated using the JavaScript Math.random method.
- To add a comment to the HTML code area of a web page you type <!-- followed by -->
For example, <!-- web page written by Mr. Minich -->
- Images can be used in a JavaScript code. By creating an Image object and storing a valid graphic filename (gif, jpg, or png) in its src property. You can display that graphic using the drawImage function as in
var image = new Image();
image.src = "pacman.png"; // file must be saved to same folder as web page
context.drawImage(image, playerLeft, playerTop, 100, 10);
The top, left corner of the graphic will be displayed on the canvas at the (x, y) location of (playerLeft, playerTop) and have a width of 100 pixels and a height of 10 pixels.
- A button can be used in the <body> section of a web page using <button> tags. Example:
<button onClick="init(); return true;">Game Reset</button>
In this example, the button has the caption "Game Reset" and when it is clicked the init function is executed from <script> area of the web page. The true value is returned to the web page so that it knows the button was successfully clicked.