Preface

Introduction to the Second Edition

In the past two years, since the release of this book, usage of the HTML5 Canvas has grown by leaps and bounds. The original edition of this book was one of the first publications dedicated to the Canvas. While we were proud to get out of the gate fast, it also meant that we had to do a lot of research and exploration of our own. Back in 2011, there were only a handful of examples of HTML5 Canvas applications, and still fewer tutorials. In 2013, the landscape has changed. There are many resources to choose from regarding the HTML5 Canvas, from frameworks and APIs to dedicated websites and books. To create this second edition, we took a hard look at what worked and what did not work the first time around. The following sections describe some of the exciting changes and updates that you can look forward to within these pages.

First Edition Updates

Most of the content from the first edition of this book remains intact. It remains because this book is geared towards a wide range of developers, from those who have never seen a Canvas to those who want to learn some intermediate-to-advanced ways to make use of the Canvas.

Every chapter has been revised with updated code and optimizations, as well as updates to address browser compatibility and other issues that have arisen over the past two years. A few parts have been removed. Some of the redundant code listings have been moved to the source distribution to make the book easier to read. We have also replaced parts of Chapter 4 with more, shorter demos, and we’ve completely rewritten Chapter 10 to remove the discussion of Phonegap because similar content is now widely available.

We have also added a ton of new content that we believe will help take your Canvas applications to the next level. This includes the following:

  • A new animated Hello World application

  • A discussion of accessibility and the sub-dom concept

  • Multiple methods to clear the Canvas

  • Finding points in the current path

  • Drawing focus rings

  • Animating gradients with text

  • Using pixel data to detect collisions

  • Five new examples that focus on using Box2Dweb for physics-based animations

  • Using getUserMedia() to capture video on the Canvas

  • Making use of the new Web Audio API

  • A* path finding and animation

  • Coarse and fine tile-based scrolling

  • Development of mobile web (iOS) full-screen, scaled applications

  • A new game named Retro Blaster Touch

  • A new drag-and-drop example

  • A discussion of building your own Canvas application framework

  • A short tutorial for building an HTML5 application for Windows 8

What You Need to Run the Examples in the Book

The best part about the programming HTML5 Canvas is that the barrier to entry is very low. All you need is a modern web browser and a text editor.

As far as compatible browsers go, we suggest that you download and use the latest version of the following web browsers. The browsers are listed in the order that we suggest you test them:

  • Chrome

  • Safari

  • Firefox

  • Internet Explorer (version 10)

  • Opera

Every example in this book was tested with Google Chrome, Safari, and Firefox. While we made every attempt to ensure that these examples worked across as many browsers as possible, we suggest that you use Google Chrome or Safari for the best results.

What You Need to Know

It would be good if you knew your way around programming in some kind of modern language like C, C++, C#, ActionScript 2, ActionScript 3, Java, or JavaScript. However, we will introduce the Canvas in the first chapter in a way that should ease you into web programming at the same time.

For Flash developers

JavaScript and ActionScript 1 are essentially the same language. While Adobe took some liberties with ActionScript 2, you should be very comfortable with JavaScript. If you have experience with only ActionScript 3, JavaScript might feel like a step backwards.

For Silverlight/C# developers

Take a deep breath, and think about a time before ASP.NET/C# when you might have had to develop web apps in VBScript. Keep your mind there, because that is just about the same space you are about to enter.

How This Book Is Organized

This book is organized into 11 chapters. All the chapters in the second edition have been updated, revised, and expanded. The first four chapters step you through the HTML Canvas API by example. The topics covered include text, images, and drawing. These chapters contain a few finished apps, but for the most part consist of demos designed to show you the facets of the Canvas API. The next six chapters build upon the Canvas API by expanding the scope of the examples to application length. In these chapters, we discuss math and physics applications, video, audio and games, and mobile. The final chapters introduce a few experimental areas: 3D, multiplayer, Windows 8, and a Canvas object model.

What you won’t get in this book is a simple run-down and retelling of the published W3C Canvas API. While we cover portions of the API in detail, some of it is not applicable to games. However, if you want to explore the API further, you can find it at this site.

Instead, we want to bring to light the ways the Canvas can be used to create animation, games, and entertainment applications for the Web and mobile web.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, if this book includes code examples, you may use the code in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “HTML5 Canvas, Second Edition by Steve Fulton and Jeff Fulton (O’Reilly). Copyright 2013 8bitrocket Studios, 978-1-449-33498-7.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

List of Interactive Examples

The online version of HTML5 Canvas includes 53 interactive examples to help teach and illustrate applications of the Canvas API. Here’s a full listing of these examples:

Chapter 1

Try It Now: “Guess The Letter” game

Exercise: Canvas “Hello World”

Chapter 2

Exercise: Drawing Rectangles

Exercise: Rotations and Transformations

Chapter 3

Try It Now: Text Arranger 1.0

