You are previewing HTML5 Canvas.

HTML5 Canvas

Cover of HTML5 Canvas by Steve Fulton... Published by O'Reilly Media, Inc.
  1. HTML5 Canvas
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Preface
      1. Running the Examples in the Book
      2. What You Need to Know
      3. How This Book Is Organized
      4. Conventions Used in This Book
      5. Using Code Examples
      6. We’d Like to Hear from You
      7. Safari® Books Online
      8. Acknowledgments
    4. 1. Introduction to HTML5 Canvas
      1. The Basic HTML Page
      2. Basic HTML We Will Use in This Book
      3. The Document Object Model (DOM) and Canvas
      4. JavaScript and Canvas
      5. HTML5 Canvas “Hello World!”
      6. Debugging with Console.log
      7. The 2D Context and the Current State
      8. The HTML5 Canvas Object
      9. Another Example: Guess The Letter
      10. What’s Next
    5. 2. Drawing on the Canvas
      1. The Basic File Setup for This Chapter
      2. The Basic Rectangle Shape
      3. The Canvas State
      4. Using Paths to Create Lines
      5. Advanced Path Methods
      6. Compositing on the Canvas
      7. Simple Canvas Transformations
      8. Filling Objects with Colors and Gradients
      9. Filling Shapes with Patterns
      10. Creating Shadows on Canvas Shapes
      11. What’s Next
    6. 3. The HTML5 Canvas Text API
      1. Displaying Basic Text
      2. Setting the Text Font
      3. Text and the Canvas Context
      4. Text with Gradients and Patterns
      5. Width, Height, Scale, and toDataURL() Revisited
      6. Final Version of Text Arranger
      7. What’s Next
    7. 4. Images on the Canvas
      1. The Basic File Setup for This Chapter
      2. Image Basics
      3. Simple Cell-Based Sprite Animation
      4. Advanced Cell-Based Animation
      5. Applying Rotation Transformations to an Image
      6. Creating a Grid of Tiles
      7. Zooming and Panning an Image
      8. Pixel Manipulation
      9. Copying from One Canvas to Another
      10. What’s Next
    8. 5. Math, Physics, and Animation
      1. Moving in a Straight Line
      2. Bouncing Off Walls
      3. Curve and Circular Movement
      4. Simple Gravity, Elasticity, and Friction
      5. Easing
      6. What’s Next?
    9. 6. Mixing HTML5 Video and Canvas
      1. HTML5 Video Support
      2. Converting Video Formats
      3. Basic HTML5 Video Implementation
      4. Preloading Video in JavaScript
      5. Video and the Canvas
      6. Video on the Canvas Examples
      7. Animation Revisited: Moving Videos
      8. What’s Next?
    10. 7. Working with Audio
      1. The Basic <audio> Tag
      2. Audio Formats
      3. Audio Tag Properties, Functions, and Events
      4. Playing a Sound with No Audio Tag
      5. Creating a Canvas Audio Player
      6. Case Study in Audio: Space Raiders Game
      7. What’s Next
    11. 8. Canvas Game Essentials
      1. Why Games in HTML5?
      2. Our Basic Game HTML5 File
      3. Our Game’s Design
      4. Game Graphics: Drawing with Paths
      5. Animating on the Canvas
      6. Applying Transformations to Game Graphics
      7. Game Graphic Transformations
      8. Game Object Physics and Animation
      9. A Basic Game Framework
      10. Putting It All Together
      11. The player Object
      12. Geo Blaster Game Algorithms
      13. The Geo Blaster Basic Full Source
      14. Rock Object Prototype
      15. What’s Next
    12. 9. Combining Bitmaps and Sound
      1. Geo Blaster Extended
      2. Creating a Dynamic Tile Sheet at Runtime
      3. A Simple Tile-Based Game
      4. What’s Next
    13. 10. Mobilizing Games with PhoneGap
      1. Going Mobile!
      2. Creating the iOS Application with PhoneGap
      3. Beyond the Canvas
      4. What’s Next
    14. 11. Further Explorations
      1. 3D with WebGL
      2. Multiplayer Applications with ElectroServer 5
      3. Conclusion
    15. Index
    16. About the Authors
    17. Colophon
    18. SPECIAL OFFER: Upgrade this ebook with O’Reilly
O'Reilly logo

Audio Tag Properties, Functions, and Events

Similar to the <video> tag, the <audio> tag in HTML5 is based on the HTMLAudioElement DOM object, which is derived from HTMLMediaElement.

Audio Functions

load()

Starts loading the sound file specified by the src property of the <audio> tag.

play()

Starts playing the sound file specified by the src property of the <audio> tag. If the file is not ready, it will be loaded.

