HTML5 Tutorial

You probably have heard of HTML5 by now, I guess the most popular new stuff would be playing video without Adobe Flash, HTML5 evangelist should thank Mr.Steve Jobs for turning it into a technology celebrity.

Besides, you might have heard of creating animation and playing music without plug-in, rich input control such as date picker, color picker, slider without javascript, and lastly offline data storage.

Anyway, this is just part of HTML5. You may want to check it out yourself from time to time - HTML5 (including next generation additions still in development). http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#audio

When?

W3C has announced in February 2011 that July 2014 will be date that HTML5 become the official recommendation of web standard!

Forget about When

As the matter of fact, the proposed timeline of WHATWG doesn't really matter. The development of the web rest in the hands of two groups of people.

First group of people are those dominant web browser companies like Mozilla, Microsoft, Apple, Google and Opera. The second group of people are the web designers or web developers in this planet. The failure of XHTML 1.1 and XHTML 2 is simply, web browser companies thought that was a stupid idea and they just shut their door.

Today, most of the major web browsers are aggressively wanting to support HTML5. Even Microsoft Internet Explorer, which has the reputation of slow in adopting new standard is supporting HTML5 in its IE9. That means, HTML5 is going to be real and big.

As of writing, Microsoft has announced that they have no plan to release IE9 for Windows XP users. If you would like to give IE9 a try, you will have to use Windows Vista SP2 or Windows 7.

There are no reason for web designers not to embrace HTML5 since it makes our life easier than ever.
Document Type Declaration in HTML5 is cool and simple. It is as simple as below:-

<!DOCTYPE html>
Unlike of different variant HTML4 or XHTML1 doctype that we are familiar with:-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Some of them can't even be fitted in one line. This is the first proof that web designer life will be easier with HTML5. A very simple HTML5 web page can be as simple as below.

<!DOCTYPE  html>
<html>
<head>    <title>HTML5 is rocks!</title> </head> <body>    <h1>HTML5 Rocks!</h1> </body> </html>

HTML Header stuff

Very often in the header of our web pages, we specify the Content Type, Javascript and CSS file path, again, life is easier with HTML5.

Instead of

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
In HTML5, it can be just :-
<meta charset="UTF-8">
It used to be :-
<script type="text/javascript" src="jquery.js"></script>
In HTML5, redundant information "type=text/javascript" is no longer necessary, practically, this is the only client side script alive.
<script src="jquery.js"></script>
Similarly, CSS receives the first class citizen treatment as javascript too. You can forget about "type=text/css" from now on.
<link rel="stylesheet" href="html-my.css">
If this is the way your <html> root looks like
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
You can now simplify with simply as below : -
<html lang="en"">

Audio

Let's have something fun to start with. We are now talking about web browser supporting audio file in native, just like how <img> tag is supported since 1994. HTML5 is likely to put an end to audio plug-in such as Microsoft Windows Media player, Microsoft Silverlight, Apple QuickTime and the infamous Adobe Flash.

If you don't see a audio player control in the dotted box above, your web browser probably don't support the audio tag.

Above is a gallery of audio players by major web browsers. As you can see the size of the player control varies from one to another, IE9 player is exceptionally large in compared to Safari player. This can be a disaster to a web designer.
If you are using Safari for Windows but without QuickTime, your Safari is not going to support media tag (both <audio> and <video>) in "native". I suppose Safari is relying on QuickTime codec to play media file in the browser.

How to?

In order to make your web page plays music, the html code can be as simple as
<audio src="vincent.mp3" controls></audio>

Unfortunately, the most popular audio format MPEG3(.mp3) is not an Open standard, it is patent encumbered. That means, web browser needs to pay a sum of money in order to decode it, and that might not be financially feasible for smaller company or organization. As you can see from table below, only those big boys are rich enough to decode MP3. Firefox and Opera supports only Vorbis (.ogg) format which is an Open standard.

On the other hand, the open standard Vorbis (*.ogg) is not supported by Safari and IE9. Hence, it is always good to have both Mp3 and Ogg side to side available.

Browser

.mp3

.wav

.ogg

Mozzila Firefox 3.6

 

Opera 10.63

 

Google Chrome 8.0

Apple Safari 5.0.3 (with QuickTime)

 

Microsoft IE 9 Beta

 

Test how far your browser support audio tag using "HTML5 <audio> and Audio() Support Tester".
What you can do is ...

  <audio  controls>
    <source src="vincent.mp3"  type="audio/mpeg"/>
    <source src="vincent.ogg"  type="audio/ogg"/>
  </audio> 

Whether or not to provide the MIME type (type="audio/mpeg") to browser is optional. Most modern web browsers are smart enough to determine the content type by itself. However, it is always good to be helpful to web browser, that makes your web browser works faster and happier.

 

Attributes of <audio>

Attribute

Value

Description

controls

*Boolean attribute

You need this to make the native audio player appear. Otherwise, you would have to use DOM to control the audio element to play your music.

autoplay

*Boolean attribute

If this guy exists, the browser will just play your song or your speech without asking permission from your visitor.

loop

*Boolean attribute

Keep repeating your music

src

url

The URL of your audio file

preload

none | metadata | auto

This attribute was formerly known as "autobuffer" and it was an boolean attribute as "controls".

none - do not buffer audio file automatically.
metadata - only buffer the metadata of audio file.
auto - buffer audio file before it gets played.

















*Boolean attribute is an attribute that either present in the tag or not present. A Boolean attribute has just its name and no value. You can put it this way too, whatever value you assign to a boolean attribute means only one thing - TRUE.

<audio src="vincent.mp3" controls="true" loop="true" autoplay="true"></audio>
(This is completely unneccessary!)
<audio src="vincent.mp3" controls loop autoplay></audio>
(This is it!)

How should we cater for less modern web browser?

HTML5 is a evolution of the web, not a revolution that will totally destroy the past. Hence, let's move forward a little bit gracefully.

In order to support web browser that doesn't understand what <audio> is about, such as IE8 and below, we shall let them enjoy their good old day using <object> tag.

  <audio  controls>
    <source src="vincent.mp3"  type="audio/mpeg"/>
    <source src="vincent.ogg"  type="audio/ogg"/>
    <object  type="application/x-shockwave-flash"  
