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

Basic HTML5 Video Implementation

In the <video> tag’s most minimal implementation, it only requires a valid src atrribute. For example, if we took a nifty little video of the waves crashing at Muir Beach, California (just north of San Francisco), and we encoded it as an H.264 .mp4 file, the code might look like this:

<video src="muirbeach.mp4" />

Note

To see an example of this basic code, look at the CH6EX1.html file in the code distribution.

There are many properties that can be set in an HTML5 video embed. These properties are actually part of the HTMLMediaElement interface, implemented by the HTMLVideoElement object. Some of the more important properties include:

src

The URL to the video that you want to play.

autoplay

true or false. Forces the video to play automatically when loaded.

loop

true or false. Loops the video back to the beginning when it has finished playing (at the time of this writing, this did not work in Firefox).

volume

A number between 0 and 1. Sets the volume level of the playing video.

poster

A URL to an image that will be shown while the video is loading.

There are also some methods of HTMLVideoElement that are necessary when playing video in conjunction with JavaScript and Canvas:

play()

A method used to start playing a video.

pause()

A method used to pause a video that is playing.

Additionally, there are some properties you can use to check the status of a video, including:

duration

The length of the video in seconds.

currentTime

The current playing time of the video in seconds. This can be used in conjunction with duration for some interesting effects, which we will explore later.

ended

true or false, depending on whether the video has finished playing.

muted

true or false. Used to inquire whether the sound of the playing video has been muted.

paused

true or false. Used to inquire whether the video is currently paused.

Note

There are even more properties that exist for HTMLVideoElement. Check them out at http://www.w3.org/2010/05/video/mediaevents.html.

Plain-Vanilla Video Embed

To demonstrate a plain-vanilla embed, we are going to work under our previously established rules for video formats. We will use three formats because no one format will work in every browser. We have created a version of the Muir Beach video as a .webm, an .ogg, and a .mp4. For the rest of this chapter, we will use all three formats in all of our video embeds.

To support all three formats at once, we must use an alternative method for setting the src attribute of the <video> tag. Why? Because we need to specify three different video formats instead of one in our HTML page. To do this, we add <source> tags within the <video> tag:

<video id="thevideo"  width="320" height="240">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>

Note

We put the .mp4 file first in the src list because on certain iOS (iPhone, iPad) devices, the browser will not attempt to load any other src type than the first one listed. Since those devices support .mp4 files, we list them first to get the broadest support for HTML5 video.

When a web browser reads this HTML, it will attempt to load each video in succession. If it does not support one format, it will try the next one. Using this style of embed allows the code in Example 6-1 to execute on all HTML5-compliant browsers.

Also notice that we have set the width and height properties of the video. While these are not necessarily needed (as we saw earlier), it is proper HTML form to include them, and we will need them a bit later when we start to manipulate the video size in code.

Example 6-1. Basic HTML video

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH6EX1: Basic HTML5 Video</title>
</head>
<body>
<div>
<video id="thevideo"  width="320" height="240">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
<div>
(Right-click To Control)
</div>
</body>
</html>

Figure 6-1 is an example of the plain-vanilla video embed in an HTML5 page. There are no controls displayed in the default settings, but if you right-click on the video, controls will appear that can be used in conjunction with the embedded video.

HTML5 video embed

Figure 6-1. HTML5 video embed

Video with Controls, Loop, and Autoplay

While a video displayed without controls might suit your needs, most users expect to see some way to control a video. Also, as the developer, you might want a video to play automatically or loop back to the beginning when it finishes. All of these things (if supported in the browser) are very easy to accomplish in HTML5.

Adding controls, looping, and autoplay to an HTML5 video embed is simple. All you need to do is specify the options controls, loop, and/or autoplay in the <video> tag, like this:

<video autoplay loop controls id="thevideo" width="320" height="240">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>

Note

As of this writing, loop does not work in Firefox; however, support is expected in version 4.0.

The code to embed our Muir Beach video with controls, loop, and autoplay is in CH6EX2.html in the code distribution. Figure 6-2 shows what a video with controls looks like in Google Chrome.

HTML5 video embed with controls

Figure 6-2. HTML5 video embed with controls

You can see the full code in Example 6-2.

Example 6-2. HTML video with controls, loop, and autoplay

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH6EX2: Basic HTML5 Video With Controls</title>
</head>
<body>
<div>
<video autoplay loop controls id="thevideo" width="320" height="240">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
<div>
(Autoplay, Loop, Controls)
</div>
</body>
</html>

Altering the Width and Height of the Video