Try It Now: Text Arranger 2.0

Try It Now: Text Arranger 3.0

View It Now: Text with Color Cycle

Chapter 4

View It Now: Ship Animation

Exercise: Rotate the Tank

Chapter 5

Try It Now: Moving on a Simple Line

Try It Now: Moving on a Simple Line 2

Try It Now: Moving on a Vector

Try It Now: Ball Bounce

Try It Now: Multiple Ball Bounce

Try It Now: Multiple Ball Bounce with Resize

Try It Now: Balls with Simple Interactions

Try It Now: Balls with Friction

Try It Now: Moving in Circle

Try It Now: Moving in Simple Geometric Spiral

Try It Now: Moving on Cubic Bezier Curve

Try It Now: Moving An Image

Try It Now: Bezier Curve Loop

Try It Now: Simple Gravity

Try It Now: Gravity with a Bounce

Try It Now: Gravity with a Vector with Bounce and Elasticity

Try It Now: Gravity with a Vector with Bounce Friction

Try It Now: Easing Out (Landing the Ship)

Try It Now: Taking Off (Fake Ease In)

Try It Now: Box2DWeb Balls Demo

Try It Now: Box2DWeb Balls Flat World

Try It Now: Box2DWeb Balls Flat World with Canvas Objects

Try It Now: Box2DWeb Boxes Falling

Try It Now: Box2DWeb Box Battle

Chapter 6

Try It Now: Basic HTML5 Video Load onto Canvas

Try It Now: Video Properties

Try It Now: Creating Simple Video Events

Try It Now: Video Rotation Transform

Try It Now: Video Puzzle

Try It Now: Canvas Video with Controls

Try It Now: Multiple Video Bounce

Chapter 7

Try It Now: Audio Properties and the Canvas

Try It Now: Playing a Sound with No Tag

Try It Now: A Custom Sound Player on the Canvas

Try It Now: Space Raiders with Unoptimized Sound

Try It Now: Space Raiders Fix #1: Create Unlimited Sounds

Try It Now: Space Raiders with a Basic Sound Pool

Try It Now: Space Raiders with Optimized Dynamic Network Sound and State Loader

Chapter 8

Play It Now: Geo Blaster Basic Game

Chapter 9

Play It Now: Geo Blaster X-ten-d

Play It Now: Micro Tank Maze

Chapter 10

Play It Now: BS Bingo

Chapter 11

Try It Now: WebGL Rotating Cube

Safari® Books Online

Safari Books Online (www.safaribooksonline.com) is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/html5-canvas-2edition.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

Steve Fulton

First off, I would like to thank my wife Dawn for the amazing patience and guidance she lovingly provided while this book was being written. I would also like to thank my girls—Rachel, Daphnie, and Kaitlyn—for not getting too frustrated every time I said “sure, yeah, in just a couple minutes” when they asked me to play with them while my head was in these pages and examples. I’d also like to thank my mom for taking her limited resources and creating a childhood where anything was possible. At the same time, I’d like to acknowledge my sisters, Mari and Carol, my mother-in-law Susan, and my uncle Richard, all of whom help guide me on a daily basis, whether they know it or not. Also thanks to the Martin, Fulton, Campi, Miller, Garnica, and Peters families for their love and support. Finally, I’d like to thank my dad, who sacrificed his dreams so that I could have my own.

Jeff Fulton

I would like thank my wonderful wife Jeanne, and sons Ryan and Justin for allowing me to devote the time necessary to complete the authoring process for a third time. They gave me the strength to keep going when times were rough and when examples were not working in even a single browser. I would also like to thank my mom, sisters Mari and Carol, as well as the entire Perry, Martin, Campi, and Backlar families for their love and support. Like Steve, I would like to thank my pop, who passed away right as we finished the first edition of this book. He taught me to chase my dreams while I still can because I have only a short time in which to realize them.

The authors would also like to acknowledge all the fine people at O’Reilly, especially Mike Loukides, who took the chance on us for this book, Simon St. Laurent, Meghan Blanchette, who led us out of the wilderness, and we’d also like to thank our technical reviewers Nick Pinkham, Kyle Nau, Tracey Oshiro, and Robert Brisita.

We’d also like to thank John and Sandy Santos of Producto Studios, everyone at Electrotank, Creative Bottle, Jet Morgan Games, Sprout, Nickelodeon, Mattel, and Adobe, plus James Becker, Ace The Super Villain, Richard Davey, Marty Goldman, Curt Vendel, Squize and nGFX from GamingYourWay.com, Bonnie Kravis, Carl Ford and all at Crossfire Media, plus Jen and Mike Foti, Wesley Crews, Eric Barth, Brandon Crist, Ian Legler, Mike Peters, Jason Neifeld, John Campi, Arnie Katz, Bill Kunkel (R.I.P.), Chris Crawford, Rob Fulop, and Nolan Bushnell.