Transformations stick around. Everything else we draw after drawing that mirrored character would also be mirrored. That might be inconvenient.
It is possible to save the current transformation, do some drawing and transforming, and then restore the old transformation. This is usually the proper thing to do for a function that needs to temporarily transform the coordinate system. First we save whatever transformation the code that called the function was using. Then the function does its thing, adding more transformations on top of the current transformation. Finally we revert to the transformation we started with.
The save and restore methods on the 2D canvas context do this transformation management. They conceptually keep a stack of transformation states. When you call save, the current state is pushed onto the stack, and when you call restore, the state on top of the stack is taken off and used as context's current transformation.
The branch function in the following example illustrates what you can do with a function that changes the transformation and then calls a function (in this case itself), which continues drawing with the given transformation.
This function draws a treelike shape by drawing a line, then moving the center or the coordinate system to the end of the line, and then calling itself twice - first rotated to the left and then rotated to the right. Every call reduces the length of the branch drawn, and the recursion stops when the length drops below 8.
The result is a simple fractal.
If the calls to save and restore were not there, the second recursive call to branch would end up with the position and rotation created by the first call. It wouldn't be connected to the current branch but rather to the innermost, rightmost branch drawn by the first call. The resulting shape might also be interesting, but it is definitely not a tree.
This is an excerpt from:
• Understand the essential elements of programming, including syntax, control, and data
• Organize and clarify your code with object-oriented and functional programming techniques
• Script the browser and make basic web applications
• Use the DOM effectively to interact with browsers
• Harness Node.js to build servers and utilities
Isn't it time you became fluent in the language of the Web?
• All source code is available online in an inter-active sandbox, where you can edit the code, run it, and see its output instantly. Click here to learn more.
Learn more at amazon.com