data="media/OriginalMusicPlayer.swf" width="225" height="86">    <param name="movie" value="media/OriginalMusicPlayer.swf"/>    <param name="FlashVars" value="mediaPath=vincent.mp3" />   </object> </audio>

In my example above, I am using a flash mp3 player from PremiumBeat.com
If your browser doesn't suppport HTML5 but you have got flash plug-in, you probably don't want to miss the fun. Here you go ...

If the web browser support neither HTML5 nor Flash, you might as well let the user download the audio file and wish them luck on getting a player to play it.

<audio  controls>
  <source src="vincent.mp3"  type="audio/mpeg"/>
  <source src="vincent.ogg"  type="audio/ogg"/>
  <object  type="application/x-shockwave-flash"  
data="media/OriginalMusicPlayer.swf" width="225" height="86">
   <param name="movie" value="media/OriginalMusicPlayer.swf"/>    <param name="FlashVars" value="mediaPath=vincent.mp3" />   </object>
  <a href="vincent.mp3">Download this lovely song and wish you all the best!</a> </audio>

Instead of using the standard web browser audio player, you can write your own control, use your creativity and imagination, the sky is the limit.

<audio  id="player" src="vincent.mp3"></audio>
<div> 
<button  onclick="document.getElementById('player').play()">Play</button> 
<button  onclick="document.getElementById('player').pause()">Pause</button> 
<button  onclick="document.getElementById('player').volume += 0.1">Vol+  </button> 
<button  onclick="document.getElementById('player').volume -= 0.1">Vol-  </button> 
</div>

Video

Video streaming over the internet is nothing new, the attempt in doing so can be dated back to the mid of 20th century. Due to the limited network bandwidth and lower CPU power, nothing was quite successful until Youtube made its debut on 2005.

With HTML5, we can now "embed" video as a native element as <img>. It works almost the same as <audio> besides it has three attributes that only applicable to <video>. There are "width", "height" and "poster"."width" and "height" determine the screen size and "poster" is just a still image file projected on screen before the movie gets played.

How to?
The code to stream video from your web page can be as simple as the line below.
<video src="rain.mp4" controls width="480" height="360"></video>

In reality, life isn't as how we thought it should be. The simple line of code above works only in Google Chrome, Apple Safari, and yet for Apple Safari to play the video, you have got to make sure QuickTime is installed in your computer.
Similarly to the plight of audio, we don't have an universal video format that all web browsers are supporting. At least at the time of writing (13 December 2010).

Again, it is money games at the end of the day. H.264 is patent-encumbered, Firefox and Opera chose to embrace a royalty free codec which is Theora and WebM (VP8 codec)

In short, the simple single line code as I demonstrated above isn't practical. You've got to provide at least two sources (recommended is three) for one video.
<video controls width="480" height="288" >
  <source src="media/html5iscool.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
  <source src="media/html5iscool.ogv" type='video/ogg; codecs="theora, vorbis"' />
  <source src="media/html5iscool.webm" type='video/webm; codecs="vp8, vorbis"'/>
</video>

Attributes of <video>

Attribute

Value

Description

controls

*Boolean attribute

If you want the browser native player control to be around, specifiy "controls"

autoplay

*Boolean attribute

If this guy exists, the browser will just play your video without asking permission from visitor

loop

*Boolean attribute

Keep repeating your video

src

url

The URL of your video file

preload

none | metadata | auto

This attribute was formerly known as "autobuffer" and it was an boolean attribute as "controls".

none - do not buffer video file automatically.
metadata - only buffer the metadata of video
auto - buffer video file before it gets played.

width

width in pixels

Width of video player

height

height in pixels

Height of video player

poster

url of a image file

If present, shows the poster image until the first frame of video has downloaded.

What about browsers that are HTML5 illiterate?
If you think encoding one video for three times is painful, hold your breath for a little longer, you are going to take more pain in order to accomodate more visitors who are using an less modern web browser. i.e. Internet Explorer 8 and below.
Microsoft has released its Internet Explorer 9 Beta on Nov 2010 which supporting HTML5, but <video> tag is yet supported as of writing. Hence, you will have to take step further to embed a flash player in <object> since most user has flash plugin installed. I believe Microsoft will eventually support <video>, even so, its always taking time for majority of the user to migrate to the latest version of web browser.

  <video  controls width="320" height="240">
  <source  src="media/html5iscool.mp4" type='video/mp4;  codecs="avc1.42E01E, mp4a.40.2"' />
  <source  src="media/html5iscool.ogv" type='video/ogg; codecs="theora,  vorbis"' />
  <source  src="media/html5iscool.webm" type='video/webm; codecs="vp8,  vorbis"'/>
  <object  width="320" height="240"  type="application/x-shockwave-flash"  
data="media/flowplayer-3.2.5.swf">    <param name="movie" value="media/flowplayer-3.2.5.swf" />    <param name="allowfullscreen" value="false" />    <param name="flashvars" value='config={"clip": {"url": "html5iscool.mp4", "autoPlay":false, "autoBuffering":true}}' /> </object> </video>

Canvas

One of the hottest subjects in HTML5 is Canvas, but what exactly a Canvas is?

“Canvas is an extremely heavy-duty plain-woven fabric used for making sails, tents, marquees, backpacks, and other items for which sturdiness is required. It is also popularly used by artists as a painting surface, typically stretched across a wooden frame.”

Perhaps that is not the answer that you are seeking. In fact, the HTML5 Canvas is mimicking the physical canvas that is used by artist.

A canvas is just blank space with no color (not even white), and javascript being the pencil and paint brush that going to turn a blank sheet into a piece of art.

Of course, the existence of canvas does not meant for just still image. Still image can be easily handled by decade-old "img" element. With the infamous javascript as your paint brush, you can create very promising animation or even interative games (here is a HTML5 Canvas showcase Pirates love Daisies)

If you have created some great flash animation before and you hope to create a HTML5 version, there are tools out there which can help you to accomplish that.

One of them are Flash to HTML5.

