Learning PHP, MySQL, JavaScript, CSS & HTML5 (2014)

Chapter 22. Introduction to HTML5

HTML5 represents a substantial leap forward in web design, layout, and usability. It provides a simple way to manipulate graphics in a web browser without resorting to plug-ins such as Flash, offers methods to insert audio and video into web pages (again without plug-ins), and irons out several annoying inconsistencies that crept into HTML during its evolution.

In addition, HTML5 includes numerous other enhancements such as geolocation handling, web workers to manage background tasks, improved form handling, access to bundles of local storage (far in excess of the limited capabilities of cookies), and even the facility to turn web pages into web applications for mobile browsers.

What’s curious about HTML5, though, is that it has been an ongoing evolution, in which different browsers have adopted different features at different times. Fortunately, all the biggest and most popular HTML5 additions are finally now supported by all major browsers (those with more than 1% or so of the market, such as Chrome, Internet Explorer, Firefox, Safari, and Opera, and the Android and iOS browsers).

But with HTML5 having only been officially submitted to the W3C in early 2013, there remain a number of features outstanding in several browsers, which I outline later in the book so you will be prepared when they are adopted.

Nevertheless, we are now fully into the second big surge toward dynamic web interactivity (the first being the adoption of what became known as Web 2.0). I would hesitate to call it Web 3.0, though, because the term HTML5 says it all to most people, and in my view it could be considered a later version of Web 2.0 (maybe something like Web 2.7).

Actually, I think it will be very interesting to see what Web 3.0 will turn out to be. If I were to hazard a prediction, though, I would say it will result from the application of artificial intelligence (AI) in the form of much more capable versions of software such as Apple’s Siri, Microsoft’s Cortana, and IBM’s Watson, combined with wearable technology that uses visual and voice input—like Google Glass and the Galaxy Gear watch—rather than keyboards. I look forward to covering these things in future editions of this book.

But for now, having written about what’s to come in HTML5 for some years, and now that so many parts of the specification are usable on virtually all devices and browsers, I’m pleased to finally be able to bring it into this edition of the book. So let me take you on an overview of what’s available to you in HTML5 right now.

The Canvas

Originally introduced by Apple for the WebKit rendering engine (which had itself originated in the KDE HTML layout engine) for its Safari browser (and now also implemented in iOS, Android, Kindle, Chrome, BlackBerry, Opera, and Tizen), the canvas element enables us to draw graphics in a web page without having to rely on a plug-in such as Java or Flash. After being standardized, the canvas was adopted by all other browsers and is now a mainstay of modern web development.

Like other HTML elements, a canvas is simply an element within a web page with defined dimensions, and within which you can use JavaScript to draw graphics. You create a canvas using the <canvas> tag, to which you must also assign an ID so that JavaScript will know which canvas it is accessing (as you can have more than one canvas on a page).

In Example 22-1, I’ve created a <canvas> element, with the ID mycanvas, that contains some text that is displayed only in browsers that don’t support the canvas. Beneath this there is a section of JavaScript, which draws the Japanese flag on the canvas (as shown in Figure 22-1).

Example 22-1. Using the HTML5 canvas element

<!DOCTYPE html>

<html>

  <head>

    <title>The HTML5 Canvas</title>

    <script src='OSC.js'></script>

  </head>

  <body>

    <canvas id='mycanvas' width='320' height='240'>

      This is a canvas element given the ID <i>mycanvas</i>

      This text is only visible in non-HTML5 browsers

    </canvas>

    <script>

      canvas            = O('mycanvas')

      context           = canvas.getContext('2d')

      context.fillStyle = 'red'

      S(canvas).border  = '1px solid black'

      context.beginPath()

      context.moveTo(160, 120)

      context.arc(160, 120, 70, 0, Math.PI * 2, false)

      context.closePath()

      context.fill()

    </script>

  </body>

</html>

Drawing the Japanese flag using an HTML5 canvas

Figure 22-1. Drawing the Japanese flag using an HTML5 canvas

At this point it’s not necessary to detail exactly what is going on, as I explain that in the following chapter, but you should already see how using the canvas is not hard, but does require learning a few new JavaScript functions. Note that this example draws on the OSC.js set of functions from the previous chapter to help keep the code neat and compact.

Geolocation

Using geolocation, your browser can return information to a web server about your location. This information can come from a GPS chip in the computer or mobile device you’re using, from your IP address, or from analysis of nearby WiFi hotspots. For security purposes, the user is always in control and can refuse to provide this information on a one-off basis, or can enable settings to either permanently block or allow access to this data from one or all websites.

There are numerous uses for this technology, including giving you turn-by-turn navigation; providing local maps; notifying you of nearby restaurants, WiFi hotspots, or other places; letting you know which friends are near you; directing you to the nearest gas station; and more.

Example 22-2 will display a Google map of the user’s location, as long as the browser supports geolocation and the user grants access to his location (as shown in Figure 22-2). Otherwise, it will display an error.

Example 22-2. Displaying the map at a user’s location

<!DOCTYPE html>

