HTML5 Canvas

Book description

No matter what platform or tools you use, the HTML5 revolution will soon change the way you build web applications, if it hasn't already. HTML5 is jam-packed with features, and there's a lot to learn. This book gets you started with the Canvas element, perhaps HTML5's most exciting feature. Learn how to build interactive multimedia applications using this element to draw, render text, manipulate images, and create animation.

Whether you currently use Flash, Silverlight, or just HTML and JavaScript, you'll quickly pick up the basics. Practical examples show you how to create various games and entertainment applications with Canvas as you learn. Gain valuable experience with HTML5, and discover why leading application developers rave about this specification as the future of truly innovative web development.

  • Create and modify 2D drawings, text, and bitmap images
  • Incorporate and manipulate video, and add audio
  • Build a basic framework for creating a variety of games on Canvas
  • Use bitmaps and tile sheets to develop animated game graphics
  • Go mobile: port Canvas applications to iPhone with PhoneGap
  • Explore ways to use Canvas for 3D and multiplayer game applications

Publisher resources

View/Submit Errata

Table of contents

  1. Dedication
  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
      1. <!doctype html>
      2. <html lang="en">
      3. <meta charset="UTF-8">
      4. <title>…</title>
      5. A Simple HTML5 Page
    2. Basic HTML We Will Use in This Book
      1. <div>
      2. <canvas>
    3. The Document Object Model (DOM) and Canvas
    4. JavaScript and Canvas
      1. JavaScript Frameworks and Libraries
      2. Where Does JavaScript Go and Why?
    5. HTML5 Canvas “Hello World!”
      1. Encapsulating Your JavaScript Code for Canvas
      2. Adding Canvas to the HTML Page
        1. Using document to reference the canvas element in JavaScript
      3. Testing to See Whether the Browser Supports Canvas
      4. Retrieving the 2D Context
      5. The drawScreen() Function
    6. Debugging with Console.log
    7. The 2D Context and the Current State
    8. The HTML5 Canvas Object
    9. Another Example: Guess The Letter
      1. How the Game Works
      2. The “Guess The Letter” Game Variables
      3. The initGame() Function
      4. The eventKeyPressed() Function
      5. The drawScreen() Function
      6. Exporting Canvas to an Image
      7. The Final Game Code
    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
      1. What’s Not Part of the State?
      2. How Do We Save and Restore the Canvas State?
    4. Using Paths to Create Lines
      1. Starting and Ending a Path
      2. The Actual Drawing
        1. lineCap attributes
          1. context.lineCap
        2. lineJoin attributes
          1. context.lineJoin
        3. lineWidth
        4. strokeStyle
      3. Examples of More Advanced Line Drawing
    5. Advanced Path Methods
      1. Arcs
        1. context.arc()
        2. context.arcTo()
      2. Bezier Curves
      3. The Canvas Clipping Region
    6. Compositing on the Canvas
    7. Simple Canvas Transformations
      1. Rotation and Translation Transformations
        1. Lesson 1: Transformations are applied to shapes and paths drawn after the setTransform() or other transformation function is called
        2. Lesson 2: We must “translate” the point of origin to the center of our shape to rotate it around its own center
      2. Scale Transformations
      3. Combining Scale and Rotation Transformations
    8. Filling Objects with Colors and Gradients
      1. Setting Basic Fill Colors
      2. Filling Shapes with Gradients
        1. Linear gradients
          1. Linear horizontal gradients
          2. Applying a horizontal gradient to a stroke
          3. Applying a horizontal gradient to a complex shape
          4. Vertical gradients
          5. Diagonal gradients
        2. Radial 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
      1. Basic Text Display
      2. Handling Basic Text in Text Arranger
      3. Communicating Between HTML Forms and the Canvas
      4. Using measureText
        1. Centering text using width
        2. What about the height of the text?
      5. fillText and strokeText
    2. Setting the Text Font
      1. Font Size, Face Weight, and Style Basics
      2. Handling Font Size and Face in Text Arranger
        1. Available font styles
        2. Available font weights
        3. Generic font faces
        4. Font size and HTML5 range control
        5. Creating the necessary variables in the canvasApp() function
        6. Setting event handlers in canvasApp()
        7. Defining event handler functions in canvasApp()
        8. Setting the font in the drawScreen() function
      3. Font Color
        1. Handling font color with JSColor
      4. Font Baseline and Alignment
        1. Vertical alignment
        2. Horizontal alignment
        3. Handling text baseline and alignment
      5. Text Arranger Version 2.0
    3. Text and the Canvas Context
      1. Global Alpha and Text
        1. Handling globalAlpha transparencies
      2. Global Shadows and Text
        1. Handling global shadows
    4. Text with Gradients and Patterns
      1. Linear Gradients and Text
      2. Radial Gradients and Text
      3. Image Patterns and Text
      4. Handling Gradients and Patterns in Text Arranger
    5. Width, Height, Scale, and toDataURL() Revisited
      1. Dynamically Resizing the Canvas
        1. Dynamically resizing in Text Arranger
      2. Dynamically Scaling the Canvas
      3. The toDataURL() Method of the Canvas Object
    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
      1. Preloading Images
      2. Displaying an Image on the Canvas with drawImage()
      3. Resizing an Image Painted to the Canvas
      4. Copying Part of an Image to the Canvas
    3. Simple Cell-Based Sprite Animation
      1. Creating an Animation Frame Counter
      2. Creating a Timer Loop
      3. Changing the Tile to Display
    4. Advanced Cell-Based Animation
      1. Examining the Tile Sheet
      2. Creating an Animation Array
      3. Choosing the Tile to Display
      4. Looping Through the Tiles
      5. Drawing the Tile
      6. Moving the Image Across the Canvas
    5. Applying Rotation Transformations to an Image
      1. Canvas Transformation Basics
        1. Step 1: Save the current context to the stack
        2. Step 2: Reset the transformation matrix to identity
        3. Step 3: Code the transform algorithm
        4. Step 4: Draw the image
      2. Animating a Transformed Image
    6. Creating a Grid of Tiles
      1. Defining a Tile Map
      2. Creating a Tile Map with Tiled
      3. Displaying the Map on the Canvas
        1. Map height and width
        2. Storing the map data
        3. Displaying the map on the canvas
    7. Zooming and Panning an Image
      1. Creating a Window for the Image
      2. Drawing the Image Window
      3. Panning the Image
      4. Zoom and Pan the Image
      5. Application: Controlled Pan and Zoom
        1. The zoom scale
        2. Keyboard input
    8. Pixel Manipulation
      1. The Canvas Pixel Manipulation API
        1. ImageData attributes
        2. Getting image data
        3. Putting image data
      2. Application Tile Stamper
        1. How ImageData.data is organized
        2. A visual look at our basic application
        3. Adding mouse events to the canvas
        4. The highlightTile() function
    9. Copying from One Canvas to Another
    10. What’s Next
  8. 5. Math, Physics, and Animation
    1. Moving in a Straight Line
      1. Moving Between Two Points: The Distance of a Line
        1. Drawing the ball
        2. Tracing movement: A path of points
      2. Moving on a Vector
    2. Bouncing Off Walls
      1. Bouncing a Single Ball
      2. Multiple Balls Bouncing Off Walls
      3. Multiple Balls Bouncing with a Dynamically Resized Canvas
      4. Multiple Balls Bouncing and Colliding
        1. Ball interactions in physics
        2. Making sure the balls don’t start on top of each other
        3. Circle collision detection
        4. Separating the code in drawScreen()
        5. Updating positions of objects
        6. Better interaction with the walls
        7. Collisions with balls
        8. Ball collisions in depth
      5. Multiple Balls Bouncing with Friction
    3. Curve and Circular Movement
      1. Uniform Circular Motion
      2. Moving in a Simple Spiral
      3. Cubic Bezier Curve Movement
      4. Moving an Image
      5. Creating a Cubic Bezier Curve Loop
    4. Simple Gravity, Elasticity, and Friction
      1. Simple Gravity
      2. Simple Gravity with a Bounce
      3. Gravity with Bounce and Applied Simple Elasticity
      4. Simple Gravity, Simple Elasticity, and Simple Friction
    5. Easing
      1. Easing Out (Landing the Ship)
      2. Easing In (Taking Off)
    6. What’s Next?
  9. 6. Mixing HTML5 Video and Canvas
    1. HTML5 Video Support
      1. Theora + Vorbis = .ogg
      2. H.264 + $$$ = .mp4
      3. VP8 + Vorbis = .webm
      4. Combining All Three
    2. Converting Video Formats
    3. Basic HTML5 Video Implementation
      1. Plain-Vanilla Video Embed
      2. Video with Controls, Loop, and Autoplay
      3. Altering the Width and Height of the Video
        1. Dynamically scaling a video
    4. Preloading Video in JavaScript
      1. A Problem with Events and Embedded Video in HTML5
    5. Video and the Canvas
      1. Displaying a Video on HTML5 Canvas
        1. Video must still be embedded in HTML
        2. Video is displayed like an image
        3. Set an interval to update the display
      2. HTML5 Video Properties
    6. Video on the Canvas Examples
      1. Using the currentTime Property to Create Video Events
      2. Canvas Video Transformations: Rotation
      3. Canvas Video Puzzle
        1. Setting up the game
        2. Randomizing the puzzle pieces
        3. Drawing the screen
        4. Detecting mouse interactions and the canvas
        5. Creating hit test point-style collision detection
        6. Swapping two elements in a two-dimensional array
        7. Testing the game
      4. Creating Video Controls on the Canvas
        1. Creating video buttons
        2. Preloading the buttons
        3. Placing the buttons
        4. Listening for the button presses
    7. Animation Revisited: Moving Videos
    8. What’s Next?
  10. 7. Working with Audio
    1. The Basic <audio> Tag
    2. Audio Formats
      1. Supported Formats
      2. Audacity
      3. Example: Using All Three Formats
    3. Audio Tag Properties, Functions, and Events
      1. Audio Functions
      2. Important Audio Properties
      3. Important Audio Events
      4. Loading and Playing the Audio
      5. Displaying Attributes on the Canvas
    4. Playing a Sound with No Audio Tag
      1. Dynamically Creating an Audio Element in JavaScript
      2. Finding the Supported Audio Format
      3. Playing the Sound
      4. Look Ma, No Tag!
    5. Creating a Canvas Audio Player
      1. Creating Custom User Controls on the Canvas
      2. Loading the Button Assets
      3. Setting Up the Audio Player Values
      4. Mouse Events
      5. Sliding Play Indicator
      6. Play/Pause Push Button: Hit Test Point Revisited
      7. Loop/No Loop Toggle Button
      8. Click-and-Drag Volume Slider
        1. Volume slider variables
        2. Volume slider functionality
    6. Case Study in Audio: Space Raiders Game
      1. Why Sounds in Apps Are Different: Event Sounds
      2. Iterations
      3. Space Raiders Game Structure
        1. State machine
        2. Initializing the game: no global variables
        3. Preloading all assets without global variables
        4. Resetting the game
        5. Mouse control
        6. Bounding box collision detection
        7. Playing the game
      4. Iteration #1: Playing Sounds Using a Single Object
      5. Iteration #2: Creating Unlimited Dynamic Sound Objects
      6. Iteration #3: Creating a Sound Pool
      7. Iteration #4: Reusing Preloaded Sounds
        1. Other stuff you could do to improve the game
        2. The final code for Space Raiders
    7. What’s Next
  11. 8. Canvas Game Essentials
    1. Why Games in HTML5?
      1. Canvas Compared to Flash
      2. What Does Canvas Offer?
    2. Our Basic Game HTML5 File
    3. Our Game’s Design
    4. Game Graphics: Drawing with Paths
      1. Needed Assets
      2. Using Paths to Draw the Game’s Main Character
        1. The static player ship (frame 1)
        2. The ship with thrust engaged (frame 2)
    5. Animating on the Canvas
      1. Game Timer Loop
      2. The Player Ship State Changes
    6. Applying Transformations to Game Graphics
      1. The Canvas Stack
    7. Game Graphic Transformations
      1. Rotating the Player Ship from the Center
      2. Alpha Fading the Player Ship
        1. Using the context.globalAlpha attribute
    8. Game Object Physics and Animation
      1. How Our Player Ship Will Move
        1. The difference between facing and moving
        2. Thrusting in the rotated direction
        3. Redrawing the player ship to start at angle 0
      2. Controlling the Player Ship with the Keyboard
        1. The array to hold our key presses
        2. The key events
        3. Evaluating key presses
      3. Giving the Player Ship a Maximum Velocity
    9. A Basic Game Framework
      1. The Game State Machine
      2. The Update/Render (Repeat) Cycle
      3. The FrameRateCounter Object Prototype
    10. Putting It All Together
      1. Geo Blaster Game Structure
        1. Game application states
        2. Game application state functions
        3. Game application functions
      2. Geo Blaster Global Game Variables
    11. The player Object
    12. Geo Blaster Game Algorithms
      1. Arrays of Logical Display Objects
        1. Rocks
        2. Saucers
        3. Missiles
        4. Explosions and particles
      2. Level Knobs
      3. Level and Game End
        1. Level end
        2. Game end
      4. Awarding the Player Extra Ships
      5. Applying Collision Detection
    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
      1. Geo Blaster Tile Sheet
        1. Refresher: Calculating the tile source location
        2. Other new player attributes
        3. The new boundingBoxCollide() algorithm
      2. Rendering the Other Game Objects
        1. Rendering the saucers
        2. Rendering the rocks
        3. Rendering the missiles
        4. Rendering the particles
      3. Adding Sound
        1. The sounds for our game
        2. Adding sound instances and management variables to the game
        3. Loading in sounds and tile sheet assets
        4. Playing sounds
      4. Pooling Object Instances
        1. Object pooling in Geo Blaster Extended
        2. Adding pooling variables to our game
      5. Adding in a Step Timer
        1. How the step timer works
      6. Geo Blaster Extended Full Source
    2. Creating a Dynamic Tile Sheet at Runtime
    3. A Simple Tile-Based Game
      1. Micro Tank Maze Description
        1. Game progression
        2. Game strategy
      2. The Tile Sheet for Our Game
      3. The Playfield
        1. Creating the board
      4. The Player
      5. The Enemy
      6. The Goal
      7. The Explosions
      8. Turn-Based Game Flow and the State Machine
        1. GAME_STATE_INIT
        2. GAME_STATE_WAIT_FOR_LOAD
        3. GAME_STATE_TITLE
        4. GAME_STATE_NEW_GAME
        5. GAME_STATE_WAIT_FOR_PLAYER_MOVE
        6. GAME_STATE_ANIMATE_PLAYER
        7. GAME_STATE_EVALUATE_PLAYER_MOVE
        8. GAME_STATE_ENEMY_MOVE
        9. GAME_STATE_ANIMATE_ENEMY
        10. GAME_STATE_EVALUATE_ENEMY_MOVE
        11. GAME_STATE_EVALUATE_OUTCOME
        12. GAME_STATE_ANIMATE_EXPLODE
        13. GAME_STATE_CHECK_FOR_GAME_OVER
        14. GAME_STATE_PLAYER_WIN
        15. GAME_STATE_PLAYER_LOSE
      9. Simple Tile Movement Logic Overview
      10. Rendering Logic Overview
      11. Simple Homegrown AI Overview
      12. Micro Tank Maze Complete Game Code
    4. What’s Next
  13. 10. Mobilizing Games with PhoneGap
    1. Going Mobile!
      1. Introducing PhoneGap
      2. The Application
      3. The Code
      4. Examining the Code for BSBingo.html
        1. The TextButton.js file
        2. The initLists() function
        3. The initButtons() function
        4. The initSounds() function
        5. The chooseButtonsForCard() function
        6. The drawScreen() function
        7. The onMouseClick() function
        8. The onMouseMove() function
      5. The Application Code
    2. Creating the iOS Application with PhoneGap
      1. Installing Xcode
      2. Installing PhoneGap
      3. Creating the BS Bingo PhoneGap Project in Xcode
      4. Testing the New Blank Application in the Simulator
      5. Integrating BS Bingo into the Project
      6. Setting the Orientation
      7. Changing the Banner and Icon
      8. Testing on the Simulator
      9. Adding in an iPhone “Gesture”
      10. Adding the Gesture Functions to index.html
      11. Testing on a Device
        1. Step 1: Launch the Provisioning Assistant
        2. Step 2: Find the device’s Unique ID
        3. Step 3: Generate a Certificate Signing Request
        4. Step 4: Locate saved Certificate Signing Request File
        5. Step 5: Drag provisioning file into Xcode Organizer window
        6. Step 6: Set up certificates with the Keychain
        7. Success
      12. Using Xcode to Target a Test Device
    3. Beyond the Canvas
    4. What’s Next
  14. 11. Further Explorations
    1. 3D with WebGL
      1. What Is WebGL?
      2. How Do I Test WebGL?
      3. How Do I Learn More About WebGL?
      4. What Does a WebGL Application Look Like?
        1. JavaScript libraries
        2. Shaders
        3. Testing for WebGL support with Modernizr
        4. Initialization in canvasApp()
        5. Animating the cube
      5. Full Code Listing
      6. Further Explorations with WebGL
      7. WebGL JavaScript Libraries
        1. Google O3D
        2. GLGE
        3. C3DL
        4. SpiderGL
        5. SceneJS
        6. CopperLicht
    2. Multiplayer Applications with ElectroServer 5
      1. Installing ElectroServer
        1. Starting the server
        2. The ElectroServer admin tool
        3. The JavaScript API
      2. The Basic Architecture of a Socket-Server Application
      3. The Basic Architecture of an ElectroServer Application
        1. Client
        2. Zones, rooms, and games
        3. Extensions
      4. Creating a Chat Application with ElectroServer
        1. Establishing a connection to ElectroServer
        2. Creating the chat functionality
      5. Testing the Application in Google Chrome
      6. Further Explorations with ElectroServer
      7. This Is Just the Tip of the Iceberg
    3. Conclusion
  15. Index
  16. About the Authors
  17. Colophon
  18. Copyright

Product information

  • Title: HTML5 Canvas
  • Author(s): Steve Fulton, Jeff Fulton
  • Release date: May 2011
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449393908