New Media Elements in HTML5

New Media Elements in HTML5 is part 3 of Beginner’s Guide to HTML5.

New Media Elements:

HTML5 element gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.

The HTML5 Canvas element is an HTML tag similar to the <div>, <a>, or <table> tag, with the exception that its contents are rendered with JavaScript.  In order to leverage the HTML5 Canvas, we’ll need to place the canvas tag somewhere inside the HTML document, access the canvas tag with JavaScript, create a context, and then utilize the HTML5 Canvas API to draw visualizations.

Here is a simple element which has only two specific attributes width and height plus all the core HTML5 attributes like id, name and class etc.

[code language=”html”][/code]

You can easily find that element in the DOM using getElementById() method as follows:

[code language=”js”]var canvas = document.getElementById(“mycanvas”);[/code]

Let us see a simple example on using element in HTML5 document.

[code language=”html”];


You can create many shapes using canvas as example below:

html5 canvas shapes

The Rendering Context:

The is initially blank, and to display something, a script first needs to access the rendering context and draw on it.

When using canvas, it’s important to understand the difference between the canvas element and the canvas context, as often times people get these confused.  The canvas element is the actual DOM node that’s embedded in the HTML page.  The canvas context is an object with properties and methods that you can use to render graphics inside the canvas element.  The context can be 2d or 3d.

Each canvas element can only have one context.  If we use the getContext() method multiple times, it will return a reference to the same context object.

The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.

Following is the code to get required context along with a check if your browser supports element:

[code language=”html”]




Before HTML5, the audio files could not be played on a web page without support of third party plug-ins like Adobe Flash Player, Apple QuickTime Player etc. But HTML5 defines a new element (

Important point need to be remembered:

HTML5 audio element is supported by latest versions of all web browsers. Internet Explorer 8 or earlier versions of Internet Explorer do not support audio element.

Presently three audio file formats are supported by HTML5 audio element – .mp3, .ogg and .wav.

There is a HTML5 audio element example given below:

[code language=”html”]