HTML5 Canvas is a very big subject, it is big enough for you write a book with. It is not my intention to cover every single detail of Canvas in this tutorial. This is just a brief introduction of Canvas. Remember,it is just the begining.

To create a canvas, the HTML code is simply
<canvas width="200" height="200"></canvas>

However, a borderless canvas is very much an invisible object. It takes up space but you don't see it. Let's add a border style and use a ID for reference. The purpose of ID is to make it accessible using DOM (Document Object Model). Without reference of ID, javascript (in this case like your paint brush) will have no idea which canvas to paint.

<canvas id="Canvas1" width="200" height="200" style="border:solid 1px #000000"></canvas>

If you see a skull with cross bones above instead of just a solid line square box, it means your web browser doesn't support Canvas. You may want to download a web browsers that work with Canvas as shown below.

Browsers

Basic Canvas Support

IE 7

(requires ExplorerCanvas)

IE 9 Beta

Firefox 3.0

Safari 3.0

Chrome 3.0

Opera 10

How to draw Rectangle?
Before dreaming about creating an interactive HTML5 games, let's start with the basic.
First, click the "Red Square" button, if you don't see a red square in the canvas, you problably want to get the right web browser to continue.

<canvas  id="c1" width="200" height="200"  style="border:solid 1px #000000;"></canvas>
<button onclick="draw_square();return true;">Red Square</button> <script>
function draw_square() {    var c1 = document.getElementById("c1");    var c1_context = c1.getContext("2d");    c1_context.fillStyle = "#f00";    c1_context.fillRect(50, 50, 100, 100); } </script>

To draw anything in canvas, you do not put anything between the opening tag and closing tag of <canvas>, browsers that supports Canvas will just ignore it. You can only use Javascript to do your drawing.

Rule number one, your canvas element has got to have an ID, so we can use Javascript to locate it. Secondly, every canvas has what we call "Context". In fact, context of canvas is what we are going to paint on, not canvas itself.

   var c1 = document.getElementById("c1");
   var c1_context = c1.getContext("2d");
Let's choose use the red paint (fillStyle="#f00";) and paint a red square with 100px width and height. (fillRect(50, 50, 100, 100)).
   c1_context.fillStyle = "#f00";
   c1_context.fillRect(50, 50, 100, 100);
The table below shows the methods of drawing rectangle.

 

 


Methods of "Context"

Descriptions

fillStyle

CSS Color, pattern or gradient within the shape. Default fillStyle is solid black color.

strokeStyle

Color or CSS style of the lines of the shape

fillRect(x, y, width, height)

Draw a rectangle start from coordinate x and y and size of width x height.

strokeRect(x, y, width, height)

Draw a rectangle with just its edges.

clearRect(x, y, width, height)

Clear the area specified in x, y coordinate and area of width x height