In our first example, we showed how you could embed a video without changing the default width or height. However, there are many good reasons why you might want to change the default width and height of a video in the HTML page, such as fitting it into a particular part of the page, or enlarging it so it is easier to see. Similar to embedding an image into HTML with the <img> tag, a video will scale to whatever width and height you provide in the <video> tag. Also, like with the <img> tag, this scale does not affect the size of the object downloaded. If the video is 5 megabytes at 640×480, it will still be 5 megabytes when displayed at 180×120—just scaled to fit that size.

In Example 6-3 (CH6EX3.html) we have scaled the same video to three different sizes and displayed them on the same page. Figure 6-3 shows what this looks like in HTML (again, rendered in the Google Chrome browser).

Example 6-3. Basic HTML5 video in three sizes

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH6EX3: Basic HTML5 Video: 3 Sizes</title>
</head>
<body>
<div>
<video autoplay loop controls  width="640" height="480" id="thevideo">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
</video>
</div>
<div>
(640×480)
<div>
<video  autoplay loop controls  width="320" height="240"id="thevideo">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
<div>
(320×240)
</div>
<div>
<video autoplay loop controls  width="180" height="120"id="thevideo">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
<div>
(180×120)
</body>
</html>
Controlling video width and height in the embed

Figure 6-3. Controlling video width and height in the embed

Dynamically scaling a video

Now it is time for a more elaborate (and we think more effective) example of scaling a video. By changing the width and height attributes of the <video> tag, we can scale the video on the fly. While there may be a few practical reasons you would do this in a real-world situation, it is also an effective way to demonstrate some of the power of the HTML5 <video> tag.

First, we need to add an HTML5 range control to the page:

<form>
 Video Size: <input type="range" id="videoSize"
       min="80"
       max="1280"
       step="1"
       value="320"/>
</form>

We discussed the details of the range control in Chapter 3, but just to refresh your memory, range is a new form control added to HTML5 that creates a slider of values. We are going to use this slider to set the video size.

Note

If the browser does not support the range element, a text box will appear that will allow the user to enter text directly.

To capture the change to the video size, we need to add some JavaScript. We create an event listener for the load event that calls the eventWindowLoaded() function when the page loads (this should look very familiar to you by now):

window.addEventListener('load', eventWindowLoaded, false);

We need to set up a couple things in the eventWindowLoaded() function. First, we need to add an event listener for a change to the videoSize form control we created in the HTML page. A “change” to the control (e.g., someone slides it right or left) will create an event handled by the videoSizeChanged() event handler:

var sizeElement = document.getElementById("videoSize")
sizeElement.addEventListener('change', videoSizeChanged, false);

Next, we need to create a value that can be used to set both the width and the height of the video at once. This is because we want to keep the proper aspect ratio of the video (the ratio of width to height) when the video is resized. To do this, we create the variable widthtoHeightRatio, which is simply the width of the video divided by the height:

var widthtoHeightRatio = videoElement.width/videoElement.height;

Finally, when the user changes the videoSize range control, the videoSizeChanged() event handler is called. This function sets the width property of the video to the value of the range control (target.value), then sets the height of the video to the same value, and divides by the widthtoHeightRatio value we just created. The effect is that the video resizes while playing. Figure 6-4 captures one moment of that:

function videoSizeChanged(e) {

      var target = e.target;
      var videoElement = document.getElementById("theVideo");
      videoElement.width = target.value;
      videoElement.height = target.value/widthtoHeightRatio;

   }
Controlling video width and height in JavaScript

Figure 6-4. Controlling video width and height in JavaScript

Example 6-4 offers the full code listing for this application.

Example 6-4. Basic HTML5 video with resize range control

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH6EX4: Basic HTML5 Video With Resize Range Control </title>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
   var sizeElement = document.getElementById("videoSize")
   sizeElement.addEventListener('change', videoSizeChanged, false);
   var videoElement = document.getElementById("theVideo");
   var widthtoHeightRatio = videoElement.width/videoElement.height;

function videoSizeChanged(e) {
      var target = e.target;
      var videoElement = document.getElementById("theVideo");
      videoElement.width = target.value;
      videoElement.height = target.value/widthtoHeightRatio;


   }

}

</script>
</head>
<body>
<div>
<form>
 Video Size: <input type="range" id="videoSize"
       min="80"
       max="1280"
       step="1"
       value="320"/>
</form>
  <br>
</div>
<div>
<video autoplay loop controls id="theVideo" width="320" height="240">
 <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
 <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
 <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
</body>
</html>

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