Time for action – saving and restoring

Now, about those savePen() and restorePen() methods. Let's go on over to canvas2d.js and add them to the Canvas2D object. We could keep track of the current properties ourselves, but the canvas API provides an easier way.

The canvas API contains both save() and restore() methods. Any time you need to save the state of the context you call save() and it pushes the state of the context on to a stack. When you want to restore the context state you call restore() and it pops the state off the stack back into the context. This allows you to save and restore the state multiple times recursively.

This works great for situations where you may have a library of drawing functions that could be drawn in any order at runtime. ...

Get HTML5 Web Application Development By Example Beginner's guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.