HTML and CSS Reference
In-Depth Information
Saving and restoring drawing state
There is a little more hope built into the 2D API: drawing state.
There are two methods on the context object: save and restore ,
which manage the current stack of drawing states. The save
method pushes the current state on to the stack, whereas
restore pops from the top of the stack.
Drawing states don't cover everything you do to the canvas,
but they do include the following:
Transformations
Clipping regions (not covered in this topic)
Current values for the following attributes: fillStyle ,
font , globalAlpha , globalCompositeOperation , lineCap ,
lineJoin , lineWidth , miterLimit , shadowBlur , shadowColor ,
shadowOffsetX , shadowOffsetY , strokeStyle , textAlign , and
textBaseline .
For example, the following code snippet from the Mozilla canvas
composition tutorial shows how it would draw 50 stars on a can-
vas in random positions. It sets the position using the translate
method. But at the end of each iteration of the loop, it restores the
original state of the canvas, thus moving the top/left of the canvas
to the real top left, rather than the position of the last translate :
for (var j=1;j<50;j++){
ctx.save();
ctx.fillStyle = '#fff';
ctx.translate(75-Math.floor(Math.random()*150),
75-Math.floor(Math.random()*150));
drawStar(ctx,Math.floor(Math.random()*4)+2);
ctx.restore();
}
NoTE Save and restore
do not affect the current
paths or current bitmap on the
canvas (you can't restore to a
previous state of the image on
the canvas).
Rendering text
canvas allows you to render text and specify fonts, sizes, align-
ment, and baselines. You can also fill text (as normal text might
appear) and stroke text (around the outline). The old Bespin
project was a great example of how custom text rendering can
be used to create a fully functional code editor written entirely
with the canvas API (it's since been superceded by Ace by the
nice folks at Ajax.org—but their version doesn't use a canvas).
 
Search WWH ::




Custom Search