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