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

Putting It All Together

We are now ready to start coding our game. First, we will look at the structure of the game and some of the ideas behind the various algorithms we will employ to create it. After that, we will present the full source code for Geo Blaster Basic.

Geo Blaster Game Structure

The structure of the game application is very similar to the structure we started to build earlier in this chapter. Let’s take a closer look at the state functions and how they will work together.

Game application states

Our game will have seven distinct game application states. We will store these in constants:


Game application state functions

Each individual state will have an associated function that will be called on each frame tick. Let’s look at the functionality for each:


Displays the title screen text and waits for the space bar to be pressed before the game starts.


Sets up all the defaults for a new game. All of the arrays for holding display objects are reinitialized—the game level is reset to 0, and the game score is set to 0.


Increases the level value by one, and then sets the “game knob” values to control the level difficulty. See the upcoming section Level Knobs for details.


Fades the player graphic onto the screen from 0 alpha to 1. Once this is complete, level play will start.


Controls the play of the game level. It calls the update() and render() functions, as well as the functions for evaluating keyboard input for player ship control.


Starts up an explosion at the location where the player ship was when it was hit by a rock, saucer, or saucer missile. Once the explosion is complete (all particles in the explosion have exhausted their individual life values), it sets the move to the GAME_STATE_PLAYER_START state.


Displays the “Game Over” screen, and starts a new game when the space bar is pressed.

Game application functions

Aside from the game application state functions, there are a number of functions we need for the game to run. Each state function will call these functions as needed:


Resets the player to the center of the game screen and readies it for game play.


Checks to see whether the player should be awarded an extra ship. See the section Awarding the Player Extra Ships for details on this algorithm.


Checks to see whether all the rocks have been destroyed on a given level and, if so, starts up a new level. See the section Level and Game End for details on this algorithm.


Fills the canvas with the background color on each frame tick.


Sets the base text style before text is written to the game screen.


Is called on each frame tick. It displays the updated score, number of ships remaining, and the current FPS for the game.


Checks the keyPressList array, and then modifies the player ship attributes based on the values found to be true.


Is called from GAME_STATE_PLAY_LEVEL. It in turn calls the update() function for each individual display object array.

Individual display object update() functions

The unique functions listed below update each different type of display object. These functions (with the exception of updatePlayer()) will loop through the respective array of objects associated with its type of display object, and update the x and y values with dx and dy values. The updateSaucer() function contains the logic necessary to check whether to create a new saucer, and whether any current saucers on the screen should fire a missile at the player.

  • updatePlayer()

  • updatePlayerMissiles()

  • updateRocks()

  • updateSaucers()

  • updateSaucerMissiles()

  • updateParticles()


Is called from GAME_STATE_PLAY_LEVEL. It in turn calls the render() function for each individual display object array.

Individual display object render() functions

Like the update() functions, the unique functions listed below render each different type of display object. Again, with the exception of the renderPlayer() object (because there is only a single player ship), each of these functions will loop through the array of objects associated with its type and draw them to the game screen. As we saw when drawing the player ship earlier in this chapter, we will draw each object by moving and translating the canvas to the point at which we want to draw our logical object. We will then transform our object (if necessary) and paint the paths to the game screen.

  • renderPlayer()

  • renderPlayerMissiles()

  • renderRocks()

  • renderSaucers()

  • renderSaucerMissiles()

  • renderParticles()


Loops through the individual game display objects and checks them for collisions. See the section Applying Collision Detection for a detailed discussion of this topic.


Creates a playerMissile object at the center of the player ship and fires it in the direction the player ship is facing.


Creates a saucerMissile object at the center of the saucer and fires it in the direction of the player ship.


Creates an explosion for the player by calling createExplode(), as well as changing the game application state to GAME_STATE_PLAYER_DIE.


Accepts in the location for the explosion to start and the number of particles for the explosion.


Determines whether the rectangular box that encompasses an object’s width and height is overlapping the bounding box of another object. It takes in two logical display objects as parameters, and returns true if they are overlapping and false if they are not. See the section Applying Collision Detection for details on this function.


Accepts in the scale and x and y starting points for two new rocks that will be created if a large or medium rock is destroyed.


Accepts in a value to add to the player’s score.

Geo Blaster Global Game Variables

Now let’s look at the entire set of game application scope variables needed for our game.

Variables that control screen flow

These variables will be used when the title and “Game Over” screens first appear. They will be set to true once the screen is drawn. When these variables are true, the screens will look for the space bar to be pressed before moving on to the next application state:

var titleStarted = false;
var gameOverStarted = false;
Game environment variables

These variables set up the necessary defaults for a new game. We will discuss the extraShipAtEach and extraShipsEarned in the section, Awarding the Player Extra Ships:

var score = 0;
var level = 0;
var extraShipAtEach = 10000;
var extraShipsEarned = 0;
var playerShips = 3;
Playfield variables

These variables set up the maximum and minimum x and y coordinates for the game stage:

var xMin = 0;
var xMax = 400;
var yMin = 0;
var yMax = 400;
Score value variables

These variables set the score value for each of the objects the player can destroy:

var bigRockScore = 50;
var medRockScore = 75;
var smlRockScore = 100;
var saucerScore = 300;
Rock size constants

These variables set up some human-readable values for the three rock sizes, allowing us to simply use the constant instead of a literal value. We can then change the literal value if needed:

Logical display objects

These variables set up the single player object and arrays to hold the various other logical display objects for our game. See the upcoming sections and Arrays of Logical Display Objects for further details on each:

var player = {};
var rocks = [];
var saucers = [];
var playerMissiles = [];
var particles = []
var saucerMissiles = [];
Level-specific variables

The level-specific variables handle the difficulty settings when the game level increases. See the section Level Knobs for more details on how these are used:

var levelRockMaxSpeedAdjust = 1;
var levelSaucerMax = 1;
var levelSaucerOccurrenceRate = 25
var levelSaucerSpeed = 1;
var levelSaucerFireDelay = 300;
var levelSaucerFireRate = 30;
var levelSaucerMissileSpeed = 1;

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