The Canvas element can be transformed. There are some transformation methods. Let’s see one by one.

1. Translation

Translation is only applied to shapes drawn after the translate() function is called. Shapes drawn before that function call are unaffected.

Output:

The green rectangle is before applying translation. The blue rectangle is after applying translation.

2. Rotation

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:

The green rectangle is before applying rotation. The blue rectangle is after applying rotation.

3. Scaling

The scaling is only applied to shapes drawn after the scale() call.

Output:

The green rectangle is before applying scaling. The blue rectangle is after applying scaling.

4. Rotating Around a Different Point

  • 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:

The green rectangle is before applying transformations. The blue rectangle is after applying transformations.

Tech Enthusiast