<html>

  <head>

    <title>Geolocation Example</title>

    <script src='OSC.js'></script>

    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

  </head>

  <body>

    <div id='status'></div>

    <div id='map'></div>

    <script>

      if (typeof navigator.geolocation == 'undefined')

         alert("Geolocation not supported.")

      else

        navigator.geolocation.getCurrentPosition(granted, denied)

      function granted(position)

      {

        O('status').innerHTML = 'Permission Granted'

        S('map').border       = '1px solid black'

        S('map').width        = '640px'

        S('map').height       = '320px'

        var lat   = position.coords.latitude

        var long  = position.coords.longitude

        var gmap  = O('map')

        var gopts =

        {

          center: new google.maps.LatLng(lat, long),

          zoom: 9, mapTypeId: google.maps.MapTypeId.ROADMAP

        }

        var map = new google.maps.Map(gmap, gopts)

      }

      function denied(error)

      {

        var message

        switch(error.code)

        {

          case 1: message = 'Permission Denied'; break;

          case 2: message = 'Position Unavailable'; break;

          case 3: message = 'Operation Timed Out'; break;

          case 4: message = 'Unknown Error'; break;

        }

        O('status').innerHTML = message

      }

    </script>

  </body>

</html>

The user’s location has been used to display a map

Figure 22-2. The user’s location has been used to display a map

Again, here is not the place to describe how this all works, as I will detail that in Chapter 25. For now, though, this example serves to show you how easy managing geolocation can be, especially given that much of the code is dedicated to handling errors and calling up the Google map, so the core geolocation code you need is actually minimal.

Audio and Video

Another great addition to HTML5 is support for in-browser audio and video. While playing these types of media can be a little complicated due to the variety of encoding types and licenses, the <audio> and <video> elements provide the flexibility you need to display the types of media you have available.

In Example 22-3, the same video file has been encoded in different formats to ensure that all major browsers are accounted for. Browsers will simply select the first type they recognize and play it, as shown in Figure 22-3.

Example 22-3. Playing a video with HTML5

<!DOCTYPE html>

<html>

  <head>

    <title>HTML5 Video</title>

  </head>

  <body>

    <video width='560' height='320' controls>

      <source src='movie.mp4'  type='video/mp4'>

      <source src='movie.webm' type='video/webm'>

      <source src='movie.ogv'  type='video/ogg'>

    </video>

  </body>

</html>

Displaying video using HTML5

Figure 22-3. Displaying video using HTML5

Inserting audio into a web page is just as easy, as you will discover in Chapter 24.

Forms

As you already saw in Chapter 12, HTML5 forms are in the process of being enhanced, but support across all browsers remains patchy. What you can safely use today has been detailed in Chapter 12, and future editions of this book will include other aspects of forms as they become adopted across the board. In the meantime, you can keep up-to-date with the latest developments on HTML5 forms at http://tinyurl.com/h5forms.

Local Storage

With local storage, your ability to save data on a local device is substantially increased from the meager space provided by cookies. This opens up the possibility of your using web apps to work on documents offline and then only syncing them with the web server when an Internet connection is available. It also raises the prospect of storing small databases locally for access with WebSQL, perhaps for keeping a copy of your music collection’s details, or all your personal statistics as part of a diet or weight loss plan, for example. In Chapter 25, I show you how to make the most of this new facility in your web projects.

Web Workers

It has been possible to run interrupt-driven applications in the background using JavaScript for many years, but it is a clumsy and inefficient process. It makes much more sense to let the underlying browser technology run background tasks on your behalf, which it can do far more quickly than you can by continuously interrupting the browser to check how things are going.

Instead, with web workers you set everything up and pass your code to the web browser, which then runs it. When anything significant occurs, your code simply has to notify the browser, which then reports back to your main code. In the meantime, your web page can be doing nothing or a number of other tasks, and can forget about the background task until it makes itself known.

In Chapter 25, I demonstrate how you can use web workers to create a simple clock and to calculate prime numbers.

Web Applications

More and more these days, web pages are beginning to resemble apps, and with HTML5 they can become web apps very easily. All you have to do is tell the web browser about the resources used in your application, and it will download them to where they can be run and accessed locally, offline, and without any Internet connection if necessary.

Chapter 25 shows how you can do this to turn the clock example in the web workers section into a web app.

Microdata

Also in Chapter 25, I show how you can mark up your code with microdata to make it totally understandable to any browser or other technology that needs to access it. Microdata is sure to become more and more important to search engine optimization too, so it’s important that you begin to incorporate it or at least understand what information it can provide about your websites.

Summary

As you can see, there’s quite a lot to HTML5, and it’s all goodies that many people waited a long time for—but they’re finally here. Starting with the canvas, the following few chapters will explain these features to you in glorious detail, so you can be up and running with them, and enhancing your websites, in no time.

Questions

1.    What new HTML5 element enables drawing of graphics in web pages?

2.    What programming language is required to access many of the advanced HTML5 features?

3.    Which tags would you use to incorporate audio and video in a web page?

4.    What feature is new in HTML5 and offers greater capability than cookies?

5.    Which HTML5 technology supports running background JavaScript tasks?

See Chapter 22 Answers in Appendix A for the answers to these questions.