Some New Elements in HTML5
While HTML5 introduces a wide variety of interesting new capabilities, this section concentrates on the new tags that help ease some long-standing difficulties.
Video Playback with <video>
Video on the Web is extremely popular. However, the methods for implementing video are generally proprietary, reproduction happening via plug-ins such as Flash, Windows Media, and Apple QuickTime. Markup that works for embedding these elements in one browser doesn’t always work in the others.
HTML5 contains a new <video> element, the aim of which is to enable the embedding of any and all video formats.
Using the new <video> tag, you can implement your favorite QuickTime movie like this:
<video src="video.mov" />
So far there has been much debate about which video formats (codecs) should be supported by the video element; at the time of writing, the search continues for a codec that requires no special licensing terms, though WebM (http://www.webmproject.org/) is currently looking like the favorite. For the time being, quoting multiple sources gets around the problem and avoids the need for browser sniffing; there are currently three widely supported video formats—MP4, WebM, and Ogg.
<video id="vid1" width="400" height="300" controls="controls"> <source src="movie.mp4" type="video/mp4" /> <source src="movie.ogg" type="video/ogg" /> <source src="movie.webm" type="video/webm" /> <p>Video tag not supported.</p> </video>
It is also a good practice to include width and height attributes for the <video> element. If height and width are not set, the browser doesn’t know how much screen space to reserve, resulting in the page layout changing as the video loads.
You are also recommended to place some suitable text between the <video> and </video> tags to display in browsers that don’t support the <video> tag.
Some important properties of the <video> tag are listed below
Note that the appearance of the controls added using the controls property will depend on the browser in use, as belowYou can access these properties in the same way as any other JavaScript or DOM object. For the previous video definition, you might use
var myVideo = document.getElementById("vid1").volume += 0.1;
to marginally increase the volume, or
if(document.getElementById("vid1").paused) { alert(message); }
to pass a message to the user indicating that video playback is currently paused.
Testing Format Support with canPlayType()
You can check for support for a particular codec using the JavaScript method
media.canPlayType(type)
In the preceding example, type is a string containing the media type, for example, “video/webm”. This method must return an empty string if the browser knows it cannot play the content. The method might also return “probably” if the browser is confident it can support the format, or “maybe” otherwise.
Controlling Playback
Playback can also be controlled programmatically using the pause() and play() commands, as in the following code snippet:
var myVideo = document.getElementById("vid1").play();
var myVideo = document.getElementById("vid1").pause();
Playing Sound with the <audio> Tag
Pretty much everything stated previously about the <video> tag applies equally well to the <audio> tag. The simple way to use the <audio> tag is like this: Click here to view code image
<audio src="song.mp3"></audio>
You can add further attributes to achieve more control over playback, such as loop and autoplay:
<audio src="song.mp3" autoplay loop></audio>
Don’t abuse loop and autoplay, or you may find that many of your site visitors don’t return!
As with the earlier examples for video files, you can include alternative formats to help ensure that a user’s browser will find one that it can play, as in the following code:
<audio controls="controls"> <source src="song.ogg" type="audio/ogg" /> <source src="song.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio>
MP3, WAV, and Ogg are typically supported file formats for the <audio> element. Controlling an audio file in JavaScript uses the same methods as for the <video> tag.
To add and play an audio file via JavaScript, you can treat it just like any other JavaScript or DOM object:
var soundElement = document.createElement('audio'); soundElement.setAttribute('src', 'sound.ogg'); soundElement.play(); soundElement.pause();
The <audio> and <video> tags have many useful properties that you can access via JavaScript. Here are a few useful ones, the meaning of which will be immediately apparent:
mediaElement.duration mediaElement.currentTime mediaElement.playbackRate mediaElement.muted
For example, to move to a point 45 seconds into a song you might use
soundElement.currentTime = 45;
You can find a comprehensive reference to these tags and their properties and methods at http://www.whatwg.org/specs/web-apps/current-work/multipage/thevideo- element.html.
Drawing on the Page with >canvas<
The new <canvas> tag gives you just that: a rectangular space in your page where you can draw shapes and graphics, as well as load and display image files and control their display via JavaScript. The many practical uses for the element include dynamic charts, JavaScript/HTML games, and instructional animations.
Using the <canvas> tag simply allows you to define a region by setting its width and height parameters; everything else related to creating the graphical content is done via JavaScript. There is an extensive set of drawing methods known as the Canvas 2D API.
Try it Yourself: Moving a Ball Using <canvas>
You’re going to make a simple animation in a <canvas> element—just a red disc (to represent a ball) moving in a circle on the page.
The only HTML markup required in the body of the page is the <canvas> element itself:
<canvas id="canvas1" width="400" height="300"></canvas>
All the drawing and animation will be done in JavaScript
If you don’t set width and height parameters, the canvas defaults to 300 pixels wide by 150 pixels high.You first need to specify the rendering context. At the time of writing, 2D is the only widely supported context, though a 3D context is under development.
context = canvas1.getContext('2d');
The only primitive shapes supported by <canvas> are rectangles:
fillRect(x,y,width,height); //draw a filled rectangle strokeRect(x,y,width,height); //draw an outlined rectangle clearRect(x,y,width,height); // clear the rectangle
All other shapes must be created by using one or more path-drawing functions. Since you want to draw a colored disc, that’s what you need here.
Several different path-drawing functions are offered by <canvas>.
Move to x, y without drawing anything: moveTo(x, y)
Draw a line from the current location to x, y: lineTo(x, y)
Draw a circular arc of radius r, having circle center x, y, from startAngle to endAngle.
Click here to view code image arc(x, y, r, startAngle, endAngle, anti)
Setting the last parameter to Boolean true makes the arc draw counterclockwise
instead of the default clockwise.
To create shapes using these basic commands, you need some additional methods:
object.beginPath(); object.closePath(); //complete a partial shape object.stroke(); //draw an outlined shape object.fill(); //draw a filled shapeIf you use the fill method, an open shape will be closed automatically without you having to use closePath().
To make the ball you’re going to generate a filled circle. Let’s make it red, of radius 15, and centered on canvas coordinates 50, 50:
context.beginPath(); context.fillStyle="#ff0000"; context.arc(50, 50, 15, 0, Math.PI*2, true); context.closePath();
To animate the ball, you need to alter the x and y coordinates of the ball center using a timer. Take a look at the animate() function:
function animate() { context.clearRect(0,0, 400,300); counter++; x += 20 * Math.sin(counter); y += 20 * Math.cos(counter); paint(); }
This function is called repeatedly via the setInterval() method. Each time it’s called, the canvas is cleared by using the clearRect() method across the full size of the canvas element. The variable counter is incremented on each loop, and its new value is then used to redefine the position of the disc’s center.
The complete code is listed below:
<!DOCTYPE HTML> <html> <head> <title>HTML5 canvas</title> <script> var context; var x=50; var y=50; var counter = 0; function paint() { context.beginPath(); context.fillStyle="#ff0000"; context.arc(x, y, 15, 0, Math.PI*2, false); context.closePath(); context.fill(); } function animate() { context.clearRect(0,0, 400,300); counter++; x += 20 * Math.sin(counter); y += 20 * Math.cos(counter); paint(); } window.onload = function() { context= canvas1.getContext('2d'); setInterval(animate, 100); } </script> </head> <body> <canvas id="canvas1" width="400" height="300"> <p>Your browser doesn't support the canvas element.</p> </canvas> </body> </html>
Create this file and load it into your browser. If your browser supports the <canvas> element, you should see a red disc following a circular route on the page, as below given snapshot