pause()

Pauses the playing audio file.

canPlayType()

Accepts a MIME type as a parameter, and returns the value maybe or probably if the browser can play that type of audio file. It returns “” (an empty string) if it cannot.

Important Audio Properties

There are many properties defined for the audio element in HTML5. We are going to focus on the following because they are the most useful for the applications we will build:

duration

The total length, in seconds, of the sound represented by the audio object.

currentTime

The current playing position, in seconds, of the playing audio file.

loop

true or false: whether the audio clip should start playing at the beginning when currentTime reaches the duration.

autoplay

true or false: whether the audio should start playing automatically when it has loaded.

muted

true or false. Setting this to true silences the audio object regardless of volume settings

controls

true or false. Displays controls for an audio object in an HTML page. Controls will not display on the canvas unless they are created in HTML (for example, with a <div> overlay).

volume

The volume level of the audio object; the value must be between 0 and 1.

paused

true or false: whether the audio object is paused. Set with a call to the pause() function.

ended

true or false. Set when an audio object has played through its entire duration.

currentSrc

URL to the source file for the audio object.

preload

Specifies whether the media file should be loaded before the page is displayed. At the time of this writing, this property has not been implemented across all browsers.

Note

To see which properties and events of the HTMLMediaObject are supported in which browsers, visit http://www.w3.org/2010/05/video/mediaevents.html.

Important Audio Events

Many events are defined for the HTML5 audio element. We are going to focus on the following events because they have proven to work when building audio applications:

progress

Raised when the browser is retrieving data while loading the file. (This still has spotty support in browsers, so be careful with it.)

canplaythrough

Raised when the browser calculates that the media element could be played from beginning to end if started immediately.

playing

Set to true when the audio is being played.

volumechange

Set when either the volume property or the muted property changes.

ended

Set when playback reaches the duration of the audio file and the file stops being played.

Loading and Playing the Audio

We are going to use the canplaythrough and progress events to load <audio> before we try to play it. Here is how we embed the audio for song1:

<audio id="theAudio" controls>
<source src="song1.mp3" type="audio/mp3">
<source src="song1.wav" type="audio/wav">
<source src="song1.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>

Similar to most of the applications we have built thus far in this book, we will create event handlers for progress and canplaythrough once the window DOM object has finished loading, and then call the load() method of audioElement to force the audio file to start loading:

window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
   var audioElement = document.getElementById("theAudio");
   audioElement.addEventListener('progress',updateLoadingStatus,false);
   audioElement.addEventListener('canplaythrough',audioLoaded,false);
   audioElement.load();

}

When the canplaythrough event is dispatched, canvasApp() is called. Then, we start playing the audio by retrieving a reference to the audio element in the HTML page through the DOM, with a call to getElementById(). (We will create a variable named audioElement that we will use throughout the canvas application to reference the audio element in the HTML page.) We then call the play() function of audioElement:

var audioElement = document.getElementById("theAudio");
audioElement.play();

You may be wondering why we didn’t use the preload attribute of HTMLAudioElement instead of forcing it to load by listening for the canplaythrough event. There are two reasons for this, and both apply to the video element as well. First, you want to preload so that you are sure the assets you need are available to your program at runtime. Second, preloading ensures that the user will see something useful or interesting while everything is loading. By using the standard preload attribute, you (in theory) force your audio assets to load before the page loads. Because canvas apps are interactive and may require many more assets than those loaded when the page loads, we avoid the preload attribute and load the assets within the application.

Displaying Attributes on the Canvas

Now we are going to display the attribute values of an audio element playing on an HTML page. In this example (CH7EX3.html), we are also going to display the audio element in the HTML page so you can see the relationship between what is shown on the canvas and the state of the <audio> tag in the page.

In the drawScreen() function we will add the following code to display the attributes of the audioElement variable:

context.fillStyle = "#000000";
context.fillText  ("Duration:" + audioElement.duration,  20 ,20);
context.fillText  ("Current time:" + audioElement.currentTime,  20 ,40);
context.fillText  ("Loop: " + audioElement.loop,  20 ,60);
context.fillText  ("Autoplay: " +audioElement.autoplay,  20 ,80);
context.fillText  ("Muted: " + audioElement.muted,  20 ,100);
context.fillText  ("Controls: " + audioElement.controls,  20 ,120);
context.fillText  ("Volume: " + audioElement.volume,  20 ,140);
context.fillText  ("Paused: " + audioElement.paused,  20 ,160);
context.fillText  ("Ended: " + audioElement.ended,  20 ,180);
context.fillText  ("Source: " + audioElement.currentSrc,  20 ,200);
context.fillText  ("Can Play OGG: " + audioElement.canPlayType("audio/ogg"),  
                  20 ,220);
