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

Creating the iOS Application with PhoneGap

You will need to install and set up two tools to get an iOS application up and running on your iOS device simulator: Xcode, a free application development IDE from Apple, and PhoneGap. Let’s start with Xcode.

Installing Xcode

Xcode actually comes packaged on the installable operating system DVD for Snow Leopard, but this version will not be as up-to-date as the version available on the Apple developer website.

First, you will want to visit the iOS Developer Center: Once there, you can create a free user account, which you will need to download Xcode and the latest iOS developer SDK. You will also need to create a paid account if you would like to test or deploy on a physical device and/or sell your application in the iTunes Store. You do not need a paid account to build and test your application in the SDK and the included iOS device simulators.

Download and install the latest version of Xcode and the iOS SDK. This is a large download (3.5 GB at the time of this writing). See Figure 10-2.

Download the iOS SDK

Figure 10-2. Download the iOS SDK

Once these are downloaded (most likely to your Downloads folder), start the Xcode installer. The file will be named similar to xcode_3.2.3_and_ios_sdk_4.0.2.dmg. Run the package installer to set up Xcode and the development kit on your computer.


Once installed (using the default location), Xcode can be found in the Developer folder on your main storage drive.

Installing PhoneGap

Download PhoneGap from, choosing the ZIP file option, as shown in Figure 10-3.

The file will most likely be saved into your Mac Downloads folder. Unpack this ZIP file in a safe location, such as the desktop.

Inside the ZIP, you will find a series of folders for various devices. We are interested in the iOS folder. Figure 10-4 illustrates this folder structure.

Download PhoneGap

Figure 10-3. Download PhoneGap

PhoneGap folder structure

Figure 10-4. PhoneGap folder structure

In the iOS folder there will be an installer with a name similar to PhoneGapLibInstaller.pkg. Open this to start the install process.

After the install, you will be given the latest install notes. It is important to read them carefully as they give great information, including the latest tips for getting started with PhoneGap. For example, after this installation, the notes read as follows:

To get started creating PhoneGap projects, launch Xcode, then under the File menu, select “New Project…”.

Navigate to the section “User Templates”, select PhoneGap, then in the right pane, select “PhoneGap-based Application”.

Select the “Choose…” button, name your project and choose the location where you want the new project to be.

That’s it! Modify the contents of the “www” directory to add your HTML, CSS and JavaScript.


Go to your project folder and launch the “[projectname]-iPad” Xcode project. You will need the 3.2 iPhone OS SDK.

In the next section, we will follow these directions closely to get BS Bingo into a PhoneGap Xcode project.

Creating the BS Bingo PhoneGap Project in Xcode

To begin, launch Xcode and create a new PhoneGap project. See Figure 10-5 for an example of the New Project screen.

Select the PhoneGap-based application and click the Choose button.

You will next be asked to save the project in a location and give it a name. We will use the name chapter10_bs_bingo.

You will be presented with a screen that resembles Figure 10-6.

On the lefthand side, you will find a folder called “www”. This is the most important folder because it is where we will place all of the files for our game. Before we do that, we need to make sure that the SDK is set to the correct version. In the top left, you might see a drop-down with the words “Base SDK Missing” (as shown in Figure 10-6). This means that we will not be able to build and compile our game until we choose an SDK.

Xcode New Project screen

Figure 10-5. Xcode New Project screen

The chapter10_bs_bingo project

Figure 10-6. The chapter10_bs_bingo project

The Base SDK Missing message simply indicates that the default SDK is not the current version installed. In the [Project] drop-down menu, you will find a menu item called Edit Project Settings. Click this and you will see a screen similar to Figure 10-7.

Select the correct Base SDK

Figure 10-7. Select the correct Base SDK

Make sure that you select an SDK that is present on your machine (4.2 is the latest as of this writing).

Close this window and click on the Base SDK Missing drop-down, and be sure to select the Simulator option rather than the Device option. See Figure 10-8 for an example of this screen.

Testing the New Blank Application in the Simulator

We are now ready to build our first application and see it in the simulator. We have not added any of our own code yet (though we will in the next section), so we will be testing the contents of the index.html file in the project’s www folder. Simply click the “Build and Run” button at the top of the IDE. If everything is set up properly, the simulator will come up with a blank screen, as shown in Figure 10-9.

