html5 canvas 2nd edition

www.it-ebooks.info www.it-ebooks.info SECOND EDITION HTML5 Canvas Steve Fulton and Jeff Fulton www.it-ebooks.info...

7 downloads 366 Views 30MB Size
www.it-ebooks.info

www.it-ebooks.info

SECOND EDITION

HTML5 Canvas

Steve Fulton and Jeff Fulton

www.it-ebooks.info

HTML5 Canvas, Second Edition by Steve Fulton and Jeff Fulton Copyright © 2013 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: Simon St. Laurent and Meghan Blanchette Production Editor: Kara Ebrahim Copyeditor: nSight, Inc. Proofreader: nSight, Inc. April 2013:

Indexer: Lucie Haskins Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest

Second Edition

Revision History for the Second Edition: 2013-04-10:

First release

See http://oreilly.com/catalog/errata.csp?isbn=9781449334987 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. HTML5 Canvas, Second Edition, the image of a New Zealand kaka, 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 trade‐ mark 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 contained herein.

ISBN: 978-1-449-33498-7 [LSI]

www.it-ebooks.info

For Pop

www.it-ebooks.info

www.it-ebooks.info

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Introduction to HTML5 Canvas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What Is HTML5? The Basic HTML5 Page ... A Simple HTML5 Page Basic HTML We Will Use in This Book
The Document Object Model (DOM) and Canvas JavaScript and Canvas Where Does JavaScript Go and Why? HTML5 Canvas “Hello World!” Encapsulating Your JavaScript Code for Canvas Adding Canvas to the HTML Page Using the document Object 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

2 3 3 4 4 4 4 5 5 7 7 7 7 8 9 10 11 11 12 12 16 17 18 19 19 20

v

www.it-ebooks.info

The initGame() Function The eventKeyPressed() Function The drawScreen() Function Exporting Canvas to an Image The Final Game Code Hello World Animated Edition Some Necessary Properties Animation Loop Alpha Transparency with the globalAlpha Property Clearing and Displaying the Background Updating the globalAlpha Property for Text Display Drawing the Text HTML5 Canvas and Accessibility: Sub Dom Hit Testing Proposal What’s Next?

21 21 23 24 25 25 26 27 28 28 29 29 31 32 33

2. Drawing on the Canvas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 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 Examples of More Advanced Line Drawing Advanced Path Methods Arcs Bezier Curves The Canvas Clipping Region Compositing on the Canvas Simple Canvas Transformations Rotation and Translation Transformations Scale Transformations Combining Scale and Rotation Transformations Filling Objects with Colors and Gradients Setting Basic Fill Colors Filling Shapes with Gradients Filling Shapes with Patterns Creating Shadows on Canvas Shapes Methods to Clear the Canvas Simple Fill

vi

| Table of Contents

www.it-ebooks.info

35 36 37 38 38 38 39 39 40 42 42 44 45 47 50 50 56 57 60 60 61 71 75 77 77

Resetting the Canvas Width and Height Resetting the Canvas clearRect Function Checking to See Whether a Point Is in the Current Path Drawing a Focus Ring What’s Next?

77 77 79 80 80

3. The HTML5 Canvas Text API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Canvas Text and CSS Displaying Basic Text Basic Text Display Handling Basic Text in Text Arranger Communicating Between HTML Forms and the Canvas Using measureText fillText and strokeText Setting the Text Font Font Size, Face, Weight, and Style Basics Handling Font Size and Face in Text Arranger Font Color Font Baseline and Alignment Text Arranger Version 2.0 Text and the Canvas Context Global Alpha and Text Global Shadows and Text 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 Scaling the Canvas The toDataURL() Method of the Canvas Object Final Version of Text Arranger Animated Gradients The Future of Text on the Canvas CSS Text Making Text Accessible What’s Next?

81 82 82 82 83 84 85 89 89 89 94 96 101 101 101 103 106 107 109 109 110 114 114 116 117 119 128 132 133 133 133

4. Images on the Canvas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 The Basic File Setup for This Chapter Image Basics

135 136

Table of Contents

www.it-ebooks.info

|

vii

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 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 Diving into Drawing Properties with a Large Image Creating a Window for the Image Drawing the Image Window Changing the ViewPort Property of the Image Changing the Image Source Scale Panning to a Spot on the Source Image Pan and Scale in the Same Operation Pixel Manipulation The Canvas Pixel Manipulation API Application Tile Stamper Copying from One Canvas to Another Using Pixel Data to Detect Object Collisions The Colliding Objects How We Will Test Collisions Checking for Intersection Between Two Objects What’s Next?

137 137 139 140 142 143 143 143 145 145 145 146 146 147 148 149 150 153 155 155 156 158 161 162 162 164 166 167 168 170 170 172 179 182 183 184 184 190

5. Math, Physics, and Animation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Moving in a Straight Line Moving Between Two Points: The Distance of a Line

viii

|

Table of Contents

www.it-ebooks.info

191 194

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 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) Box2D and the Canvas Downloading Box2dWeb How Does Box2dWeb Work? Box2D Hello World Including the Library Creating a Box2dWeb World Units in Box2dWeb Defining the Walls in Box2D Creating Balls Rendering b2debugDraw vs. Canvas Rendering drawScreen() Bouncing Balls Revisited Translating to the Canvas Interactivity with Box2D Creating the Boxes Rendering the Boxes Adding Interactivity Creating Boxes Handling the Balls Box2D Further Reading

199 204 205 208 214 219 232 239 239 243 245 251 255 259 260 263 266 270 273 273 277 281 281 281 282 282 282 283 284 285 286 287 289 290 293 294 295 296 296 297 303

Table of Contents

www.it-ebooks.info

|

ix

What’s Next?

303

6. Mixing HTML5 Video and Canvas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 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 Preloading Video in JavaScript Video and the Canvas Displaying a Video on HTML5 Canvas HTML5 Video Properties Video on the Canvas Examples Using the currentTime Property to Create Video Events Canvas Video Transformations: Rotation Canvas Video Puzzle Creating Video Controls on the Canvas Animation Revisited: Moving Videos Capturing Video with JavaScript Web RTC Media Capture and Streams API Example 1: Show Video Example 2: Put Video on the Canvas and Take a Screenshot Example 3: Create a Video Puzzle out of User-Captured Video Video and Mobile What’s Next?

305 305 306 306 307 307 308 309 311 312 317 321 321 327 331 331 335 341 355 364 369 370 370 373 376 378 379

7. Working with Audio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 The Basic