HTML and CSS Reference
In-Depth Information
// Move the object to the correct spot
// Uncenter the element back to its original spot
// Rotate it
ctx.rotate(45 * Math.PI / 180);
// Center it
// Draw it
If you change the order of any of these (with the exception of the first two translations, which are commut-
ative), you end up with a rectangle that changes position as you try to change the angle of rotation.
Saving, Restoring, and Resetting the Transformation
Because you often want to nest transforms, the Canvas context provides a couple of handy methods to save and
restore the state of the transformation matrix:; // Save the state
ctx.restore(); // Restore the matrix
Using save and restore enables you to apply any number of child transforms and then restore the state
back without affecting any other code that might rely on the state of the transformation matrix.
You can also reset the transformation matrix back to a known state with setTransform :
ctx.setTransform(a, b, c, d, e, f)
If you need to reset the matrix to the identity matrix (which doesn't do any transforms), you can run
You must be careful with resetting the transform completely because this may cause unexpected results if
you adjust the canvas size for retina graphics, for example, as shown earlier.
Drawing Snowflakes
To drive home the power of transforms, build a recursive random “snowflake generator” that generates interest-
ing recursive fractal-like patterns.
Search WWH ::

Custom Search