HTML5 Canvas, 2nd Edition

Book description

Flash is fading fast as Canvas continues to climb. The second edition of this popular book gets you started with HTML5 Canvas by showing you how to build interactive multimedia applications. You’ll learn how to draw, render text, manipulate images, and create animation—all in the course of building an interactive web game throughout the book.

Updated for the latest implementations of Canvas and related HTML5 technologies, this edition includes clear and reusable code examples to help you quickly pick up the basics—whether you currently use Flash, Silverlight, or just HTML and JavaScript. Discover why HTML5 is the future of innovative web development.

  • Create and modify 2D drawings, text, and bitmap images
  • Use algorithms for math-based movement and physics interactions
  • Incorporate and manipulate video, and add audio
  • Build a basic framework for creating a variety of games
  • Use bitmaps and tile sheets to develop animated game graphics
  • Go mobile: build web apps and then modify them for iOS devices
  • Explore ways to use Canvas for 3D and multiplayer game applications

Publisher resources

View/Submit Errata

Table of contents

  1. HTML5 Canvas
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Preface
    1. Introduction to the Second Edition
      1. First Edition Updates
      2. What You Need to Run the Examples in the Book
      3. What You Need to Know
      4. How This Book Is Organized
    2. Conventions Used in This Book
    3. Using Code Examples
    4. Safari® Books Online
    5. How to Contact Us
    6. Acknowledgments
      1. Steve Fulton
      2. Jeff Fulton
  5. 1. Introduction to HTML5 Canvas
    1. What Is HTML5?
    2. The Basic HTML5 Page
      1. <!doctype html>
      2. <html lang=“en”>
      3. <meta charset=“UTF-8”>
      4. <title>...</title>
      5. A Simple HTML5 Page
    3. Basic HTML We Will Use in This Book
      1. <div>
      2. <canvas>
    4. The Document Object Model (DOM) and Canvas
    5. JavaScript and Canvas
      1. Where Does JavaScript Go and Why?
    6. HTML5 Canvas “Hello World!”
      1. Encapsulating Your JavaScript Code for Canvas
      2. Adding Canvas to the HTML Page
      3. Using the document Object to Reference the Canvas Element in JavaScript
      4. Testing to See Whether the Browser Supports Canvas
      5. Retrieving the 2D Context
      6. The drawScreen() Function
    7. Debugging with console.log
    8. The 2D Context and the Current State
    9. The HTML5 Canvas Object
    10. 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
    11. Hello World Animated Edition
      1. Some Necessary Properties
      2. Animation Loop
      3. Alpha Transparency with the globalAlpha Property
      4. Clearing and Displaying the Background
      5. Updating the globalAlpha Property for Text Display
      6. Drawing the Text
    12. HTML5 Canvas and Accessibility: Sub Dom
      1. Hit Testing Proposal
        1. So what kind of mechanism are they suggesting?
        2. So what does this mean for developers?
    13. What’s Next?
  6. 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
          6. Radial gradients
    9. Filling Shapes with Patterns
    10. Creating Shadows on Canvas Shapes
    11. Methods to Clear the Canvas
      1. Simple Fill
      2. Resetting the Canvas Width and Height
      3. Resetting the Canvas clearRect Function
    12. Checking to See Whether a Point Is in the Current Path
    13. Drawing a Focus Ring
    14. What’s Next?
  7. 3. The HTML5 Canvas Text API
    1. Canvas Text and CSS
    2. 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
    3. 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
      4. Font Baseline and Alignment
        1. Vertical alignment
        2. Horizontal alignment
        3. Handling text baseline and alignment
      5. Text Arranger Version 2.0
    4. Text and the Canvas Context
      1. Global Alpha and Text
      2. Global Shadows and Text
    5. 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
    6. Width, Height, Scale, and toDataURL() Revisited
      1. Dynamically Resizing the Canvas
      2. Dynamically Scaling the Canvas
      3. The toDataURL() Method of the Canvas Object
    7. Final Version of Text Arranger
    8. Animated Gradients
    9. The Future of Text on the Canvas
      1. CSS Text
      2. Making Text Accessible
    10. What’s Next?
  8. 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. Diving into Drawing Properties with a Large Image
      1. Creating a Window for the Image
      2. Drawing the Image Window
      3. Changing the ViewPort Property of the Image
      4. Changing the Image Source Scale
      5. Panning to a Spot on the Source Image
      6. Pan and Scale in the Same Operation
    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. Using Pixel Data to Detect Object Collisions
      1. The Colliding Objects
      2. How We Will Test Collisions
      3. Checking for Intersection Between Two Objects
        1. The pixelX loop
        2. The nested pixelY loop
        3. The collision check
        4. All of the code for this example
    11. What’s Next?
  9. 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. Box2D and the Canvas
      1. Downloading Box2dWeb
      2. How Does Box2dWeb Work?
      3. Box2D Hello World
      4. Including the Library
      5. Creating a Box2dWeb World
      6. Units in Box2dWeb
      7. Defining the Walls in Box2D
      8. Creating Balls
      9. Rendering b2debugDraw vs. Canvas Rendering
      10. drawScreen()
      11. Bouncing Balls Revisited
      12. Translating to the Canvas
    7. Interactivity with Box2D
      1. Creating the Boxes
      2. Rendering the Boxes
      3. Adding Interactivity
      4. Creating Boxes
      5. Handling the Balls
    8. Box2D Further Reading
    9. What’s Next?
  10. 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
    4. Preloading Video in JavaScript
    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. Capturing Video with JavaScript
      1. Web RTC Media Capture and Streams API
      2. Example 1: Show Video
      3. Example 2: Put Video on the Canvas and Take a Screenshot
      4. Example 3: Create a Video Puzzle out of User-Captured Video
    9. Video and Mobile
    10. What’s Next?
  11. 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. Web Audio API
      1. What Is the Web Audio API?
      2. Space Raiders with the Web Audio API Applied
    8. What’s Next?
  12. 8. Canvas Games: Part I
    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
    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. Simple A* Path Finding on a Tile Grid
      1. What Is A*?
      2. A* Applied to a Larger Tile Map
      3. A* Taking Diagonal Moves into Account
      4. A* with Node Weights
      5. A* with Node Weights and Diagonals
      6. Moving a Game Character Along the A* Path
        1. Game variables for tank movement and node changes
        2. Logic for updating the tank node and position
        3. Drawing the tank on the screen
      7. Tanks That Pass Through Walls?
    16. What’s Next?
  13. 9. Canvas Games: Part II
    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 a Step Timer
    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
      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. Scrolling a Tile-Based World
      1. First, a Tile Sheet That Contains the Tiles We Want to Paint to the Screen
      2. Second, a Two-Dimensional Array to Describe Our Game World
      3. Third, Paint the Tile-Based World to the Canvas
      4. Coarse Scrolling vs. Fine Scrolling
      5. The Camera Object
      6. The World Object
      7. Fine Scrolling the Row and Column Buffers
        1. The camera top-left position
        2. The camera scrolled position
        3. The camera far-right scrolled position
        4. The camera far down scrolled position
      8. Coarse Scrolling Full Code Example
      9. Fine Scrolling Full Code Example
    5. What’s Next?
  14. 10. Going Mobile!
    1. The First Application
      1. The Code
      2. 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
      3. The Application Code
      4. Scaling the Game for the Browser
        1. Starting to create a full screen mobile version of BS Bingo
        2. Changing the Canvas style properties
        3. Updating the mouse listening code
        4. Adding meta-tags for iOS devices
      5. Testing the Game on an Actual Device
    2. Retro Blaster Touch
    3. Mobilizing Retro Blaster Touch
      1. Jumping to Full Screen
        1. Canvas element
        2. Meta-tags
        3. Style sheets
      2. Touch Move Events
        1. New global variables
        2. New listener functions
        3. Auto-fire
        4. Player movement
        5. Checking out the game
      3. Retro Blaster Touch Complete Game Code
    4. Beyond the Canvas
    5. What’s Next?
  15. 11. Further Explorations
    1. 3D with WebGL
      1. What Is WebGL?
      2. How Does One 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. Further Explorations with WebGL
      6. WebGL JavaScript Libraries
        1. Google O3D
        2. C3DL
        3. SpiderGL
        4. SceneJS
        5. CopperLicht
        6. GLGE
        7. Three.js
    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. Creating a Simple Object Framework for the Canvas
      1. Creating the Drag-and-Drop Application
      2. Application Design
        1. EventDispatcher.js
        2. Ornament.js
        3. DisplayList.js
        4. GameUtilities.js
        5. DragAndDrop.js
        6. DragAndDrop.html
    4. Windows 8 Apps and the HTML5 Canvas
    5. What’s Next in HTML5.1 and Canvas Level 2?
      1. HTML5.1 Canvas Context
        1. supportsContext()
        2. toDataURLHD(), toBlob(), toBlobHD()
      2. Canvas Level-2
    6. Conclusion
  16. A. Full Code Listings
    1. Code from Chapter 7
    2. Code from Chapter 9
      1. Geo Blaster Extended Full Source
    3. Code from Chapter 11
  17. Index
  18. About the Authors
  19. Colophon
  20. Copyright

Product information

  • Title: HTML5 Canvas, 2nd Edition
  • Author(s): Steve Fulton, Jeff Fulton
  • Release date: April 2013
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449335878