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

Text with Gradients and Patterns

We’ve already explored the fillColor and strokeColor properties of the Canvas context by setting those value to CSS-compliant colors. However, those very same properties can be set to refer to a few other objects defined in the Canvas API to create some stunning text effects. The objects are:

Linear gradient

A linear color gradient with two or more colors

Radial gradient

A circular color gradient with two or more colors

Image pattern

An Image object used as a fill pattern

Linear Gradients and Text

To create a linear gradient, make a call to the context’s createLinearGradient() method to create a Gradient object. The createLinearGradient() method accepts four parameters that all define the line of the linear gradient. The x0 and y0 parameters are the starting point of the line, and x1 and y1 represent the ending point of the line:

var gradient = context.createLinearGradient( [x0],[y0],[x1],[y1]);

For example, if you want to create a linear gradient that starts at the beginning of the text (located at 100,100), and has an endpoint that is the width of your text as displayed on the canvas, you might write the following code:

var metrics = context.measureText(message);
var textWidth = metrics.width;
var gradient = context.createLinearGradient(100, 100, textWidth, 100);

After you have created the line that represents the gradient, you need to add colors that will form the gradations of the gradient fill. This is done with the addColorStop() method, which requires two arguments: offset and color:


This is the offset on the gradient line to start the color gradation. The entire gradient is represented by the numbers between 0.0 and 1.0. The offset will be a decimal that represents a percentage.


A valid CSS color in the format “#RRGGBB”.

So, if you want black to be the first color in the gradient, and then red to be the second color that starts halfway down the gradient line, you would create two calls to addColorStop():

gradient.addColorStop(0, "#000000");
gradient.addColorStop(.5, "#FF0000");


If you fail to add colors with addColorStop(), the text will be rendered invisible.

The results are shown in Figure 3-9.

Text with linear gradient applied

Figure 3-9. Text with linear gradient applied

Radial Gradients and Text

A radial gradient is created much like a linear gradient, except that it represents a cone—not a line. The cone is created by defining the center points and the radii of two different circles when calling the createRadialGradient() function of the Canvas context:

var gradient = context.createRadialGradient([x0],[y0],[radius0],[x1],[y1],[radius1]);

Let’s say you want to create a radial gradient based on a cone. It starts with a circle that has its center point at 100,100 and a radius of 20, and ends at a circle with its center point at 200,100 and a radius of 5. The code would look like this:

var gradient = context.createRadialGradient(100,100,20,200,100,5);

Adding color stops to a radial gradient works the same as with a linear gradient, except the color moves along the cone instead of the line:

gradient.addColorStop(0, "#000000 ");
gradient.addColorStop(.5, "#FF0000");

Image Patterns and Text

Another option for filling text on HTML5 Canvas is to use an Image object. We will devote all of Chapter 4 to using the Image API, so here we will only discuss the basics of how to use one as a pattern for a text fill.

To create an image pattern, call the createPattern() method of the Canvas context, passing a reference to an Image object, and an option for repetition:

var pattern = context.createPattern([image], [repetition]);

A valid Image object that has been loaded with an image by setting the pattern.src property and waiting for the image to load by setting an event listener for the Image onload event. The Canvas specification also allows for a video element or another <canvas> to be used here as well.


The “tiling” of the image. This can have one of four values:


The image is tiled on both the x and y axes.


The image is tiled only on the x-axis (horizontally).


The image is tiled only on the y-axis (vertically).


The image is not tiled.

To use the image pattern, apply it to the fillColor and strokeColor properties of the context, just as you would apply a color:

context.fillStyle = pattern;


context.strokeStyle = pattern;

For example, to load an image named texture.jpg and apply it to the fillStyle so that it tiles on both the x and y axes, you would write code like this:

