thing that stays behind is the re sulting bitmap. A direct co nsequence of this fact is
that if you want, for example, to remove a g raphical object from the bitmap, you must
redraw the whole bitmap by yourself or at least redraw th e part of the bitmap affected
by the removed obje ct.
To set up a canvas in HTML, you most commonly provide the id attribute for easier
referenc e from JavaScript code, and the width and height attributes to set physical
dimensions of the element. The <canvas> element ca n also have content, which will
only be displayed if the visitor’s browser doesn’t support it. This is an example of
HTML code defining a 400 × 200 px canvas:
<canvas id="someCanvas" width="400" height="200">
Your browser doesn’t seem to support HTML5 Canvas.
</canvas>
As with any other HTML element, you can of course also set Canvas dimensions
through CSS or even dynamically using JavaScript.
From within JavaScript, you fetch a reference to a canvas element in the same fashion
as you fetch a reference to any other HTML element. For example, you can use the
getElementById() method:
var canvas = document.getElementById("someCanvas");
A peculiar thing about Canvas is that most of the time you don’t actually use Canvas
for drawing. Instead, you u se its drawing context object. You get this object by calling
the getContext() method on a Canvas object using the argumen t "2d":
var context = canvas.getContext("2d");
This way, you obtain a CanvasRenderingContext2D obje ct, which c an be used for two-
dimensional drawing on th e canvas. If yo u want to use three-dimensional graphics,
you can u se Web G L (Web Graphics Library) JavaScript API, which is the newest
addition to the <c anvas> element and is already supported by most major browsers. If
you want to use WebGL, you can refer to the
developer.mozilla.org/en-US/docs/Web/
WebGL
where you’ll find a quite exh austive c ollection of useful WebGL articles and
other resources.
Drawing Lines
Drawing a line on a canvas takes some programming effort because to draw even a
single line you need to define a path. A path is a series of one or more subpaths and a
subpath is a series of one or more lines. When you’re done de fining subpaths, you can
stroke them and you can also fill the individual areas enclosed by the subpaths. A new
path and subpath begin with the beginPath() and moveTo() methods, r espectively.
You don’t have to end a path or subpath because it closes automatically when a new
path or subpath starts. Note that the mov eTo() method star ts a new subpath and at the
272 Appendix B. Ways to Continue