context.fillText  ("Can Play WAV: " + audioElement.canPlayType("audio/wav"),  
                  20 ,240);
context.fillText  ("Can Play MP3: " + audioElement.canPlayType("audio/mp3"),  
                  20 ,260);

You should already be familiar with most of these attributes. When you launch Example 7-3 (CH7EX3.html), play with the audio controls in the browser. You will notice that the changes are reflected by the attribute values displayed on the canvas. This is just our first step toward integrating audio with the canvas, but it should give you a good idea of how we will start to use audio elements and manipulate them through JavaScript.

Figure 7-3 shows what this application looks like when it is executed in a web browser.

Showing audio properties on the canvas

Figure 7-3. Showing audio properties on the canvas

There are also a few attributes displayed at the bottom of this list that we have not discussed. They all come from calls to the canPlayType() function of HTMLAudioElement. We are only displaying these right now, but in Example 7-3 we will make use of this function to help us decide which sound to dynamically load in JavaScript.

Example 7-3. Audio properties and the canvas

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH7EX3: Audio Properties And The Canvas</title>
<script src="modernizr-1.6.min.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
   var audioElement = document.getElementById("theAudio");
   audioElement.addEventListener("progress",updateLoadingStatus,false);
   audioElement.addEventListener("canplaythrough",audioLoaded,false);
   audioElement.load();

}

function canvasSupport () {
     return Modernizr.canvas;
}

function updateLoadingStatus() {
   var loadingStatus = document.getElementById("loadingStatus");
   var audioElement = document.getElementById("theAudio");
   var percentLoaded = parseInt(((audioElement.buffered.end(0) /
      audioElement.duration) * 100));
    document.getElementById("loadingStatus").innerHTML =   'loaded '  
      + percentLoaded + '%';

}

function audioLoaded() {

   canvasApp();

}

function canvasApp() {

  if (!canvasSupport()) {
          return;
        }

  function  drawScreen () {


      //Background
      context.fillStyle = "#ffffaa";
      context.fillRect(0, 0, theCanvas.width, theCanvas.height);
     
      //Box
      context.strokeStyle = "#000000";
      context.strokeRect(5,  5, theCanvas.width−10, theCanvas.height−10);

      // Text
      context.fillStyle  = "#000000";
      context.fillText  ("Duration:" + audioElement.duration,  20 ,20);
      context.fillText  ("Current time:" + audioElement.currentTime,  20 ,40);
      context.fillText  ("Loop: " + audioElement.loop,  20 ,60);
      context.fillText  ("Autoplay: " +audioElement.autoplay,  20 ,80);
      context.fillText  ("Muted: " + audioElement.muted,  20 ,100);
      context.fillText  ("Controls: " + audioElement.controls,  20 ,120);
      context.fillText  ("Volume: " + audioElement.volume,  20 ,140);
      context.fillText  ("Paused: " + audioElement.paused,  20 ,160);
      context.fillText  ("Ended: " + audioElement.ended,  20 ,180);
      context.fillText  ("Source: " + audioElement.currentSrc,  20 ,200);
      context.fillText  ("Can Play OGG: " + audioElement.canPlayType("audio/ogg"),  
                        20 ,220);
      context.fillText  ("Can Play WAV: " + audioElement.canPlayType("audio/wav"),  
                        20 ,240);
      context.fillText  ("Can Play MP3: " + audioElement.canPlayType("audio/mp3"),  
                        20 ,260);

   }

   var theCanvas = document.getElementById("canvasOne");
   var context = theCanvas.getContext("2d");
   var audioElement = document.getElementById("theAudio");
   audioElement.play();

   setInterval(drawScreen, 33);

}

</script>

</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">

<canvas id="canvasOne" width="500" height="300">
 Your browser does not support HTML5 Canvas.
</canvas>
</div>

<div id="loadingStatus">
0%
</div>

<div style="position: absolute; top: 50px; left: 600px; ">
<audio id="theAudio" controls >
<source src="song1.mp3" type="audio/mp3">
<source src="song1.ogg" type="audio/ogg">
<source src="song1.wav" type="audio/wav">

Your browser does not support the audio element.
</audio>

</div>
</body>
</html>

Note

This process is explained in detail in Chapter 6, where we warned that some browsers do not fire events for embedded <video> tags. That does not appear to be the case for <audio>, but it could happen in the future. We still believe the best bet for loading audio and video is the technique developed in the next section.

The best content for your career. Discover unlimited learning on demand for around $1/day.