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.
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 Elec‐
trotank, 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.
xx | Preface
Introduction to HTML5 Canvas
HTML5 is the current iteration of HTML, the HyperText Markup Language. HTML
was first standardized in 1993, and it was the fuel that ignited the World Wide Web.
HTML is a way to define the contents of a web page using tags that appear within pointy
brackets (< >).
HTML5 Canvas is an immediate mode bitmapped area of the screen that can be ma‐
on the screen. HTML5 Canvas completely redraws the bitmapped screen on every frame
screen display before each frame is rendered so that the correct pixels will be shown.
This makes HTML5 Canvas very different from Flash, Silverlight, or SVG, which operate
in retained mode. In this mode, a display list of objects is kept by the graphics renderer,
and objects are displayed on the screen according to attributes set in code (that is, the
x position, y position, and alpha transparency of an object). This keeps the programmer
away from low-level operations but gives her less control over the final rendering of the
The basic HTML5 Canvas API includes a 2D context that allows a programmer to draw
various shapes, render text, and display images directly onto a defined area of the
browser window. You can apply colors; rotations; gradient fills; alpha transparencies;
pixel manipulations; and various types of lines, curves, boxes, and fills to augment the
shapes, text, and images you place onto the canvas.
In itself, the HTML5 Canvas 2D context is a display API used to render graphics on a
bitmapped area, but there is very little in that context to create applications using the
and mouse inputs, timer intervals, events, objects, classes, sound, math functions, and
so on, you can learn to take HTML5 Canvas and create stunning animations, applica‐
tions, and games.
Here’s where this book comes in. We are going to break down the Canvas API into
digestible parts and then put it back together, demonstrating how to use it to create
applications. Many of the techniques you will learn in this book have been tried and
used successfully on other platforms, and now we are applying them to this exciting
Browser Support for HTML5 Canvas
With the exception of Internet Explorer 8, HTML5 Canvas is supported in some way
by most modern web browsers, with specific feature support growing on an almost daily
basis. The best support seems to be from Google Chrome, followed closely by Safari,
modernizr.js that will help us figure out which browsers support which Canvas features.
What Is HTML5?
Recently the definition of HTML5 has undergone a transition. When we wrote the first
edition of this book in 2010, the W3C HTML5 specification was a distinct unit that
covered a finite set of functionality. This included things like new HTML mark-up,
<video>, <audio>, and <canvas> tags. However, in the past year, that definition has
So, what is HTML5 now? The W3C HTML5 FAQ says this about HTML5:
HTML5 is an open platform developed under royalty free licensing terms. People use the
term HTML5 in two ways:
• to refer to a set of technologies that together form the future Open Web Platform.
These technologies include HTML5 specification, CSS3, SVG , MathML, Geoloca‐
tion, XmlHttpRequest, Context 2D, Web Fonts (WOFF) and others. The boundary
of this set of technologies is informal and changes over time.
• to refer to the HTML5 specification, which is, of course, also part of the Open Web
What we have learned through conversations and project work in the past few months
is that, to the common person who does not follow this closely (or more likely, the
common customer who needs something done right away), it’s all HTML5, and
therefore when someone says “HTML5,” they are actually referring to the “Open Web
The one thing we are certain about regarding this “Open Web Platform” is that the one
technology that was definitely left off the invite list was Adobe Flash.
2 | Chapter 1: Introduction to HTML5 Canvas
C# Image: Save or Print Document and Image in Web Viewer
or image, you can easily save the changes to DLL Library, including documents TIFF, PDF, Excel, Word string fileName = Request.Form["saveFileName"]; string fid extracting data from pdf into excel; extracting data from pdf forms
So what is HTML5? In a nutshell, it is “not Flash” (and other like technologies), and
HTML5 Canvas is the technology that has the best capability of replacing Flash func‐
tionality on the web and mobile web. This book will teach you how to get started.
The Basic HTML5 Page
Before we get to Canvas, we need to talk a bit about the HTML5 standards that we will
be using to create our web pages.
HTML is the standard language used to construct pages on the World Wide Web. We
will not spend much time on HTML, but it does form the basis of <canvas>, so we
cannot skip it entirely.
A basic HTML page is divided into sections, commonly <head> and <body>. The new
HTML5 specification adds a few new sections, such as <nav>, <article>, <header>,
The <head> tag usually contains information that will be used by the HTML <body>
in the <head>, as you will see later when we discuss the <canvas> tag. There might be
Basic HTML for a page might look like Example 1-1.
Example 1-1. A basic HTML page
<title>CH1EX1: Basic Hello World HTML Page</title>
This tag informs the web browser to render the page in standards mode. According to
the HTML5 spec from W3C, this is required for HTML5 documents. This tag simplified
a long history of oddities when it came to rendering HTML in different browsers. This
should always be the first line of HTML in a document.
The Basic HTML5 Page | 3
This is the <html> tag with the language referenced: for example, "en" = English. Some
of the more common language values are:
lang = "zh"
lang = "fr"
lang = "de"
lang = "it"
lang = "ja"
lang = "ko"
lang = "pl"
lang = "ru"
lang = "es"
This tag tells the web browser which character-encoding method to use for the page.
Unless you know what you’re doing, there is no need to change it. This is a required
element for HTML5 pages.
This is the title that will be displayed in the browser window for the HTML page. This
is a very important tag, because it is one of the main pieces of information a search
engine uses to catalog the content on the HTML page.
A Simple HTML5 Page
Now let’s look at this page in a web browser. (This would be a great time to get your
tools together to start developing code.) Open your chosen text editor, and get ready to
use your preferred web browser: Safari, Firefox, Opera, Chrome, or IE.
1. In your text editor, type in the code from Example 1-1.
2. Save the code as CH1EX1.html in a directory of your choosing.
3. Under the File menu in Chrome, Safari, or Firefox, you should find the option Open
File. Click that selection. You should then see a box to open a file. (On Windows
using Chrome, you might need to press Ctrl+O to open a file.)
4. Locate the CH1EX1.html that you just created.
5. Click Open.
You should see something similar to Figure 1-1.
4 | Chapter 1: Introduction to HTML5 Canvas
Figure 1-1. HTML Hello World!
Basic HTML We Will Use in This Book
Many HTML tags can be used to create an HTML page. In past versions of HTML, tags
that specifically instructed the web browser on how to render the HTML page (for
example, <font> and <center>) were very popular. However, as browser standards have
become more restrictive in the past decade, those types of tags have been pushed aside,
and the use of CSS (Cascading Style Sheets) has been adopted as the primary way to
style HTML content. Because this book is not about creating HTML pages (that is, pages
that don’t have Canvas in them), we are not going to discuss the inner workings of CSS.
We will focus on only two of the most basic HTML tags: <div> and <canvas>.
This is the main HTML tag that we will use in this book. We will use it to position
<canvas> on the HTML page.
Example 1-2 uses a <div> tag to position the words “Hello World!” on the screen, as
shown in Figure 1-2.
Basic HTML We Will Use in This Book | 5
Figure 1-2. HTML5 Hello World! with a <div>
Example 1-2. HTML5 Hello World!
<title>CH1EX2: Hello World HTML Page With A DIV </title>
<div style="position: absolute; top: 50px; left: 50px;">
The style="position: absolute; top: 50px; left: 50px;" code is an example of
inline CSS in an HTML page. It tells the browser to render the content at the absolute
position of 50 pixels from the top of the page and 50 pixels from the left of the page.
This <div> might position the Canvas in the web browser, but it will
not help us when we try to capture mouse clicks on the Canvas. In
Chapter 5, we will discuss a way to both position the Canvas and capture
mouse clicks in the correct locations.
6 | Chapter 1: Introduction to HTML5 Canvas
Our work with <canvas> will benefit from using the absolute positioning method with
<div>. We will place our <canvas> inside the <div> tag, and it will help us retrieve
information, such as the relative position of the mouse pointer when it appears over a
The Document Object Model (DOM) and Canvas
The Document Object Model represents all the objects on an HTML page. It is language-
neutral and platform-neutral, allowing the content and style of the page to be updated
The canvas element itself is accessible through the DOM in a web browser via the
Canvas 2D context, but the individual graphical elements created on Canvas are not
accessible to the DOM. As we stated earlier, this is because Canvas works in immediate
mode and does not have its own objects, only instructions on what to draw on any single
Our first example will use the DOM to locate the <canvas> tag on the HTML5 page so
need to understand when we start using <canvas>: window and document.
The window object is the top level of the DOM. We will need to test this object to make
sure all the assets and code have loaded before we can start our Canvas applications.
The document object contains all the HTML tags that are on the HTML page. We will
need to look at this object to find the instance of <canvas> that manipulates with
run inside nearly any web browser in existence. If you need a refresher on the topic,
and well-written reference on the subject.
The Document Object Model (DOM) and Canvas | 7
you will need to test to see whether the HTML page has loaded before you run your
<head> location. If you are not comfortable with this, you can adapt the style of the code
to your liking.
No matter where you put the code, you can place it inline in the HTML page or load an
if you know what you are doing, saving an external file and loading it will work just as
In HTML5, you no longer have to specify the script type.
HTML5 Canvas “Hello World!”
As we just mentioned, one of the first things we need to do when putting Canvas on an
HTML5 page is test to see whether the entire page has loaded and all HTML elements
are present before we start performing any operations. This will become essential when
we start working with images and sounds in Canvas.
when a defined event occurs. Other objects listen for events so that they can do some‐
for are keystrokes, mouse movements, and when something has finished loading.
The first event we need to listen for is a window object’s load event, which occurs when
the HTML page has finished loading.
To add a listener for an event, use the addEventListener() method that belongs to
objects that are part of the DOM. Because window represents the HTML page, it is the
top level of the DOM.
The addEventListener() function accepts three arguments:
8 | Chapter 1: Introduction to HTML5 Canvas
Documents you may be interested
Documents you may be interested