Using the Canvas Transformation Matrix

Although it’s been referenced previously, this book hasn’t yet described in detail the transformation matrix that Canvas provides. This matrix enables you to translate, rotate, and scale any element you draw in Canvas, including images and paths.

This matrix works much the same way as the transforms in SVG from Chapter 14 (“Building Games with SVG and Physics”) do, but in addition canvas provides a way to easily save and restore the matrix state to enable easy nesting of drawing commands. (SVG didn’t have this problem because elements were nested under each other in the DOM.)

Understanding the Basic Transformations

Similar to SVG and CSS3, Canvas provides the standard basic 2-D transformations: translate, scale, and rotate. After you apply a transform, it applies to everything you draw until you change it.

  ctx.translate(x,y);

  ctx.scale(sx,sy);

  // Rotate takes an angle in radians
  ctx.rotate(angle * Math.PI / 180);

If you need to apply a custom transform (such as a skew) that is not handled by the built-in translate, scale, or rotate, you can also call ctx.transform directly with the matrix values:

 ctx.transform(a, b, c, d, e, f);

When you call any of the preceding methods, internally the browser creates a transform matrix that performs the wanted transform and multiplies the current transformation matrix by it. This means that the order of operations is important—and is something that people often have trouble with.

The best practice is to ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.