HTML and CSS Reference
In-Depth Information
var m = ctx.measureText("This is some text");
// Width of "This is some text" with the current font
More properties may appear at some point, but the primary use case now is to precalculate the width of a
piece of text for positioning or hit-testing.
Using the Canvas Transformation Matrix
Although it's been referenced previously, this topic 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, in-
cluding 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 en-
able 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.
// 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 opera-
tions is important—and is something that people often have trouble with.
The best practice is to apply transforms from global to local. This means that if you want to move an object
to some spot on the canvas and have it appear rotated to a certain angle, you would first apply the more global
transform (the translation) and then apply the more local transform (the rotation). If you apply it the other way
around, you imply that the rotation is the global transform, so the element should be rotated around its transla-
If the element needs to be rotated around its center and was not centered at 0,0, you also need to wrap trans-
lations to center and then uncenter them around the rotation.
For example, to rotate a square around its own center and then translate it somewhere on the canvas, apply
those transforms in the reverse order. (It's easier if you read the following code from bottom to top.)
Search WWH ::

Custom Search