HTML and CSS Reference
In-Depth Information
system with (0,0) at the top-left corner (thereby matching the coordinate system style
in web pages). Practically all canvas API calls are made against the context, rather than
the canvas itself.
Assuming you have a reference to a canvas element, to get a reference to its 2d con
text , use:
var mycontext = mycanvas. getContext ("2d");
Once you have the context , the canvas API commands listed in the previous section are
all available to be called. The shape-drawing commands in the canvas API are all path-
based. This means that you first “draw”—or define, but not visibly—a path (one or
more straight or curved edges) that represents the shape (line, arc/curve, rectangle,
etc.), and then you specify what you want done to the path.
Typically, you stroke the path, drawing a line along its boundary edges, and/or fill the
path, filling its interior with a color or pattern.
Because you essentially render a path only after that path is defined, you will often end
up needing to create many separate path segments in your drawing, and you will apply
different strokes/fills/etc. to render each of the segments as you define them.
The first step in defining a path segment is always to call beginPath() :
mycontext. beginPath ();
mycontext.moveTo(10, 10);
mycontext.lineTo(30, 30);
If you call closePath() before you call a rendering command like
stroke() or fill() , the path literally is “closed,” in that the beginning
point of the path is automatically joined with the end point of the path,
with a final line segment.
After defining your path segment, call a rendering command, such as stroke() or
fill() . Those commands act upon that most recently defined path segment—whatever
has been defined since the most recent beginPath() call—and then subsequently that
path is no longer active or available:
mycontext.moveTo(10, 10);
mycontext.lineTo(30, 30);
mycontext. stroke ();
Keep in mind that if you draw more than one shape in the same path segment, generally
speaking, the canvas interprets the paths as being connected. In this sense, “connected”
means that there is an edge from the end of one shape to the beginning of the next. This
is not always true, though; some shape definition commands imply their own inde-
pendent or not-relative segments.
Search WWH ::

Custom Search