<div  ><canvas id="Canvas2" width="200" height =  "200" style="border:solid 1px #000000;"></canvas>
   <div>      <button onclick="blue_square_2();return true;">Blue Square</button>      <button onclick="red_stroke_2();return true;">Red Square</button>      <button onclick="clear_rect_2();return true;">Erase Everything</button>    </div> </div> <script>    var c2 = document.getElementById("c2");    var c2_context = c2.getContext("2d");    function blue_square_2() { //Blue color square      c2_context.fillStyle = "#00f";      c2_context.fillRect(50, 50, 100, 100);    }
   function red_stroke_2() { //Red color edges      c2_context.strokeStyle = "#f00";      c2_context.strokeRect(45, 45, 110, 110);    }
   function clear_rect_2() { //Clear all      c2_context.clearRect(40, 40, 120, 120);    } </script>

How to cast a shadow
Since you now know how to draw a rectangle, you probably want to make it more sytlish by casting a shadow. Well, it can be pretty simple. You just need to add a few more lines into your code. Let's first look at the properties that will be involved in casting a shadow.

 



Context properties

Descriptions

shadowOffsetX

Horizontal distance (x-axis) between the shadow and the shape in pixel.

shadowOffsetY

Vertical distance (y-axis) between the shadow and the shape in pixel.

shadowBlur

How blur you want your shadow to be.

shadowColor

Obviously, this is to set the color of your shadow

Here you go

<div><canvas  id="c8" width="200" height = "200"  
style="border:solid 1px #000000;"></canvas></div>
<script> var c8 = document.getElementById("c8"); var c8_context = c8.getContext("2d");
function draw_rectangle() { c8_context.shadowOffsetX = 5; c8_context.shadowOffsetY = 5; c8_context.shadowBlur = 10; c8_context.shadowColor = "DarkGoldenRod"; c8_context.fillStyle = "Gold"; c8_context.fillRect(20, 20, 100, 120); }
window.onload = draw_rectangle(); </script>

 

As you can see in the code above, in order to draw a shape with shadow,
you need to first specify the shadow properties before "drawing" the shape.

How to draw paths?
Let's first draw one line
Here you go, the script that drew the brown line above.
<div><canvas id="Canvas2" width="600" height = "200"
style="border:solid 1px #000000;"></canvas>
   <div>      <button onclick="Vertical_line();return true;">
Click me to draw a brown vertical line</button>
   </div> </div> <script>    var c3 = document.getElementById("c3");    var c3_context = c3.getContext("2d");
   function Vertical_line() {      c3_context.moveTo(300, 10);      c3_context.lineTo(300, 190);      c3_context.strokeStyle = "brown";      c3_context.stroke();    }
</script>
The methods that really matters are "moveTo", "lineTo" ,"stroke" and "strokeStyle".

Context method

Descriptions

moveTo(x,y)

move to starting point with coordinate x and y.

lineTo(x,y)

Draw a line to this point from starting point. Again x and y being the coordinate.

strokeStyle

CSS color of the line

stroke

A method to actually make javascript draw a line

beginPath

Before you start drawing a new line with different color, you will have to call "beginPath".

Check out the demo below, "beginPath" method is playing an important role. Without it, the last "stroke" will redraw the previous line with the last-called "strokeStyle" color.

<div>
  <canvas id="c4" width="600" height =  "200" style="border:solid 1px #000000;"></canvas>
<div>
  <button onclick="Vertical_2px_Red();return true;">Vertical 2px Red line</button>
  <button onclick="Vertical_1px_Blue();return true;">Vertical 1px Blue line</button>
  <button onclick="Horizontal_2px_Green();return true;">Horizontal 2px Green line</button>   <button onclick="Clear_line();return true;">Erase Everything</button>
</div>
</div>

<script> var c4 = document.getElementById("c4");
var c4_context = c4.getContext("2d");
function Vertical_2px_Red() { c4_context.beginPath(); c4_context.moveTo(300, 10); c4_context.lineTo(300, 190); c4_context.strokeStyle = "Red"; c4_context.stroke(); }

function Vertical_1px_Blue() {
c4_context.beginPath(); c4_context.moveTo(350.5, 10); c4_context.lineTo(350.5, 190); c4_context.strokeStyle = "Blue"; c4_context.stroke(); }
function Horizontal_2px_Green() { c4_context.beginPath(); c4_context.moveTo(100, 100); c4_context.lineTo(500, 100); c4_context.strokeStyle = "Green"; c4_context.stroke(); }
function Clear_line() { c4_context.clearRect(1, 1, 600, 190); }
</script>

You may notice in the demo above, there are two buttons to help you draw a vertical line, however, one draws a one pixel line and the other draws a two pixels line. What makes the difference as follows:-

c4_context.moveTo(300, 10);c4_context.lineTo(300, 190);
and
c4_context.moveTo(300.5, 10);c4_context.lineTo(300.5, 190);

In order to draw a line with 1 pixel wide, you simply have to shift the coordinate to 0.5 pixel to the left or right (up or down). This is because integer value of the coordinate is to be considered at the edge of each pixel. Drawing a line at the edge will simply make the line spread across two adjacent pixels. By shifting the coordinate 0.5 pixel, the line will still spread between two pixels but occupy half of each pixel.

Place images in Canvas
Drawing lines or simple shape is boring, let's draw some pictures!

In above demo, I use only one context method, "drawImage()". However, "drawImage" method can have 3,5 or 9 arguments. I have three functions which are "draw_dragon()", "draw_smaller_dragon()" and "draw_dragon_head()", each of them implements 3,5 and 9 arguments respectively.

Overloading of drawImage()

Description

3 arguments
drawImage (img,x,y)

img is the image element.
x and y being the coordinate to place the image object.

5 arguments
drawImage (img,x,y,width,height)

img is the image element.
x and y being the coordinate to place the image object. width and height will be image size that you want, resize as you want.

9 arguments
drawImage (img, crop_x, crop_y, crop_width, crop_height, x, y, width, height)

img is the image element.
crop_x and crop_y is where you start cropping your image.
crop_width and crop_height is the size you want to crop your image.
x and y still being the coordinate to place the image object.
width and height will be image size that you want, resize as you like it.

Here is the code of of the dragon demo.

  <div"><canvas  id="c5" width="600" height = "300"  style="border:solid 1px #000000;"></canvas>
  <div>
  <button  onclick="draw_dragon();return true;">Draw Dragon</button>
<button onclick="draw_smaller_dragon();return true;">Draw smaller dragon</button>
<button onclick="draw_dragon_head();return true;">Draw Dragon Head</button>
<button onclick="Clear_image();return true;">Erase Everything</button>
</div>
</div>
<script>
var c5 = document.getElementById("c5");
var c5_context = c5.getContext("2d");
var dragon = new Image();
dragon.src = 'images/chinese_dragon.png';
function draw_dragon() {
c5_context.drawImage(dragon, 100, 5);
}

function draw_smaller_dragon() {
c5_context.drawImage(dragon, 10, 5, 58, 100);
}
function draw_dragon_head() {
c5_context.drawImage(dragon, 0, 19, 69, 97, 300, 100, 103, 145);
}
function Clear_image() {
c5_context.clearRect(1, 1, 600, 300);
}
</script>

How to display text in canvas

The magic words for printing text in canvas are "fillStyle","strokeStyle", "font","textBaseline" and lastly "fillText" and "strokeText".

<div><canvas  id="c6" width="600" height = "200"  style="border:solid 1px #000000;"></canvas>
<div>
<button  onclick="showFillText();return true;">Fill Text</button>
<button onclick="showStrokeText();return true;">Stroke Text</button>
<button onclick="Clear_text();return true;">Erase Everything</button>
</div>
</div>
<script>
var c6 = document.getElementById("c6");
var c6_context = c6.getContext("2d");
function showFillText() {
c6_context.fillStyle = '#f00';
c6_context.font = 'italic bold 30px sans-serif';
c6_context.textBaseline = 'bottom';
c6_context.fillText('HTML5 is cool!', 50, 100);
}
function showStrokeText() {
c6_context.strokeStyle = "#003300";
c6_context.font = '40px san-serif';
c6_context.textBaseline = 'bottom';
c6_context.strokeText('HTML5 is cool?', 300, 100);
}
function Clear_text() {
c6_context.clearRect(1, 1, 600, 300);
}
</script>
Context method

Description

fillText(text,x,y)

Print the text with solid color within. Text color is determined by fillStyle().

strokeText(text,x,y)

Print the text with only color the outline of the text. Text color is set by strokeStyle().

strokeStyle

CSS color for text that call strokeText

fillStyle

CSS color for text that call fillText

font

CSS font style such as "bold, 10px, san-serif"

textBaseline

This is a little bit tricky to explain. We will need another demo. The value for this propery can be "top", "hanging", "middle", "alphabetic", "ideographic" and "bottom". Default value is "alphabetic".

Below is a picture that I borrowed from WHATWG (http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#2dcontext) which is a perfect illustration for all kinds of text baselines. What you should observe is how a text is being placed in relation to those baselines.

Here I have drawn a gray line at y = 100 and I am going to place each word at y = 100 but using different "textBaseline".

c7_context.textBaseline = "top";
c7_context.fillText('Top', 5, 100);

c7_context.textBaseline = "bottom";
c7_context.fillText('Bottom', 80, 100);

c7_context.textBaseline = "middle";
c7_context.fillText('Middle', 200, 100);

c7_context.textBaseline = "alphabetic";
c7_context.fillText('Alphabetic', 300, 100);

c7_context.textBaseline = "hanging";
c7_context.fillText('Hanging', 400, 100);

If you are planning to roll out something in Canvas and you wish you could support users running on IE 8 or below, you can consider to use a free open source javascript library called ExplorerCanvas. Beware, work around is still a work around, there are some nonuniformity issues that might drive you mad.

Again, this is just a brief introduction on HTML5 Canvas, there are many more interesting features on HTML5 Canvas out there to be explored. Have fun!

Web form 2.0

The evolution of HTML5 is to make a better World Wide Web. Writing less code is good (especially javascript), at the end of the day, those repetitive works of web developers should be taken over by web browsers. After all, this is the main reason man invented machine.

What you can see below is a list of new input attributes and input types, we shall go through each and every one.
New Input attributes <input type="text" "new input attribute"/>

  • Placeholder
  • Autofocus
  • Required
  • DataList

For years, We are only given a handful of "Type"s to be used in Input element, such as "text", "radio", "checkbox", "password", "file" and "submit", In HTML5, we will be having more fun with the new kids on the block.
New input types <input type="new input type"/>

  • Search
  • Email, URL and Phone
  • Range as Slider
  • Number as Spinner
  • Date and Times
  • Color picker

Input Attr : Placeholder

A placeholder is a textbox that hold a text in lighter shade when there is no value and not focused.
Below is how a placeholder should look like if no value is entered and textbox is not focus. (What you see is just picture, not real placeholder, don't try to click it)



..and, here is the code. Javascript and CSS is no longer needed to handle the appearance of the text.
<label for="first_name">First Name</label> : <input id="first_name" placeholder="First name goes here">
Let's see what which browsers support placeholder.

Browsers

Placeholder Support

IE 10

Firefox 3.7

Safari 4.0

Chrome 4.0

Opera 11

If placeholder is just a nice-to-have feature in your web page, you probably will not bother about supporting browsers other than above.

Otherwise, you would have to go extra mile. First, use Javascript to check if the browser support Placeholder, for browsers that does not support Placeholder, use Javascript + CSS to create a Placeholder on your own.
<label for="demo">Placeholder demo</label> : <input id ="demo" placeholder="Support Placeholder" />

  <script>
  function testAttribute(element, attribute)
{
  var test = document.createElement(element);
  if (attribute in test)
    return true;
  else
    return false;
}
if (!testAttribute("input", "placeholder"))
{
  window.onload = function()
  {
    var demo = document.getElementById("demo");
    var text_content = "No Placeholder support";
    demo.style.color = "gray";
    demo.value = text_content;
demo.onfocus = function() {
    if (this.style.color == "gray")
    { this.value = ""; this.style.color = "black" }
    }
    demo.onblur = function() {
    if (this.value == "")
    { this.style.color = "gray"; this.value = text_content; }
    }
  }
}
</script>

"testAttribute" function above is to test if an attribute of an element is supported by a web browser. In this case, we want to know if your web browser supports "Placeholder" attribute of "Input" element.

If "Placeholder is not supported, I make the browser to run some Javascript code to do create something as a Placeholder, you can use your own Javascript instead of mine, (my code is created for showcase and might not be suitable for production)

If you are using a web browser that supports "Placeholder", you should be able to see "Support Placeholder" in the textbox. Conversely, you will see "No Placeholder Support" if you are using web browser such as Internet Explorer 8.

Input Attr : Autofocus

Autofocus is an boolean attribute of form field that make browser set focus on it when a page is loaded. If you still don't understand what that is, please go to Google and you notice you just type your search string without first click on the big textbox.

This is because Google has set focus to that textbox automatically (I am not saying Google uses HTML5 "autofocus") and save you ONE mouse click.

below is the code to do it, piece of cake.
<label for="name">Your name goes here :</label><input id ="name" type="text" autofocus/> <br />
<label for="mothername">Your dog's name goes here :</label><input id ="mothername" type="text" />
"autofocus" is a boolean attribute, it is needless to set any value to it.
As usual, not every web browser supports "autofocus"

Browsers

Autofocus Support

IE 10

Firefox 4

Safari 4.0

Chrome 3.0

Opera 10

To implement a little bit more foolproof "autofocus", you will have to again use Javascript to check if a web browser supports "autofocus", if not, just set focus with Javascript.

Below is actually a demo as well as a test. If your web browser support Autofocus, you will notice the cursor is blinking in the first textbox, if your web browser does not support it, it will be set focus at the second input textbox.

Support Autofocus :
No Autofocus Support :

<script>
function testAttribute(element, attribute) {
   var test = document.createElement(element);
   if (attribute in test) {
    return true;
  }
else
  return false;
}

window.onload = function() {
  if (!testAttribute('input', 'autofocus'))
  document.getElementById('Text2').focus();
//for browser has no autofocus support, set focus to Text2.
}
</script>
<label for="Text1">Support Autofocus :</label><input id ="Text1" type="text" autofocus/> <br />
<label for="Text2">No Autofocus Support :</label><input id ="Text2" type="text" />

Input Attr : Required field

A "Required Field" is a field that must be filled in with value before submission of a form. Required field sometimes known as Mandatory field or Compulsory field.

As of writing, only Opera and Firefox support "Required" attribute of input textbox. Please see table below.

Browsers

"Required" Support

IE 10

Firefox 4

Safari 5

 

Chrome 20

Opera 9

To make a field as required field is fairly simple, you are only required to add a "required" boolean attribute into your input element.

  <form>
  <label  for="movie">What is your favorite movie : </label>
<input name="movie" type="text" required />
<input type="submit" value="Submit"/>
</form>

The picture below shows us how Firefox and Opera prompt user to fill in value if a "Required field" is left blank upon submission.

Input Attr : DataList

Datalist is seem like type-ahead auto suggest textbox as you can see in Google search box. Of course, it is only "seem-like" but not even close to it.

Datalist is like a "Select" dropdown list but user can freely input anything in the textbox other than what are listed in dropdown. As with <SELECT> dropdown everything is in client side.

Before we get into the code and demo, let's first check out which browser that is currently supporting it.

Browsers

Datalist Support

IE 10

Firefox 4

Safari 5

 

Chrome 20

Opera 11

Let's look into how to accomplish HTML5 Datalist. Pretty simple!

<label  for="country_name">Country : </label><input  id="country_name" 
name="country_name" type="text" list="country" />
<datalist id="country">
   <option value="Afghanistan">
   <option value="Albania">
   <option value="Algeria">
   <option value="Andorra">
   <option value="Angola">
</datalist>

Feel free to try the Datalist demo! Just enter your country name.

Country :

If you do not have the browser that support it, here is how it looks like in Firefox 4.

Input Type : Search

The information in the web is growing every single second. Since Google redefined Search in the late 90's, finding information through organized directory is dead. Today, we can spot a "search box" in almost all content rich websites, it is even popular in personal blog.

In HTML5, we can define a textbox as search box instead of a normal textbox. What you can actually do for your search box is this:-
<input id="mysearch" type="search" />

By doing so, don't expect web browser to automatically blend it with a search engine. It is almost like a normal textbox <input type="text">, but browser might tweak it slightly to make it cuter.

As of writing, only Apple Safari (tested with Safari 5) and Google Chrome (tested with Google Chrome 8) does that.

Browsers

Tweak search box?

IE 10

Firefox 13

 

Safari 5

Chrome 8

Opera 9

 

Here is a simple demo.
search :

As you may notice, there is a blue "cross" sign appears in the textbox when you input something in the search box, when you click on the "cross", your input string will be clear and you can start to type a new string.

You can add more input attribute such as "Placeholder" or "Autofocus". Below is a demo of a search box with placeholder attribute.

<label for="mysearch2">Enter your search string here : </label>
<input id="mysearch2" type="search" placeholder="search">

Input Type : Email,URL,Phone

Email, Phone number and Website url are the three most commonly used contact detail which has its unique input patterns.
Email has an @ and ending with ".com" or ".net" or ".something else", website has at least one dot in the middle and most of them ending with ".com", and phone number is just number without alphabet.

Don't be confuse, these types are not for data validation, at least not yet. You will have to use the same regular expression to do so.

Below is how it looks like, you may try to input something into each field and you will find nothing special compared to plain textbox (<input type="text"/>).

Here is how the code looks like.

  <input  id="email" type="email"/>
<input id="website" type="url"/>
<input id="phone" type="tel" />

However, there are differences in how touch screen based web browsers treat those field. Below is the screen capture of iPhone 4 (iOS 4.2) and HTC Desire (Android 2.2) when each of the field gets focus.

As you can see, the web browser will give you a number pad when you focus on phone number field (type="tel"), iphone even take it further to make input of email and web url easier, every email has an "@" sign and most of the web url ending with ".com".

On the other hand, My Android keyboard input is not as friendly as iPhone is as of writing.

In conclusion, there is no reason for you not to use these "Types" from now, for web browsers that does not regconize these new types will just treat it as plain text (<input type="text"/>). This will make your page more input friendly to mobile users and more readable by machine, this is the spirit of Semantic web.

Input Type : Range

Slider control is a very intuitive user interface to set a number within a range. A typical Slider usually can be found in color picker where we can drag the arrow left and right to pick the right RGB value.

In order to create a Slider in a web page, we used to choose between javascript or flash as our solution. HTML5 is here to save thousands of bytes in your code. With the new input type (<input type="range">), Slider control will be native as Dropdown List (<select>)

The code can be as simple as :-

<input id="test" type="range"/>

As usual, the designer behind each web browser has their own taste in rendering user interface. Again, I would like to show you the gallery of Sliders in various browsers running in Windows.

Browsers do not render <input type="range"> as slider will simply render it as a normal textbox (<input type="text">).
As of writing, web browsers that render <input type="range"> as slider as follows:-

Browsers

Render Range input as Slider

IE 10

Firefox 13

 

Safari 5

Chrome 8

Opera 11

Let's look at the demo of a slider. Well, I admit it is not sexy at all.

The Range type input has a few interesting attributes which you may want to learn.

Attribute

Descriptions

value

Value is a common attribute of "Input" element. The value can be any valid floating point number, not neccessary must be an integer number. Default value is minimum value plus half of the maximum value.

min

Minimum value of the range. Default minimum value is 0.

max

Maximum value of the range. Default maximum value is 100.

step

This is Step scale factor of the slider, default value is 1 and only allowing integer number unless minimum value is non integer number.

list

List is the DataList in the past lesson. Datalist can be incorporated into Range type input, however, none of the browser has implemented this feature as of writing.

Input Type : Number

In HTML5, you can have a number input field as a spinner which you have up and down arrow at the right of the textbox to increase or decrease the number value. Please see the spinner gallery as below

As of writing, the web browsers that does the job in Windows are Google Chrome and Opera.

Browsers

Render "Number" input as Spinner

IE 9 Beta

 

Firefox 13

 

Safari 5

(in Mac OS, but not Windows)

Chrome 8

Opera 11

Let's have some real demo so you can touch it by your own self.

<label for="movie">How often you watch movie in week : </label><input id="movie" type="number" value="0"/>
If you are using Google Chrome 8, try input a non number value like "a", "B" ,"?", Chrome won't allow you to do so, but it allows you to input "e"? Why is that so? because "e" can be a part of a floating point number. For example : 5.34 e+12
On the other hand, Opera allows you do input anything as you like to it.

We shall explore some important attributes that we can have in Number Type (<input type="number">) input.

Attributes

Descriptions

value

Value is the default value of the input box when a page is first loaded. This is a common attribute for <input> element regardless which type you are using.

min

Obviously, the minimum value you of the number. I should have specified minimum value to 0 for my demo up there as a negative number doesn't make sense for number of movie watched in a week.

max

Apprently, this represents the biggest number of the number input.

step

Step scale factor, default value is 1 if this attribute is not specified.


Let's have another demo, If you are software company and your software is sold by number of user license, minimum licenses you sell is 5, each increase is 5, maximum licenses per customer you can sell is 30.

<label for="user_lic">Number of user license : </label><input id="user_lic" type="number" min="5" max="30" step="5" value ="5"/>
If you happen to use javascript to increase and decrease the value, here is the solution.

  • spinner.stepUp(x) - x being the value you want to increase in the field.
  • spinner.stepDown(x) - x being the value you want to decrease in the field.
  • spinner.valueAsNumber - return value of input as floating point number instead of string.

A spinner with relatively tiny up/down arrow might not be very finger friendly for touch screen application. Both iPhone (iOS 4.2) and Android 2.2 web browsers render <input type="number"> as normal textbox but give users a Number keypad for data input.

Screen of iPhone (iOS 4.2) on the left and HTC Desire (Android 2.2) on the right.

Input Type : Date

A Date and time field can be easily found in many web forms. Typical applications are like ticket booking, appointment booking, ordering pizza and etc.

The most commonly used solution for date input is to use Javascript date picker. Don't believe me? Just google "Javascript date picker". Most of the date picker use a calendar to let user choose a date and fill the date into a textbox.
As of writing, the only web browser completely support date time input is Opera (v11) and Google Chrome (v20). In HTML5, it is the job of web browser to ensure user can only enter a valid date time string into the input textbox.
Note: Picking a date from Calendar is not the only way to input a date value even though it's the most popular implementation. HTML5 specifications does not mention anything about displaying a calendar for date input.

Browsers

Date Time Support

IE 9 Beta

 

Firefox 13

 

Safari 5

 

Chrome 20

Opera 11

If you happen to have Opera version 11 or Google Chrome 20 (or later version of course) installed in your computer, please feel free to check it out.

Input Type : Color

In HTML5, we can have color input with simply <input type="color">. The textbox should only carry value of so called "simple color" string in lowercase such as #ff0000 for Red Color, #000000 for Black Color and #ffffff for White color.
As of writing, the only web browser that support color input is Opera 11.

Browsers

Color input Support

IE 9 Beta

 

Firefox 13

 

Safari 5

 

Chrome 20

Opera 11

With Color input type, you no longer need a complex Javascript color picker, a simple line of code below will do the work.

<label for="background-color">Choose a calor for background :</label>
<input id="background-color" type="color" />

If you are lucky enough to have web browser that support color input, please feel free to try the demo below.
Choose a calor for background :

You have chosen :

Once upon a time (it was 1990), a man named Tim Berners-Lee gave birth to the World Wide Web that we all love today.
Don't get confused, he did not invent the Internet, but HTML and HTTP Protocol. Years later, he founded WWW Consortium aka W3C, an organization that overseeing the development of the web and maintaining standard of the HTML and some other related technologies. He is still the director of W3C until today.

Most great people are driven by their dream, Sir Tim Berners-Lee is no exception. He has a great dream too. Here you go.
I have a dream for the Web... and it has two parts.
In the first part, the Web becomes a much more powerful means for collaboration between people. I have always imagined the information space as something to which everyone has immediate and intuitive access, and not just to browse, but to create. The initial WorldWideWeb program opened with an almost blank page, ready for the jottings of the user. Robert Cailliau and I had a great time with it, not because we were looking for a lot of stuff, but because we were writing and sharing our ideas. Furthermore, the dream of people-to-people communication through shared knowledge must be possible for groups of all sizes, interacting electronically with as much ease as they do now in person.

In the second part of the dream, collaborations extend to computers. Machines become capable of analyzing all the data on the Web -- the content, links, and transactions between people and computers. A "Semantic Web", which should make this possible, has yet to emerge, but when it does, the day-to-day mechanisms of trade, bureaucracy, and our daily lives will be handled by machines talking to machines, leaving humans to provide the inspiration and intuition. The intelligent "agents" people have touted for ages will finally materialize. This machine-understandable Web will come about through the implementation of a series of technical advances and social agreements that are now beginning

Once the two-part dream is reached, the Web will be a place where the whim of a human being and the reasoning of a machine coexist in an ideal, powerful mixture. Realizing the dreeam will require a lot of nitty-gritty work. The Web is far from "done." It is in only a jumbled state of construction, and no matter how grand the dream, it has to be engineered piece by piece, with many of the pieces far from glamorous.

In short, the objective of Semantic web is making the Web understandable not just by human but also machines. (not machine with artificial intelligence) With that, information exchange and sharing can be much more efficient.
HTML5 introduces a handful of new inline elements (such as span, strong, abbr) to the HTML family, in fact, it is no longer called inline element but text-level semantics.
New Text-level semantics

  • <mark>
  • <time>
  • <meter>
  • <progress>

Besides text-level elements, there are series of blocking elements for content sectioning. With the addition of these new elements, it is aim to make sections of a web page more meaningful rather than overwhelmed with "div"s of various classes such as <div class="header">....<div class="footer"> or <div class="article">
New Blocking Elements

  • <section>
  • <header>
  • <footer>
  • <nav>
  • <article>
  • <aside>

Semantic <mark>

The mark <mark> element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context.

Basically, it is used to bring the reader's attention to a part of the text that might not have been considered important or overlooked.

In the sentence above, I have highlighted "a part of the text" because I think that is a very important point that you must not overlook.

To mark part of the text, simply put your text in between <mark></mark>. It is that easy.
Basically, it is used to bring the reader's attention to <mark>a part of the text</mark> that might not have been considered important or overlooked.

As of writing, not every web browser renders <mark></mark> as highlighted text, to be on the safe side, it is also good you style the mark element in CSS.

mark { background-color:#ff9; color:#000; font-style:normal; font-weight:bold; }

Semantic <time>

The time element represents either a time on a 24 hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset.

For instance, you can do this to indicate a specific date.

We were celebrating our daugther's <time datetime="2004-07-13">birthday</time> in that seafood restaurant.
In the example below, since the time value is exposed to user in 24 hour format, we do not need "datetime" attribute to further specify the time value.

I usually go swimming at <time>20:00</time> every Saturday.

Using a styling technology that supports restyling times, the sentence above can be
"I usually go swimming at 8pm every Saturday."
Or
"I usually go swimming at 20h00 every Saturday."
On the hand, if the time value is not exposed in 24 hour format, you will have to specifically encode it in "datetime" attribute in 24 hour format.

We are open Monday to Friday from <time datetime="08:00">8am</time> through <time datetime="18:00">6pm</time>.
For a specific date and time (local time), here is how we do
You may collect your book at <time datetime="2011-01-16T06:00Z">January 16, 2011 6pm</time>.
Alternatively, you may need to specify an accurate date and time with time zone too.

The webinar will start at <time datetime="2011-02-22T09:00-4:00">February 22, 2011 9am EDT</time>.
The HTML5 specification tells us not to use "time" element if precise date or time is not known. For instance,
"I know what you did last Summer" or "I knew him sometime around 1980"

You may ask what do we get at the end of the day for using the "time" element. Alright, with all the effort, we are making our content machine readable, imagine we can one day save the "February 22, 2011 9am EDT" into our Calendar with just one click.

Besides the "datetime" attribute, the "time" element has two more attributes "pubdate" and "valueAsDate".

Attributes

Descriptions

dateTime

Date or Time or Date Time value. If present, gives the date or time being specified. Otherwise, the date or time is given by the element's contents.

pubDate

Publication Date. This is boolean attribute, which means you don't need put a value to it. If specified, it means the publication date of an article (<article>), if "time" element is not within an article block, it means it is the publication date of the entire document.
Note: You should only have one "pubdate" in one article or one document.

valueAsDate

This is a readOnly attribute, it returns a Date object representing the specified date and time

"pubDate" can be typically applied in blog entry or news article. For article that published in January 21 2011, simply encode as :

<time datetime="2011-01-21" pubdate>January 21 2011</time>

Semantic <meter>

"Meter" is a new element in HTML5 which represenet value of a known range as a gauge. The keyword here is "known range". That means, you are only allowed to use it when you are clearly aware of its minimum value and maximum value.
Besides, you shouldn't use meter element to indicate a progress such as 80% because there is a "progress" element in HTML5.

One example is score of rating. I would rate this movie <meter min="0" max="10" value="8">8 of 10</meter>.
Below is the scores of alex's mid-term exam.

Science : 95 of 100
Math : 60 of 100
Geography : 20 of 100
History : 50 of 100

Science : <meter min="0" max="100" value="95">95 of 100</meter> <br />
Math : <meter min="0" max="100" value="60">60 of 100</meter><br />
Geography : <meter min="0" max="100" value="20">20 of 100</meter> <br />
History : <meter min="0" max="100" value="50">50 of 100</meter>

As of writing, only Opera 11 and Google Chrome 8 render "meter" element into a visualize gauge. Therefore, it is good to specify textual value in between "meter" tags, so web browsers don't render "meter" as gauge can simply show its value in plain text.

Without your effort to specify a textual value in between "meter" tag, user will just see a blank space in web browsers that don't support "meter".

Browsers

Render meter element as gauge

IE 9 Beta

 

Firefox 13

 

Safari 5

 

Chrome 8

Opera 11

Semantic <aside>

The "aside" element is a section that somehow related to main content, but it can be separate from that content. In this tutorial, I use "aside" element for tips related to the topic. What mentioned in the the yellow block provides additional information to reader, however, a reader can actually continue the tutorial without reading the tips.

<article>
<p>

As of writing, the only web browser completely support date time input is Opera. In HTML5, it is the job of web browser to ensure user can only enter a valid date time string into the input textbox.

</p>

<aside>

Picking a date from Calendar is not the only way to input a date value even though it's the most popular implementation.
HTML5 specifications does not mention anything about displaying a calendar for date input.
</aside>
</article>

The specifications of W3C says:
The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.

The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page.

Elements you shouldn't be using

After the introduction of many new elements and attributes in the past lessons, it is time to talk about what you should be avoiding in HTML5.

Ever since CSS was invented, web developers have been always told to segregate design from content. Let's CSS take care of the styles and HTML take care the structure and content of your page.

In HTML5, The life of the following elements have come to an end. They have no role to play in HTML5 because CSS has grab it all.

  • <basefont>
  • <big>
  • <center>
  • <font>
  • <strike>
  • <tt>
  • <u>

The following elements has nothing to do with styling but they are simply a bad guys in HTML coding because they have been blamed of "damages usability and accessibility"

  • <frame>
  • <frameset>
  • <noframes>

The following elements are not included in HTML5 because they have not been used often, created confusion, or their function can be handled by other elements:

  • <acronym> is gone, use <abbr> instead for abbreviations.
  • <applet> has been obsoleted in favor of object.
  • <isindex> usage can be replaced by usage of form controls.
  • <dir> has been obsoleted in favor of <ul>.
  • Finally the <noscript> element is only conforming in the HTML syntax. It is not included in the XML syntax as its usage relies on an HTML parser.

If you still insist on using these element, you web page will not blow, and yet, web browser will still be supporting it. So, the cost of doing is, your page will not pass in HTML5 validation.

Attributes you shouldn't be using

In HTML5, none of the attribute should be used for styling purpose. Rule of thumb is, styling should be taken care by CSS.

What I meant for "styling" is such as font size, color, border, font family, whatever is used for presentational purpose.
In the table below, you should be avoid using attributes below in the elements listed in following table.

Attributes

Elements

align

caption, iframe, img, input, object, legend, table, hr, div, h1, h2, h3, h4, h5, h6, p, col, colgroup, tbody, td, tfoot, th, thead and tr.

alink, link, text and vlink

body

background

body

bgcolor

table, tr, td, th and body

border

table and object

cellpadding and cellspacing

table

char and charoff

col, colgroup, tbody, td, tfoot, th, thead and tr

clear

br

compact

dl, menu, ol and ul

frame

table

frameborder

iframe

height

td and th

hspace and vspace

img and object

marginheight and marginwidth

iframe

noshade

hr

nowrap

td and th

rules

table

scrolling

iframe

size

hr

type

li, ol and ul

valign

col, colgroup, tbody, td, tfoot, th, thead and tr

width

hr, table, td, th, col, colgroup and pre

 








}