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. Each method can call save()
before it starts changing context properties and call restore()
when it's done. That way when a method is done the context is in the same state that it was before the method was called:
this.savePen = function() {...