Setting up an app to run in the simulator

Figure 10-8. Setting up an app to run in the simulator

A basic app running in the simulator

Figure 10-9. A basic app running in the simulator

For a single second you will see the PhoneGap banner show up on the screen. We will customize this banner for our own game shortly.

Integrating BS Bingo into the Project

We are now going to copy code from the BSBingo.html file we created earlier into the index.html file in our project.

First we will copy our JavaScript include files and add them under the phonegap.js script include. We will not need the modernizer.js file, as we will assume the iOS platform can use HTML5 Canvas:

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script src="TextButton.js"></script>
<script src="ConsoleLog.js"></script>

The phonegap.js file should already be included in the www folder, along with index.html. It is part of the project template and is needed for all PhoneGap iOS applications.

Next, we will need to add the call to start our application into the deviceReady() function:

/*When this function is called, PhoneGap has been initialized and is ready to roll*/
   function onDeviceReady()
      // do your thing!

We can now replace the rest of the script code in the file with our code.


At this step, don’t replace from the <body> tag down to the end of the <html>. Just add the game code inside the <script> tags. You can use the existing <script></script> tags; if you do, be careful not to copy them from BSBingo.html.

Make sure that the first few lines look like this because we are removing the check for Canvas support:

function canvasApp(){

   theCanvas = document.getElementById("canvas");
   context = theCanvas.getContext("2d");
   var bingoCard = [];

   var buttons = [];

   var standardJargonList = [];

   var tempButton = {};

   var clickSound;

Notice that we have removed this set of code:

if (!canvasSupport()) {


    theCanvas = document.getElementById("canvas");

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


We have replaced it with just the following since we no longer need to check whether the device can use the canvas (we must assume it can):

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

We have also deleted the canvasSupport() function, as it is not needed. We will next copy the rest of the code, including our HTML, and replace everything in the index.html file.

We need to make sure that the current opening <body> tag remains in index.html. It should look like this:

<body onload="onBodyLoad()">

The next step is to replace the rest of the file with HTML code from BSBingo.html:

<div style="position: absolute; top: 0px; left: 0px;">
<canvas id="canvas" width="570" height="418">

 Your browser does not support HTML5 Canvas.


<audio id ="clicksound"  preload="auto">
<source src="click.mp3" type="audio/mpeg" />

Your browser does not support the audio element.

We now have enough code to do a preliminary test of our game in the simulator.

We will first need to move our files into the project folder. Take TextButton.js, ConsoleLog.js, and click.mp3 and move them to the www folder on the disk. The project in Xcode will now reflect the new files, as seen in Figure 10-10.

The project www file listing

Figure 10-10. The project www file listing


You will see that we have added the BSBingo.html file to the www folder. This is not necessary, but it makes it easier to edit and copy code into the index.html file.

Setting the Orientation

It is important to note that Safari Mobile and iOS applications render the screen in different ways. A Safari Mobile application can be set to automatically scale to fit in the iOS device’s window, while a pure iOS application needs to be coded to fit the size of the target device. If an application targeted to the iOS platform is taller or wider than the device, the application will automatically be put into “scroll” mode.

We set the width of our application to be 570 and the height to be 418. The height will fit fine in either Landscape or Portrait orientation, but the width will only fit in Landscape (without scrolling). For this reason, we will want our application to run in Landscape mode only.

To set the application to default to Landscape and not allow Portrait, we must make some changes to a file called chapter10_bs_bingo-info.plist, which is in the root folder (the parent of the www folder) for our project.

Open this file and you will see settings called “Supported interface orientations” and “Supported interface orientations (iPad)”. You will want to be sure to have four entries in each that allow only the “Landscape (left home button)” value. See Figure 10-11 for an example.


The iPad entries are only necessary if you are targeting that platform. There is a separate PhoneGap project created by the template for iPad-targeted projects.

Setting Landscape orientation

Figure 10-11. Setting Landscape orientation

Next, we will customize the banner and icon for our application.

Changing the Banner and Icon

We have the option of changing the startup banner and “desktop” icon for our application to customized graphics.

In the root folder of our project, we will customize two image files. default.png is the banner image that shows up when the application starts. icon.png is the “desktop” icon that remains on the iOS device just like any other installed application.

Our icon is a 57×75 image called bingo_icon.png (see Figure 10-12).

The BS Bingo icon.png customization

Figure 10-12. The BS Bingo icon.png customization

The startup banner is a 320×460 image, which we will name startup.png. It will look like Figure 10-13.

The BS Bingo default.png customization

Figure 10-13. The BS Bingo default.png customization

Now we need to replace the existing default.png and icon.png files with these new images.

Once you change these files in the project, you should be able to explore the root project folder in Xcode and see the new images. Figure 10-14 illustrates the root folder for our project.

The BS Bingo root folder

Figure 10-14. The BS Bingo root folder


Included in the source for this chapter is the full Xcode project with all of these changes ready to be made and compiled.

We are ready to test on the iPhone simulator. If you have any problems or questions up to this point, you can always examine the source files on this book’s download site.

Testing on the Simulator

Our project is set to target the iPhone (not iPad). Before we test, we must make sure that we target that platform in the simulator. To do this, choose the iPhone simulator from the SDK drop-down menu at the top left of the Xcode screen, as shown in Figure 10-15.

Setting the build target to the simulator

Figure 10-15. Setting the build target to the simulator


The PhoneGap template has created a second project file, called chapter10_bs_bingo-iPad.xcodeproj, to target the iPad.

Once this is set, click on the “Build and Run” icon at the top center of this screen.

You should see the simulator fire up, show the custom banner image oriented to Landscape mode, and present the game, as shown in Figure 10-16.

If you click on the buttons, the simulator will even play the click.mp3 file we included. When the iPhone “control button” is clicked (the big black circle on the left), the game will exit to the iOS “desktop.” On the desktop, the custom icon.png will wait to be clicked once again, as shown in Figure 10-17.

BS Bingo running in the simulator

Figure 10-16. BS Bingo running in the simulator

The BS Bingo iOS desktop icon

Figure 10-17. The BS Bingo iOS desktop icon


You will notice that the iPhone simulator has made our plain icon look much better by adding a bevel and highlighting. There is no need for you to create anything other than a plain image, as the phone takes care of the rest.

Adding in an iPhone “Gesture”

The PhoneGap API allows us to add in control over various iOS features, such as vibrate, geolocation, and accelerometer. We will target one of these features by adding code that will wipe our board clean and create a fresh new game when the phone is shaken.

To do this, we will look for changes to the device’s physical location in space (using JavaScript), and then simply call our existing chooseButtonsForCard() and drawScreen() functions to refresh the card.

First, we need to add a single line to the chooseButtonsForCard() function that will set all the buttons instances’ press attributes to false:

function chooseButtonsForCard(){
      //copy jargon into temp array
      var tempArray = [];
      for (var arrayctr=0;arrayctr<standardJargonList.length;arrayctr++){

      for (var ctr1=0;ctr1<buttons.length;ctr1++){

         for (var ctr2=0; ctr2<buttons[ctr1].length;ctr2++){
            var randInt = Math.floor(Math.random()*tempArray.length)
            buttons[ctr1][ctr2].text = tempArray[randInt];
            buttons[ctr1][ctr2].press = false;


Next, we need to add a function that will listen for the iOS “shake” event, and then refresh the card.

Apple makes it pretty easy to test for changes in the x, y, and z coordinate spaces of an iOS device (and PhoneGap makes it even easier), but acting on this information is a little tricky and will require the use of an actual device for testing.


At the time of this writing, a PhoneGap Adobe AIR iPhone simulator was available that goes beyond the limited shake gestures available in the SDK simulator. If you do not have a device to test with, we recommend trying this emulator. It can be found at

Adding the Gesture Functions to index.html

Inside the canvasApp() function, we will need to add a series of functions and a variable to use in testing the iPhone’s accelerometer, which detects movement in our application.

Example 10-2 shows the code necessary to do this. Notice we are placing it under the current application start code (the new code is in bold).

Example 10-2. The gesture code added to BS Bingo

   theCanvas.addEventListener("mousemove", onMouseMove, false);
   theCanvas.addEventListener("click", onMouseClick, false);

   var accelerationWatchId = null;


   function startAccelerationWatch() {

        // Update acceleration every 3 seconds
        var options = { frequency: 100 };

        accelerationWatchId = navigator.accelerometer.watchAcceleration
        (onSuccess, onError, options);

    function stopAccelerationWatch() {
        if (accelerationWatchId) {
            accelerationWatchIdD = null;

   function onSuccess(acceleration) {

        if (Math.abs(acceleration.x) > 2 || Math.abs(acceleration.y)>2 
         || Math.abs(acceleration.z)>2) {
         alert('Acceleration X: ' + acceleration.x + '\n' +
             'Acceleration Y: ' + acceleration.y + '\n' +
             'Acceleration Z: ' + acceleration.z + '\n' +
             'Timestamp: '      + acceleration.timestamp + '\n');


    // onError: Failed to get the acceleration
    function onError() {

The new code begins with the var accelerationWatchId = null; variable setting. We have created a startAccelerationWatch() function, which will call the onSuccess() function every 100 milliseconds.

The onSuccess() function receives the “acceleration” values from the API, which consist of delta changes to the x, y, and z of the device. These values are set to 0,0,0 when the application begins.

On each 100-millisecond interval, these values are checked. If any is 2 units greater (in either the positive or negative direction) from the 0 beginning values, we fire off an alert and then call our functions to reset the card. First, we call the stopAccelerationWatch() function, which acts as a reset for the location of the device in physical space. Next, we call the chooseButtonsForCard() and drawScreen() functions. Finally, we set up the watch again with startAccelerationWatch().


For the most detailed and up-to-date information on integrating PhoneGap with iOS and other device features, visit the PhoneGap documentation website. Most of the information for this example is based off the explanation and examples found at

Testing on a Device

Before we can test the application on an actual device, we need to “provision” the device. To do this, we will need the device, a paid iOS developer account, and a development Mac computer all synced up into a single provisioning profile. This necessary process is not for the faint of heart.

Step 1: Launch the Provisioning Assistant

Begin by visiting the Developer Provisioning Assistant ( and logging in with your paid iOS developer ID. Once logged in, click on the link for the “iOS Provisioning Portal” (currently in the upper-right side menu). There should be a button called “Launch the Provisioning Assistant.” Click on this button and follow all the on-screen instructions.

Step 2: Find the device’s Unique ID

You will be asked to find the Unique ID of your physical device. This is found by plugging the device into your computer, and then looking up the ID in Xcode. In the WindowOrganizer Information window, you will see a list of the attached devices. The ID will be a long alphanumeric string next to the word Identifier.

Step 3: Generate a Certificate Signing Request

When asked by the Provisioning Assistant, input this ID value. You will next be asked to “Generate a Certificate Signing Request”, which involves the Apple Keychain. Follow all the on-screen dialogs carefully because this can be a confusing process. You will need to open the Keychain Access application in the ApplicationsUtilities folder on your machine, and then follow the on-screen instructions from the Provisioning Assistant.

Step 4: Locate saved Certificate Signing Request File

This will save a Certificate Signing Request File to your desktop. In the next step, the Provisioning Assistant will need to find this file, so it is important to remember where you save the request.

After you find the file, the assistant will ask you to name your profile. This will generate a file that you must download and install on your Mac.

Step 5: Drag provisioning file into Xcode Organizer window

With the location of the downloaded file handy, plug in your device (if it isn’t already plugged in), and open up the Xcode WindowOrganizer once again. Simply drag the .mobileProvision file into the Organizer window, and it will set up the profile in Xcode automatically.

Step 6: Set up certificates with the Keychain

Next, you will be asked to download and install development certificates that match this profile. Save the .cer file and double-click it to add it to the Keychain Access list.

You should now see both Public and Private keys paired together with your developer account name inside the Keychain Access provisioning list.


Whew! That certainly was not simple, but the Provisioning Assistant is very easy to use as long as you follow each step carefully. We are now ready to test the application on a physical device.

Using Xcode to Target a Test Device

We will need to change the build profile to target the attached device rather than the simulator. To do this, we simply change the drop-down in the upper left from Simulator to Device, as shown in Figure 10-18.

Setting the build target to a device

Figure 10-18. Setting the build target to a device

After all that, now it is time to click the “Build and Run” icon.

After a few seconds, the application will initialize and show up on the device like a normal iOS application.

When running the app on a device, you will be able to click the buttons, hear the sounds, and see the buttons change color. When you want to reset the card, give the device a good shake to see the alert box with the current location offsets for the accelerometer. Click the OK button, and the card will reset.

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