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

Text and the Canvas Context

We’ve already discussed a couple Canvas context properties that affect the canvas in a global fashion: fillStyle and strokeStyle. However, there are two areas that visually demonstrate how changes to the properties of the context can affect the entire HTML5 Canvas: alpha transparencies and shadows.

Global Alpha and Text

Using alpha is a cool way to make objects seem to be partially or fully transparent on HTML5 Canvas. The globalAlpha property of the Canvas context is used for this purpose. After globalAlpha is applied, it affects all drawing on the canvas, so you need to be careful when setting it.

The valid values for context.globalAlpha are numbers between 0.0 (transparent) and 1.0 (opaque), and they act as a percentage for the alpha value. For example, a 50% alpha value would be coded like this:

context.globalAlpha = 0.5;

A 100% alpha (no transparency) would be coded like this:

context.globalAlpha = 1.0;

Handling globalAlpha transparencies

Besides the now-familiar elements that we included for most of the other configurable options in Text Arranger, the globalAlpha property requires us to think a bit more about when we use it and how it will affect the rest of the canvas.

First, we create a variable named textAlpha in the canvasApp() function and initialize it with 1, which means the text will have no transparency when it is first displayed:

var textAlpha = 1;

Next, in the drawImage() function, we need to set the globalAlpha property twice: once before we draw the background and the bounding box frame…

function drawScreen() {

      context.globalAlpha = 1;

…and then again to the value stored in textAlpha, just before rendering the text to the canvas:

      context.globalAlpha = textAlpha;

This will reset globalAlpha so we can draw the background, but it will still allow us to use a configurable alpha value for the displayed text.

We will use another HTML5 range control in our form, but this time we set the value range with a min of 0.0 and a max of 1.0, stepping 0.01 every time the range is moved:

Alpha: <input type="range" id="textAlpha"

The textAlphaChanged() function works just like the other event handler functions we created in this chapter:

function textAlphaChanged(e) {
      var target =;
      textAlpha = (target.value);

Also, don’t forget the event listener for the textAlpha range control:

formElement = document.getElementById("textAlpha");
formElement.addEventListener('change', textAlphaChanged, false);

The results will look like Figure 3-7.

Text with globalAlpha applied

Figure 3-7. Text with globalAlpha applied

Global Shadows and Text

HTML5 Canvas includes a unique set of properties for creating a shadow for drawings. The context.shadow functions are not unique to text, but they can make some very good text effects with very little effort.

To create a shadowEffect, there are four properties of the Canvas context that need to be manipulated:


The color of the shadow. This uses the same “#RRGGBB” format of the fillStyle and strokeStyle properties.


The x offset of shadow. This can be a positive or negative number.


The y offset of shadow. This can be a positive or negative number.


The blur filter diffusion of the shadow. The higher the number, the more diffusion.

For example, if you want to create a red shadow that is 5 pixels to the right and 5 pixels down from your text, with a blur of 2 pixels, you would set the properties like this:

context.shadowColor = "#FF0000";
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 2;

Handling global shadows

Just like we saw with globalAlpha, we must reset the shadow properties before we draw the background for textArranger; otherwise, the shadow will apply to the entire image. First, in the canvasApp() function, we create a set of variables to hold the shadow values:

var textAlpha = 1;
var shadowX = 1;
var shadowY = 1;
var shadowBlur = 1;
var shadowColor = "#707070";

We then make sure to turn off the shadow before we render the background for textArranger in the drawScreen(). We don’t have to reset the shadowColor, but we think it is good practice to update all the relative properties relating to any global change to the Canvas context:

context.shadowColor = "#707070";
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;

Later in drawScreen(), we render the shadow based on the settings in the four variables we created:

context.shadowColor = shadowColor;
context.shadowOffsetX = shadowX;
context.shadowOffsetY = shadowY;
context.shadowBlur = shadowBlur;

We also need to create the HTML to allow the user to update the shadow settings. We do this with three range controls, as well as another color picker using jsColor:

Shadow X:<input type="range" id="shadowX"
Shadow Y:<input type="range" id="shadowY"
Shadow Blur: <input type="range" id="shadowBlur"
       value="1" />
Shadow Color: <input class="color" id="shadowColor" value="707070"/>

Finally, we need to add the event listeners and event handler functions so the HTML form elements can communicate with the canvas. See the results in Figure 3-8:

formElement = document.getElementById("shadowX");
formElement.addEventListener('change', shadowXChanged, false);

formElement = document.getElementById("shadowY");
formElement.addEventListener('change', shadowYChanged, false);

formElement = document.getElementById("shadowBlur");
formElement.addEventListener('change', shadowBlurChanged, false);

formElement = document.getElementById("shadowColor");
formElement.addEventListener('change', shadowColorChanged, false);
function shadowXChanged(e) {
      var target =;
      shadowX = target.value;

   function shadowYChanged(e) {
      var target =;
      shadowY = target.value;

   function shadowBlurChanged(e) {
      var target =;
      shadowBlur = target.value;

   function shadowColorChanged(e) {
      var target =;
      shadowColor = target.value;
Text with global shadow applied

Figure 3-8. Text with global shadow applied

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