HTML5 Canvas
Total Page:16
File Type:pdf, Size:1020Kb
HTML5 Canvas HTML5 Canvas Native Interactivity and Animation for the Web Steve Fulton and Jeff Fulton Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo HTML5 Canvas by Steve Fulton and Jeff Fulton Copyright © 2011 8bitrocket Studios. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editors: Mike Loukides and Simon St.Laurent Indexer: Ellen Troutman Zaig Production Editor: Kristen Borg Cover Designer: Karen Montgomery Copyeditor: Marlowe Shaeffer Interior Designer: David Futato Proofreader: Sada Preisch Illustrator: Robert Romano Printing History: May 2011: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. HTML5 Canvas, the image of a kaka parrot, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-1-449-39390-8 [LSI] 1303735727 To Flash. Table of Contents Preface ..................................................................... xv 1. Introduction to HTML5 Canvas ............................................ 1 The Basic HTML Page 2 <!doctype html> 3 <html lang="en"> 3 <meta charset="UTF-8"> 3 <title>…</title> 3 A Simple HTML5 Page 3 Basic HTML We Will Use in This Book 4 <div> 4 <canvas> 5 The Document Object Model (DOM) and Canvas 5 JavaScript and Canvas 6 JavaScript Frameworks and Libraries 6 Where Does JavaScript Go and Why? 6 HTML5 Canvas “Hello World!” 7 Encapsulating Your JavaScript Code for Canvas 8 Adding Canvas to the HTML Page 9 Testing to See Whether the Browser Supports Canvas 10 Retrieving the 2D Context 11 The drawScreen() Function 11 Debugging with Console.log 14 The 2D Context and the Current State 15 The HTML5 Canvas Object 16 Another Example: Guess The Letter 17 How the Game Works 17 The “Guess The Letter” Game Variables 17 The initGame() Function 19 The eventKeyPressed() Function 19 The drawScreen() Function 21 Exporting Canvas to an Image 22 vii The Final Game Code 23 What’s Next 26 2. Drawing on the Canvas ................................................. 27 The Basic File Setup for This Chapter 27 The Basic Rectangle Shape 28 The Canvas State 29 What’s Not Part of the State? 30 How Do We Save and Restore the Canvas State? 30 Using Paths to Create Lines 30 Starting and Ending a Path 31 The Actual Drawing 31 Examples of More Advanced Line Drawing 32 Advanced Path Methods 34 Arcs 34 Bezier Curves 36 The Canvas Clipping Region 37 Compositing on the Canvas 39 Simple Canvas Transformations 41 Rotation and Translation Transformations 42 Scale Transformations 47 Combining Scale and Rotation Transformations 49 Filling Objects with Colors and Gradients 51 Setting Basic Fill Colors 51 Filling Shapes with Gradients 52 Filling Shapes with Patterns 61 Creating Shadows on Canvas Shapes 64 What’s Next 67 3. The HTML5 Canvas Text API .............................................. 69 Displaying Basic Text 69 Basic Text Display 69 Handling Basic Text in Text Arranger 70 Communicating Between HTML Forms and the Canvas 71 Using measureText 71 fillText and strokeText 73 Setting the Text Font 78 Font Size, Face Weight, and Style Basics 78 Handling Font Size and Face in Text Arranger 79 Font Color 83 Font Baseline and Alignment 86 Text Arranger Version 2.0 90 Text and the Canvas Context 94 viii | Table of Contents Global Alpha and Text 94 Global Shadows and Text 96 Text with Gradients and Patterns 100 Linear Gradients and Text 100 Radial Gradients and Text 102 Image Patterns and Text 102 Handling Gradients and Patterns in Text Arranger 103 Width, Height, Scale, and toDataURL() Revisited 106 Dynamically Resizing the Canvas 106 Dynamically Scaling the Canvas 109 The toDataURL() Method of the Canvas Object 110 Final Version of Text Arranger 112 What’s Next 121 4. Images on the Canvas ................................................. 123 The Basic File Setup for This Chapter 123 Image Basics 124 Preloading Images 125 Displaying an Image on the Canvas with drawImage() 125 Resizing an Image Painted to the Canvas 127 Copying Part of an Image to the Canvas 128 Simple Cell-Based Sprite Animation 130 Creating an Animation Frame Counter 130 Creating a Timer Loop 131 Changing the Tile to Display 131 Advanced Cell-Based Animation 132 Examining the Tile Sheet 133 Creating an Animation Array 133 Choosing the Tile to Display 133 Looping Through the Tiles 134 Drawing the Tile 134 Moving the Image Across the Canvas 135 Applying Rotation Transformations to an Image 137 Canvas Transformation Basics 137 Animating a Transformed Image 140 Creating a Grid of Tiles 142 Defining a Tile Map 143 Creating a Tile Map with Tiled 143 Displaying the Map on the Canvas 145 Zooming and Panning an Image 149 Creating a Window for the Image 149 Drawing the Image Window 150 Panning the Image 152 Table of Contents | ix Zoom and Pan the Image 153 Application: Controlled Pan and Zoom 154 Pixel Manipulation 158 The Canvas Pixel Manipulation API 158 Application Tile Stamper 159 Copying from One Canvas to Another 166 What’s Next 169 5. Math, Physics, and Animation ........................................... 171 Moving in a Straight Line 171 Moving Between Two Points: The Distance of a Line 174 Moving on a Vector 179 Bouncing Off Walls 183 Bouncing a Single Ball 184 Multiple Balls Bouncing Off Walls 188 Multiple Balls Bouncing with a Dynamically Resized Canvas 193 Multiple Balls Bouncing and Colliding 198 Multiple Balls Bouncing with Friction 210 Curve and Circular Movement 216 Uniform Circular Motion 217 Moving in a Simple Spiral 220 Cubic Bezier Curve Movement 223 Moving an Image 228 Creating a Cubic Bezier Curve Loop 232 Simple Gravity, Elasticity, and Friction 236 Simple Gravity 236 Simple Gravity with a Bounce 240 Gravity with Bounce and Applied Simple Elasticity 243 Simple Gravity, Simple Elasticity, and Simple Friction 246 Easing 249 Easing Out (Landing the Ship) 249 Easing In (Taking Off) 253 What’s Next? 257 6. Mixing HTML5 Video and Canvas ........................................ 259 HTML5 Video Support 259 Theora + Vorbis = .ogg 260 H.264 + $$$ = .mp4 260 VP8 + Vorbis = .webm 260 Combining All Three 261 Converting Video Formats 261 Basic HTML5 Video Implementation 262 Plain-Vanilla Video Embed 263 x | Table of Contents Video with Controls, Loop, and Autoplay 265 Altering the Width and Height of the Video 266 Preloading Video in JavaScript 271 A Problem with Events and Embedded Video in HTML5 274 Video and the Canvas 275 Displaying a Video on HTML5 Canvas 275 HTML5 Video Properties 281 Video on the Canvas Examples 285 Using the currentTime Property to Create Video Events 285 Canvas Video Transformations: Rotation 289 Canvas Video Puzzle 294 Creating Video Controls on the Canvas 307 Animation Revisited: Moving Videos 316 What’s Next? 320 7. Working with Audio ................................................... 321 The Basic <audio> Tag 321 Audio Formats 322 Supported Formats 322 Audacity 322 Example: Using All Three Formats 323 Audio Tag Properties, Functions, and Events 324 Audio Functions 325 Important Audio Properties 325 Important Audio Events 326 Loading and Playing the Audio 326 Displaying Attributes on the Canvas 327 Playing a Sound with No Audio Tag 331 Dynamically Creating an Audio Element in JavaScript 331 Finding the Supported Audio Format 332 Playing the Sound 333 Look Ma, No Tag! 334 Creating a Canvas Audio Player 336 Creating Custom User Controls on the Canvas 337 Loading the Button Assets 337 Setting Up the Audio Player Values 339 Mouse Events 340 Sliding Play Indicator 340 Play/Pause Push Button: Hit Test Point Revisited 342 Loop/No Loop Toggle Button 343 Click-and-Drag Volume Slider 344 Case Study in Audio: Space Raiders Game 352 Why Sounds in Apps Are Different: Event Sounds 353 Table of Contents | xi Iterations 353 Space Raiders Game Structure 353 Iteration #1: Playing Sounds Using a Single Object 362 Iteration #2: Creating Unlimited Dynamic Sound Objects 362 Iteration #3: Creating a Sound Pool 365 Iteration #4: Reusing Preloaded Sounds 368 What’s Next 378 8. Canvas Game Essentials ................................................ 379 Why Games in HTML5? 379 Canvas Compared to Flash 379 What Does Canvas Offer? 380 Our Basic Game HTML5 File 380 Our Game’s Design 382 Game Graphics: Drawing with Paths 382 Needed Assets 382 Using Paths to Draw the Game’s Main Character 383 Animating on the Canvas 385 Game Timer Loop 385 The Player Ship State Changes 386 Applying Transformations to Game Graphics 388 The Canvas Stack 388 Game Graphic Transformations 390 Rotating the Player Ship from the Center 390 Alpha Fading the Player Ship 392 Game Object Physics and Animation 393 How Our Player Ship Will Move 393 Controlling the Player Ship with the Keyboard 395 Giving the Player Ship a Maximum Velocity 399 A Basic Game Framework 400 The Game State Machine 400 The Update/Render (Repeat) Cycle 404 The FrameRateCounter Object Prototype 406 Putting It All Together 407 Geo Blaster Game Structure 407 Geo Blaster Global Game Variables 410 The player Object 412 Geo Blaster Game Algorithms 412 Arrays of Logical Display Objects 412 Level Knobs 415 Level and Game End 415 Awarding the Player Extra Ships 416 Applying Collision Detection 417 xii | Table of Contents The Geo Blaster Basic Full Source 419 Rock Object Prototype 443 What’s Next 445 9.