Transformations
Move, rotate, and scale the canvas coordinate system using transformation methods. These provide an alternative way to position objects without manually calculating coordinates for each shape.
| Method | Description |
|---|---|
translate(x, y) |
Moves the origin (0,0) of the canvas to a new position (x, y). |
rotate(angle) |
Rotates the canvas coordinate system around its current origin. The angle param is in radians. |
scale(x, y) |
Scales the canvas horizontally by x and vertically by y. |
transform(a, b, c, d, e, f) |
Multiplies the current transformation matrix with a new matrix. |
setTransform(a, b, c, d, e, f) |
Resets the current transformation and then applies a new matrix in one step. |
resetTransform() |
Resets the current transformation back to the identity matrix. |
Origins
Transformations always occur relative to the canvas origin (0,0). To rotate an object around its own center, first move the origin to the center point using translate(), then call rotate(), and finally draw the object relative to that point.
Transformation Example
The following example moves the origin to the center of the canvas and rotates the coordinate system before drawing a rectangle:
The next lesson explains how to implement compositing and clipping.