HTML and CSS Reference
In-Depth Information
// Move the object to the correct spot
ctx.translate(250,200);
// Uncenter the element back to its original spot
ctx.translate(50,50);
// Rotate it
ctx.rotate(45 * Math.PI / 180);
// Center it
ctx.translate(-50,-50);
// Draw it
ctx.fillRect(0,0,100,100);
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
Matrix
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:
ctx.save(); // Save the state
ctx.translate(...);
ctx.scale(...);
ctx.rotate(...);
...
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
ctx.setTransform(1,0,0,1,0,0);
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