Core HTML5 Canvas
Graphics, Animation, and Game Development
David Geary
Upper Saddle River, NJ Boston Indianapolis San Francisco
New York Toronto Montreal London Munich Paris Madrid
Capetown Sydney Tokyo Singapore Mexico City
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 the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:
U.S. Corporate and Government Sales
(800) 3823419
For sales outside the United States, please contact:
International Sales
Visit us on the Web: informit.com/ph
Library of Congress Cataloging-in-Publication Data
Geary, David M.
Core HTML5 canvas : graphics, animation, and game development / David
Geary.
p. cm.
Includes index.
ISBN 978-0-13-276161-1 (pbk. : alk. paper)
1. HTML (Document markup language) 2. Computer gamesProgramming. 3.
Computer animation. I. Title.
QA76.76.H94C66 2012
006.6'6dc23
2012006871
Copyright 2012 David Geary
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-13-276161-1
ISBN-10: 0-13-276161-0
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, May 2012
Preface
In the summer of 2001, after 15 years of developing graphical user interfaces and graphics-intensive applications, I read a best-selling book about implementing web applications by someone I did not knowJason Hunterbut whom, unbeknownst to me, would soon become a good friend on the No Fluff Just Stuff (NFJS) tour.
When I finished Jasons Servlets book, I thought to myself, am I really going to implement user interfaces with print statements that generate HTML? Unfortunately, I was.
From then on, I soldiered on through what I consider the Dark Ages of software development. I was the second Apache Struts committer and I invented the Struts Template Library, which ultimately became the popular Tiles project. I spent more than six years on the JavaServer Faces (JSF) Expert Group, spoke about server-side Java at more than 120 NFJS symposiums and many other conferences, and coauthored a book on JSF. I got excited about Google Web Toolkit and Ruby on Rails for a while, but in the end the Dark Ages was mostly concerned with the dull business of presenting forms to users on the client and processing them on the server, and I was never again able to capture that passion that I had for graphics and graphical user interfaces.
In the summer of 2010, with HTML5 beginning its inexorable rise in popularity, I came across an article about Canvas, and I knew salvation was nigh. I immediately dropped everything in my professional life and devoted myself fulltime to write the best Canvas book that I could. From then on, until the book was finalized in March 2012, I was entirely immersed in Canvas and in this book. Its by far the most fun Ive ever had writing a book.
Canvas gives you all the graphics horsepower you need to implement everything from word processors to video games. And, although performance varies on specific platforms, in general, Canvas is fast, most notably on iOS5, which hardware accelerates Canvas in Mobile Safari. Browser vendors have also done a great job adhering to the specification so that well-written Canvas applications run unmodified in any HTML5-compliant browser with only minor incompatibilities.
HTML5 is the Renaissance that comes after the Dark Ages of software development, and Canvas is arguably the most exciting aspect of HTML5. In this book I dive deeply into Canvas and related aspects of HTML5, such as the Animation Timing specification, to implement real-world applications that run across desktop browsers and mobile devices.
Reading This Book
I wrote this book so that in the Zen tradition you can read it without reading.
I write each chapter over the course of months, constantly iterating over material without ever writing a word. During that time I work on outlines, code listings, screenshots, tables, diagrams, itemized lists, notes, tips, and cautions. Those things, which I refer to as scaffolding, are the most important aspects of this book. The words, which I write only at the last possible moment after the scaffolding is complete, are meant to provide context and illustrate highlights of the surrounding scaffolding. Then I iterate over the words, eliminating as many of them as I can.
By focusing on scaffolding and being frugal with words, this book is easy to read without reading. You can skim the material, concentrating on the screenshots, code listings, diagrams, tables, and other scaffolding to learn a great deal of what you need to know on any given topic. Feel free to consider the words as second-class citizens, and, if you wish, consult them only as necessary.
An Overview of This Book
This book has two parts. The first part, which spans the first four chapters of the book and is nearly one half of the book, covers the Canvas API, showing you how to draw shapes and text into a canvas, and draw and manipulate images. The last seven chapters of the book show you how to use that API to implement animations and animated sprites, create physics simulations, detect collisions, and develop video games. The book ends with a chapter on implementing custom controls, such as progress bars, sliders, and image panners, and a chapter that shows you how to create Canvas-based mobile applications.
The first chapterEssentialsintroduces the canvas
element and shows you how to use it in web applications. The chapter contains a short section on getting started with HTML5 development in general, briefly covering browsers, consoles, debuggers, profilers, and timelines. The chapter then shows you how to implement Canvas essentials: drawing into a canvas, saving and restoring Canvas parameters and the drawing surface itself, printing a canvas, and an introduction to offscreen canvases. The chapter concludes with a brief math primer covering basic algebra, trigonometry, vector mathematics, and deriving equations from units of measure.
The second chapterDrawingwhich is the longest chapter in the book, provides an in-depth examination of drawing with the Canvas API, showing you how to draw lines, arcs, curves, circles, rectangles, and arbitrary polygons in a canvas, and how to fill them with solid colors, gradients, and patterns. The chapter goes beyond the mere mechanics of drawing, however, by showing you how to implement useful, real-world examples of drawing with the Canvas API, such as drawing temporary rubber bands to dynamically create shapes, dragging shapes within a canvas, implementing a simple retained-mode graphics subsystem that keeps track of polygons in a canvas so users users can edit them, and using the clipping region to erase shapes without disturbing the Canvas background underneath.