HTML5 Canvas Transformations
The Canvas element can be transformed. There are some transformation methods. Let’s see one by one.
1. Translation
It is possible to apply translation to everything that is drawn on a canvas. Translation means relocation of what is drawn. The translate(x,y) method is used to move the Canvas. x indicates how far to move the grid horizontally, and y indicates how far to move the grid vertically.
Translation is only applied to shapes drawn after the translate()
function is called. Shapes drawn before that function call are unaffected.
Output:
2. Rotation
You can apply automatic rotation to any shape drawn on an HTML5 canvas. This is done using the rotate()
function on the 2D Context. The angle to rotate is passed as parameter to the rotate()
function. The value must be in radians, not degrees.
All shapes drawn after a rotation is set will rotated around the point 0,0 on the canvas. This is the upper left corner of the canvas.Rotation is only applied to all shapes drawn after the rotate()
function is called.
Output:
3. Scaling
When scaling you scale all cordinates on the x-axis and y-axis by some factors. The scale() method scales the current drawing. It takes two parameters:
- The number of times by which the image should be scaled in the X-direction.
- The number of times by which the image should be scaled in the Y-direction.
The scaling is only applied to shapes drawn after the scale()
call.
Output:
4. Rotating Around a Different Point
To rotate around a point you need to do 3 steps.
- First translate the context to the center you wish to rotate around.
- Then do the actual rotation.
- Then translate the context back.
Eg: Rotate a shape around its own center
Output: