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

HTML5 Canvas “Hello World!”

As we just mentioned, one of the first things we need to do when putting Canvas on an HTML5 page is test to see whether the entire page has loaded and all HTML elements are present before we start performing any operations. This will become essential when we start working with images and sounds in Canvas.

To do this, you need to work with events in JavaScript. Events are dispatched by objects when a defined event occurs. Other objects listen for events so they can do something based on the event. Some common events that an object in JavaScript might listen for are key presses, mouse movements, and when something has finished loading.

The first event we need to listen for is a window object’s load event, which occurs when the HTML page has finished loading.

To add a listener for an event, use the addEventListener() method that belongs to objects that are part of the DOM. Because window represents the HTML page, it is the top level of the DOM.

The addEventListener() function accepts three arguments:

Event: load

This is the named event for which we are adding a listener. Events for existing objects like window are already defined.

Event handler function: eventWindowLoaded()

Call this function when the event occurs. In our code, we will then call the canvasApp() function, which will start our main application execution.

useCapture: true or false

This sets the function to capture this type of event before it propagates lower in the DOM tree of objects. We will always set this to false.

Below is the final code we will use to test to see whether the window has loaded:

window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
   canvasApp();
}

Alternatively, you can set up an event listener for the load event in a number of other ways:

window.onload = function()
   {
      canvasApp();
   }

or:

window.onload = canvasApp();

We will use the first method throughout this book.

Encapsulating Your JavaScript Code for Canvas

Now that we have created a way to test to see whether the HTML page has loaded, we can start creating our JavaScript application. Because JavaScript runs in an HTML page, it could be running with other JavaScript applications and code simultaneously. Usually, this does not cause any problems. However, there is a chance that your code might have variables or functions that conflict with other JavaScript code on the HTML page.

Canvas applications are a bit different from other apps that run in the web browser. Because Canvas executes its display in a defined region of the screen, its functionality is most likely self-contained, so it should not interfere with the rest of the page, and vice versa. You might also want to put multiple Canvas apps on the same page, so there must be some kind of separation of JavaScript when defining the code.

To avoid this issue, you can encapsulate your variables and functions by placing them inside another function. Functions in JavaScript are objects themselves, and objects in JavaScript can have both properties and methods. By placing a function inside another function, you are making the second function local in scope to the first function.

In our example, we are going to have the canvasApp() function that is called from the window load event contain our entire Canvas application. This “Hello World!” example will have one function named drawScreen(). As soon as canvasApp() is called, we will call drawScreen() immediately to draw our “Hello World!” text.

The drawScreen() function is now local to canvasApp(). Any variables or functions we create in canvasApp() will be local to drawScreen(), but not to the rest of the HTML page or other JavaScript applications that might be running.

Here is the sample code for how we will encapsulate functions and code for our Canvas applications:

function canvasApp() {
   drawScreen();

   ...

   function drawScreen() {

        ...

   }

}

Adding Canvas to the HTML Page

In the <body> section of the HTML page, add a <canvas> tag using code such as the following:

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

Now, let’s break this down to understand what we are doing. The <canvas> tag has three main attributes. In HTML, attributes are set within pointy brackets of an HTML tag. The three attributes we need to set are:

id

The id is the name we will use to reference this <canvas> tag in our JavaScript code. canvasOne is the name we will use.

width

The width, in pixels, of the canvas. The width will be 500 pixels.

height

The height, in pixels, of the canvas. The height will be 300 pixels.

Note

HTML5 elements, including canvas, have many more attributes: tabindex, title, class, accesskey, dir, draggable, hidden, etc.

Between the opening <canvas> and closing </canvas> tags, you can put text that will be displayed if the browser executing the HTML page does not support Canvas. For our Canvas applications, we will use the text “Your browser does not support HTML5 Canvas.” However, you can adjust this text to say anything.

Using document to reference the canvas element in JavaScript

We will now make use of the DOM to reference the <canvas> we defined in HTML. Recall that the document object represents every element of an HTML page after it has loaded.

We need a reference to the Canvas object so that we will know where to display the Canvas API calls we will make from JavaScript.

First, we will define a new variable named theCanvas that will hold the reference to the Canvas object.

Next, we retrieve a reference to canvasOne by calling the getElementById() function of document, and passing the name canvasOne, which we defined as the id of the <canvas> tag we created in the HTML page:

var theCanvas = document.getElementById("canvasOne");

Testing to See Whether the Browser Supports Canvas

Now that we have a reference to the canvas element on the HTML page, we need to test to see whether it contains a context. The Canvas context refers to the drawing surface defined by a web browser to support Canvas. Simply put, if the context does not exist, neither does the canvas. There are several ways to test this. This first test looks to see whether the getContext method exists before we call it using Canvas, as we have already defined it in the HTML page:

if (!theCanvas || !theCanvas.getContext) {
   return;
}

Actually, this tests two things. First, it tests to see whether theCanvas does not contain false (the value returned by document.getElementById() if the named id does not exist). Then, it tests whether the getContext() function exists.

The return statement breaks out and stops execution if the test fails.

Another method—popularized by Mark Pilgrim on his HTML5 website, http://diveintohtml5.org—uses a function with a test of a dummy canvas created for the sole purpose of seeing whether browser support exists:

function canvasSupport () {
    return !!document.createElement('testcanvas').getContext;
}
function canvasApp() {
   if (!canvasSupport) {
      return;
  }

}

Our favorite method is to use the modernizr.js library, which you can find here: http://www.modernizr.com/. Modernizr—an easy-to-use, lightweight library for testing support for various web-based technologies—creates a set of static Booleans that you can test against to see whether Canvas is supported.

To include modernizr.js in your HTML page, download the code from http://www.modernizr.com/ and then include the external .js file in your HTML page:

<script src="modernizr-1.6.min.js"></script>

To test for Canvas, change the canvasSupport() function to look like this:

function canvasSupport () {
   return Modernizr.canvas;
}

We are going to use the modernizr.js method because we think it offers the best approach for testing whether Canvas is supported in web browsers.

Retrieving the 2D Context

Finally, we need to get a reference to the 2D context so we can manipulate it. HTML5 Canvas is designed to work with multiple contexts, including a proposed 3D context. However, for the purposes of this book, we only need to get the 2D context:

var context = theCanvas.getContext("2d");

The drawScreen() Function

It’s time to create actual Canvas API code. Every operation we perform on Canvas will be through the context object, as it references the object on the HTML page.

We will delve into writing text, graphics, and images to HTML5 Canvas in later chapters, so for now, we will only spend a very short time on the code of the drawScreen() function.

The “screen” here is really the defined drawing area of the canvas, not the whole browser window. We refer to it as such because within the context of the games and applications you will write, it is effectively the “window” or “screen” into the canvas display that you will be manipulating.

The first thing we want to do is clear the drawing area. The following two lines of code draw a yellow box on the screen that is the same size as the canvas. fillStyle() sets the color, and fillRect() creates a rectangle and puts it on the screen:

context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);

Note

Notice that we are calling functions of the context. There are no screen objects, color objects, or anything else. This is an example of the immediate mode we described earlier.

Again, we will discuss the text functions of Canvas in the next chapter, but here is a short preview of the code we will use to put the text “Hello World!” on the screen.

First, we set the color of the text in the same way we set the color of the rectangle:

context.fillStyle  = "#000000";

Then we set the font size and weight:

context.font = "20px _sans";

Next, we set the vertical alignment of the font:

context.textBaseline = "top";

Finally, we print our test on the screen by calling the fillText() method of the context object. The three parameters of this method are text string, x position, and y position:

context.fillText  ("Hello World!", 195, 80);

Let’s add some graphics to our “Hello World!” text. First, let’s load in an image and display it. We will dive into images and image manipulation in Chapter 4, but for now, let’s just get an image on the screen. To display an image on the canvas, you need to create an instance of the Image() object, and set the Image.src property to the name of the image to load.

Note

You can also use another canvas or a video as the image to display. We will discuss these topics in Chapters 4 and 6.

Before you display it, you need to wait for the image to load. Create a callback() function for the Image load event by setting the onload function of the Image object. callback() will be executed when the onload event occurs. When the image has loaded, you then call context.drawImage(), passing three parameters to put it on the canvas: Image object, x position, and y position:

var helloWorldImage = new Image();
helloWorldImage.src = "helloworld.gif";
helloWorldImage.onload = function () {
   context.drawImage(helloWorldImage, 160, 130);
}

Finally, let’s draw a box around the text and the image. To draw a box with no fill, use the context.StrokeStyle() method to set a color for the stroke (the border of the box), and then call the context.strokeRect() method to draw the rectangle border. The four parameters for the strokeRect() method are the upper left x and y coordinates, and the lower right x and y coordinates:

context.strokeStyle = "#000000";
context.strokeRect(5,  5, 490, 290);

The full code for the HTML5 Hello World! application is shown in Example 1-3, and its results are illustrated in Figure 1-3.

Example 1-3. HTML5 Canvas Hello World!

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH1EX3: Your First Canvas Application </title>
<script src="modernizr-1.6.min.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);

var Debugger = function () { };
Debugger.log = function (message) {
   try {
      console.log(message);
   } catch (exception) {
      return;
   }
}

function eventWindowLoaded () {
   canvasApp();
}

function canvasSupport () {
    return Modernizr.canvas;
}

function canvasApp () {

        if (!canvasSupport()) {
          return;
        }

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

      Debugger.log("Drawing Canvas");

        function drawScreen() {
         //background
         context.fillStyle = "#ffffaa";
         context.fillRect(0, 0, 500, 300);

         //text
         context.fillStyle  = "#000000";
         context.font = "20px _sans";
         context.textBaseline = "top";
         context.fillText  ("Hello World!", 195, 80 );

         //image
         var helloWorldImage = new Image();
         helloWorldImage.src = "helloworld.gif";
         helloWorldImage.onload = function () {
            context.drawImage(helloWorldImage, 160, 130);
         }

         //box
         context.strokeStyle = "#000000";
         context.strokeRect(5,  5, 490, 290);

      }

      drawScreen();

}

</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>
</body>
</html>
HTML5 Canvas Hello World!

Figure 1-3. HTML5 Canvas Hello World!

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