HTML5 Guidelines for Web Developers

(coco) #1
5.13 “save( )” and “restore( )” 165

5.13 “save()” and “restore()”


Our journey through CanvasContext2D is nearly at an end. Only two methods are
left to explain: context.save() and context.restore(). Without them, we could
probably not manage any complex Canvas graphics; if you had a quick glance at
the figures’ source code, you would probably agree. To help you better under-
stand the methods context.save() and context.restore(), we need to recapitu-
late first.


By defining the drawing context with canvas.getContext('2d'), all attributes are
assigned default values, which then have a direct effect when drawing:


context.globalAlpha = 1.0;
context.globalCompositeOperation = 'source-over';
context.strokeStyle = 'black';
context.fillStyle = 'black';
context.lineWidth = 1;
context.lineCap = 'butt';
context.lineJoin = 'miter';
context.miterLimit = 10;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;
context.shadowColor = 'rgba(0,0,0,0)';
context.font = '10px sans-serif';
context.textAlign = 'start';
context.textBaseline = 'alphabetic';


At the same time, the coordinate system is initialized with the identity matrix,
and a clipping mask is created, which comprises the entire canvas area:


context.setTransform(1, 0,0,1,0,0);
context.beginPath();
context.rect(0,0,canvas.width,canvas.height);
context.clip();


If we change attributes, transformations, or clipping masks, they remain valid
until we change them again. In more complicated graphics, it is easy to lose track
of all these changes. This is where context.save() and context.restore() be-
come useful.


With context.save(), we can create a snapshot at any time, which saves the cur-
rently set attributes and transformations while taking into account the current
clipping mask. Later, we can easily access this snapshot with context.restore().
The specification mentions the stack of drawing states in this context, because
snapshots can also be nested.

Free download pdf