var pattern = new Image();
pattern.src = "texture.jpg"
pattern.onload = function() {
 var pattern = context.createPattern("texture.jpg", "repeat");
 context.fillStyle = pattern;

Handling Gradients and Patterns in Text Arranger

Text Arranger 3.0 includes many changes that were implemented to support using gradients and image patterns with text on HTML5 Canvas. To see these changes in action, we first need to make sure that we have preloaded the texture.jpg image, which we will use for the context.createPattern() functionality. To do this, we will create a new function named eventAssetsLoaded() that we will set as the event handler for the onload event of the Image object that will hold the pattern. When that image has loaded, we will call canvasApp() in the same way we called it from eventWindowLoaded():

function eventWindowLoaded() {
   var pattern = new Image();
   pattern.src = "texture.jpg";
   pattern.onload = eventAssetsLoaded;

function eventAssetsLoaded() {



We are not going to use the pattern variable we created in this function, as it does not have scope in the canvasApp() function. We are merely using it to make sure that the image is available before we use it.

In the canvasApp() function, we will create three variables to support this new functionality. fillType describes how the text will be filled (a regular color fill, a linear gradient, a radial gradient, or a pattern). The textColorFill2 variable is the second color we will use for the gradient color stop. Finally, the pattern variable holds the Image object we preloaded, which we now need to create an instance of in canvasApp():

var fillType = "colorFill";
var textFillColor2 = "#000000";
var pattern = new Image();
pattern.src = "texture.jpg";

Now, let’s jump to the HTML of our <form>. Since we have created different ways to fill the text we are displaying, we need to build a selection that allows for this choice. We will create a <select> box with the id of fillType for this purpose:

Fill Type: <select id="fillType">
  <option value="colorFill">Color Fill</option>
  <option value="linearGradient">Linear Gradient</option>
  <option value="radialGradient">Radial Gradient</option>
  <option value="pattern">pattern</option>

We need to add a second color selection that we can use for the gradient fills. We will use the jsColor picker and the id textColorFill2:

Text Color 2: <input class="color" id="textFillColor2" value ="000000"/>

Back in canvasApp(), we need to create the event listeners for our two new form elements:

   formElement = document.getElementById("textFillColor2");
   formElement.addEventListener('change', textFillColor2Changed, false);

   formElement = document.getElementById("fillType");
   formElement.addEventListener('change', fillTypeChanged, false);

We also need to create the associated event handler functions for the new form elements:

function textFillColor2Changed(e) {
      var target =;
      textFillColor2 = "#" + target.value;

   function fillTypeChanged(e) {
      var target =;
      fillType = target.value;

We need to add support to drawScreen() for this new functionality. First, we use the measureText() method of the context to get the width of the text, which we will use to create the gradients:

var metrics = context.measureText(message);
var textWidth = metrics.width;

Then, we need to decide how to format our “color” for the fillStyle or strokeStyle of the context. In this instance, it can be a CSS color, a gradient, or an image pattern; the list below provides more information.

Color fill

If we are doing a simple color fill, we operate just like in previous versions of Text Arranger. All we need to do is make tempColor equal to the value of y.

Linear gradient

For the linear gradient, we need to decide what line we are going to create for the gradient. Our line will start at the beginning of the text (xPosition-textWidth/2 because the text uses the center alignment), and runs horizontally to the end of the text (textWidth). We also add two color stops (at 0 and 60%)—the colors are textFillColor1 and textFillColor2.

Radial gradient

For the radial gradient, we are going to create a cone that starts at the center of the text (xPosition,yPosition) with a radius the size of the font (fontSize). The cone will extend horizontally the width of the text (textWidth) with a radius of 1.


For this option, we create a pattern using the pattern image variable we previously created. We designate it to repeat so it will tile horizontally and vertically.

Here’s the code:

var tempColor;
if (fillType == "colorFill") {
   tempColor = textFillColor;
} else if (fillType == "linearGradient") {
   var gradient = context.createLinearGradient(xPosition-
       textWidth/2, yPosition, textWidth, yPosition);
   tempColor = gradient;
} else if (fillType == "radialGradient") {
   var gradient = context.createRadialGradient(xPosition, yPosition, 
       fontSize, xPosition+textWidth, yPosition, 1);
   tempColor = gradient;
} else if (fillType == "pattern") {
  var tempColor = context.createPattern(pattern,"repeat");
} else {
   tempColor = textFillColor;

Now, when we set our fillStyle or strokeStyle, we use tempColor instead of textFillColor. This will set the proper text fill choice that will be displayed on the canvas, as shown in Figure 3-10:

context.fillStyle = tempColor;
Text with image pattern applied

Figure 3-10. Text with image pattern applied

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