There will be four effects demonstrated: modifying the alpha (or transparency), scaling, rotating and shearing the image. In order to show these effects in action we need to be able to apply the changes they make over a range of values. The sineWave variable will be used to define the base of this value range.
The standard sine function produces a nice wave graph with values between -1 and 1. First of all we increase the currentTime variable to reflect how long the application has been running for, and then use that value to find a point on the sine wave. By adding 1 and diving by 2 we can take the values returned by the sin function, which are between -1 and 1, and convert them into values between 0 and 1. [code]
The canvas is then cleared with a call to clearRect, making sure we have a clean slate to work with. [code]
Effects applied to the canvas are cumulative. This allows effects to be "built up" from a handful of simple functions. For example you may have a space ship that you want to rotate, translate and scale before drawing to the screen. Since the effects are applied at the canvas level though these effects are applied to everything being drawn to the canvas, not just your one image or shape (like a space ship).
The save and restore functions in the context provide an easy way to apply these cumulative effects, draw an image or shape to the canvas that has these effects applied, and then "undo" the changes. Behind the scenes the save function pushes the current drawing state onto a stack, while the restore function pops the last state off the stack. So, using the example of a space ship above, you would perform the following operations:
- Call the save function (which saves the current drawing state)
- Rotate, translate and scale the context
- Draw the ship
- Call the restore function to remove any effects that might have been added since the last call to save, effectively undoing those changes
We use this combination of the save and restore functions by first saving the drawing state before any effects are applied to the canvas. [code]
Once the drawing state is saved it's time to actually apply the effects that are the purpose of this demo application. First we call the translate function, which has the effect of centering the image that will be drawn in the canvas. [code]
Next the function referenced by the currentFunction variable is called. It is in these referenced functions that the alpha (or transparency), scaling, rotating and shearing of the image takes place. These functions will be described later. [code]
Once the effects have been applied the image has to be drawn to the canvas. We use the drawImage function to achieve this. [code]
And finally any effects that have been applied since the call to the save function are removed from the canvas by calling the restore function. [code]