html5-canvas Introduction to Transformations


Example

Transformations alter a given point's starting position by moving, rotating & scaling that point.

  • Translation: Moves a point by a distanceX and distanceY.
  • Rotation: Rotates a point by a radian angle around it's rotation point. The default rotation point in Html Canvas is the top-left origin [x=0,y=0] of the Canvas. But you can reposition the rotation point using translations.
  • Scaling: Scales a point's position by a scalingFactorX and scalingFactorY from it's scaling point. The default scaling point in Html Canvas is the top-left origin [x=0,y=0] of the Canvas. But you can reposition the scaling point using translations.

You can also do less common transformations, like shearing (skewing), by directly setting the transformation matrix of the canvas using context.transform.

Translate (==move) a point with context.translate(75,25)

enter image description here

Rotate a point with context.rotate(Math.PI/8)

enter image description here

Scale a point with context.scale(2,2)

enter image description here

Canvas actually achieves transformations by altering the canvas' entire coordinate system.

  • context.translate will move the canvas [0,0] origin from the top left corner to a new location.
  • context.rotate will rotate the entire canvas coordinate system around the origin.
  • context.scale will scale the entire canvas coordinate system around the origin. Think of this as increasing the size of every x,y on the canvas: every x*=scaleX and every y*=scaleY.

Canvas transformations are persistent. All New drawings will continue to be transformed until you reset the canvas' transformation back to it's default state (==totally untransformed). You can reset back to default with:

// reset context transformations to the default (untransformed) state
context.setTransform(1,0,0,1,0,0);