JavaScript Journal

Subscribe to JavaScript Journal: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get JavaScript Journal: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

JavaScript Authors: Sematext Blog, Klaus Enzenhofer, Mehdi Daoudi, Yakov Fain, AppDynamics Blog

Related Topics: RIA Developer's Journal, JavaScript, HTML5


Book Excerpt: Introducing HTML5

HTML5 marks a groundbreaking change in how we interact with the browser

Handling Unsupported Formats
At the time of this writing, the audio and video elements in different browsers don't necessarily all support the same types of audio and video. The reason a particular browser doesn't support a particular format might be due to the age of the format, competition with an endorsed format, or patent restrictions that the browser's parent company doesn't want to deal with. Media tags have several methods to deal with this.

Listing Multiple Sources
Instead of specifying a single source, the developer can choose to list multiple sources to let the browser choose the appropriate one to use. The following snippet lists two sources for a video tag and the fallback message if neither format is supported or the browser doesn't support the video tag.

<source src="video.ogv" />
<source src="video.avi" />
<!- Neither is supported, can show message or fallback to Flash ->
<div><span>Use a modern browser</span></div>

Although listing multiple sources is an option for a static page, it's not great for applications with dynamic content. For those instances, using the tool Modernizr is recommended. We'll discuss Modernizr in more detail in Chapter 2, but consider this a primer.

Using Modernizr
Modernizr ( inspects browser capabilities at runtime and injects the properties into a JavaScript object. To see whether the browser can play audio or video, we would check the value of or to see if it evaluates to true.

Checking support for a particular format is slightly different. Verifying support for MP3 files is done by checking the value of, but the value returned isn't true or false. The HTML5 spec states that the browser should return its confidence level that it can play the format. The return value will be "probably," "maybe," or an empty string. When we use in a conditional clause, any non-empty value is treated as true and the empty string is treated as false.

CSS3 doesn't fit the scope of this book, and readers are encouraged to explore the specification if they are interested in it. Like HTML5, CSS3 extends its predecessor (CSS2) by adding new features and codifying previous proposals, such as web fonts and speech, which were introduced in previous versions but not widely supported. A useful website for further information is

HTML5 Drawing APIs
An interesting area of the HTML5 spec is the new drawing APIs. Canvas, SVG, and WebGL provide bitmapped, vector, and three-dimensional drawing capabilities, respectively.

The canvas element started its life as an Apple extension to Webkit, the layout engine powering Safari and Chrome, to display Dashboard gadgets and additions to the Safari browser. It was later adopted by Opera, Firefox, and related browsers, eventually becoming a component of the HTML5 specification. The beta release of Internet Explorer 9 (IE9) has brought native support to all major browsers, although support in IE9 is not as complete as the aforementioned browsers.

The canvas element can be most simply described as a drawable region with height and width attributes using JavaScript as the medium to draw and animate complex graphics such as graphs and images. A full set of 2D drawing functions is exposed by the JavaScript language. Given the close relationship between JavaScript and ActionScript, a Flash drawing or animation using ActionScript can be easily ported to JavaScript with only moderate effort. Canvas will be covered in more detail in Chapter 5, "Creating Games with the Canvas Tag."

SVG (Scalable Vector Graphics) is a mature W3C specification for drawing static or animated graphics. The ability to inline SVG without the use of an object or embed tag was added in HTML5. Vector graphics use groupings of mathematics formulas to draw primitives such as arcs, lines, paths, and rectangles to create graphics that contain the same quality when rendered at any scale. This is a marked benefit over images whose discernible quality degrades when they are displayed at a scale larger than that for which they were designed.

SVG takes a markedly different approach from the canvas element in that it represents drawings in XML files instead of purely in code. XML is not the more concise representation of data, so a file may contain many repeated sections. This can be addressed by compressing the file, which can greatly reduce its size. As with the canvas element, interaction can be scripted using JavaScript. Prior to IE9, IE supported an incompatible vector format called VML. As of IE9, all major desktop browsers support a fairly common feature set of SVG 1.1. Chapter 6, "Creating Games with SVG and RaphaëlJS," puts SVG front and center.

WebGL is a JavaScript API for 3D drawing that enables the developer to assess graphics hardware and control minute details of the rendering pipeline. It is managed by the Khronos group and shares much of its syntax with OpenGL 2.0 ES. At the time of this writing, WebGL is not supported in Internet Explorer 6+ or the stable branches of Opera and Safari. It is available in the stable builds of Firefox and Chrome/Chromium and in development builds of Opera and Safari. Chapter 7, "Creating Games with WebGL and Three.js," dives into WebGL.

Conveying Information with Microdata
A web application or API parsing a page can interpret HTML marked up with microdata and respond to it. For instance, a search engine that returns results marked up with microdata could be parsed by a browser extension or script to better present the data to a visually impaired or colorblind user. Microformats are a preceding concept that serves the same goal. One key difference between microformats and HTML5 microdata is the way that the data is denoted. As shown in Listing 6, microformats use the class property of an object to indicate the fields on an object.

Listing 6: hCard Microformat Example
<div class="vcard">
<div class="fn">James Williams</div>
<div class="org">Some Company</div>
<div class="tel">650-555-3055</div>
<a class="url" href=""></a>

Microdata uses the same concept with slightly different notation. Instead of marking properties using classes, the itemprop keyword is used. The keyword itemscope marks an individual unit. At its core, microdata is a set of name/value pairs composed into items. Listing 7 shows a microdata example. The itemtype property indicates a definition of the object and specifies valid properties. You could use microdata to encode the names and scores on a leader board page or instructions and screenshots from a game.

Listing 7: Microdata Example
<p itemprop="address" itemscope

<span itemprop="street-address">1600 Amphitheatre Parkway</span><br>

<span itemprop="locality">Mountain View</span>,
<span itemprop="region">CA</span>

<span itemprop="postal-code">94043</span><br>

<span itemprop="country-name">USA</span>


HTML5 marks a groundbreaking change in how we interact with the browser. This excerpt highlighted the major additions that apply to our needs. You learned how Google Chrome Frame brings HTML5 features to IE browsers as well as the multiple ways to draw assets.

In exploring HTML5, in addition to its drawing APIs, you learned about features that allow you to run computationally heavy tasks without blocking the browser, setting up bidirectional communications channels between applications, and enabling offline execution of applications.

You can download chapter code at

•   •   •

This chapter is from the book, ‘Learning HTML5 Game Programming: A Hands-on Guide to Building Online Games Using Canvas, SVG, and WebGL', authored by James Williams, published by Pearson/Addison-Wesley Professional, Sept. 2011, ISBN 0321767365, Copyright 2012 Pearson Education, Inc. For more info please visit

More Stories By James Williams

James Williams is an experienced developer and speaker who has given presentations all over the world on Java, user interfaces, and Google Wave. He is the creator of SwingXBuilder, a DSL for creating user interfaces using SwingX components, and a co-despot of Griffon, a framework to make rich applications using Groovy. James is based in the San Francisco Bay Area and you can follow his blog at

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.