Prerequisites:
Text Flurry uses string operations to break apart a string, and canvas text operations to measure and render the parts, in an animation which merges the characters together from random locations.
You can also draw text:
ctx.fillText("text", x, y);
ctx.strokeText(text, x, y);
As with any other figure, filling means painting the interior, and stroking means drawing the edges. For small fonts, you will normally want to just fill the text; stroking tends to look fuzzy because the line width is too large for the font (see Example 03-02).
The position specified by (x, y) is normally something in the neighborhood of the bottom left of the text (unlike drawing rectangles, which are positioned by the top left corner). This is controlled by the context textBaseline setting, which is described below.
The default font—the one in effect when the context is created—is 10px sans-serif. You can request other fonts:
ctx.font = "bold 12px sans-serif"; // font style
The fonts are specified as in CSS. In particular:
Other things you can do to control drawing text (possible values are separated by |, meaning “or”):
canvas.dir = "ltr" | "rtl";
// writing direction; default: left to right
ctx.textAlign = "start" | "end" | "left" | "right" | "center";
// default: "start", same as "left" if direction is ltr
ctx.textBaseline = "top" | "hanging" | "middle" |
"alphabetic" | "ideographic" | "bottom";
// default: "alphabetic"
Note that dir is an HTML attribute, so it belongs to the canvas (or any HTML element), not to the drawing context. See The dir attribute for details.
Text direction, alignment, and baseline.
Draw some text with controls for direction, alignment, and baseline.
Sometimes we need to measure the space filled up by our text or scale it down to fit in a small area.
Both fillText and strokeText take an optional fourth parameter, maxWidth; if used, the text is scaled down, if necessary, so that its width is no greater than maxWidth:
ctx.fillText(text, x, y [, maxWidth]);
ctx.strokeText(text, x, y [, maxWidth]);
Text can be measured, producing a TextMetrics object, from which we can extract the width of the text.
var metrics = ctx.measureText(text);
var twidth = metrics.width;
Using the width, you can position other graphics (text or otherwise) relatively to some text which you have drawn.
The HTML5 spec (4.8.11.1.11) mentions a bunch of other properties of the TextMetrics object (metrics.actualBoundingBoxLeft, metrics.actualBoundingBoxRight, metrics.fontBoundingBoxAscent, metrics.fontBoundingBoxDescent, metrics.actualBoundingBoxAscent, metrics.actualBoundingBoxDescent, metrics.emHeightAscent, metrics.emHeightDescent, metrics.hangingBaseline, metrics.alphabeticBaseline, metrics.ideographicBaseline), but in my experience, they have not been implemented.
Using text metrics to position an image.
We use the width attribute to place the image at the end of the text.