HTML and CSS Reference
In-Depth Information
left (in left-to-right languages at least), but you can change this by using the ctx.textAlign property for
any of the following values:
ctx.textAlign = "left"; // Left aligned from x,y
ctx.textAlign = "right"; // Right aligned from x,y
ctx.textAlign = "center"; // Centered on x,y
ctx.textAlign = "start"; // Same as "left" in left-to-right languages
ctx.textAlign = "end"; // Same as "right" in left-to-right languages
The default is "start" , but to center text horizontally on a specific point, you can use "center" .
Vertical alignment is controlled via the ctx.textBaseline property. By setting this property to different
values, you can control where text is positioned relative to the passed in y value:
ctx.textBaseline = "top"; // text baseline is top of the em square
ctx.textBaseline = "middle"; // text baseline is middle of the em
square
ctx.textBaseline = "alphabetic"; // text is on normal alphabetic
baseline
ctx.textBaseline = "bottom"; // text baseline is bottom of the em
square
A couple of additional options are currently unsupported ("ideographic" and "hanging" ) as of this
writing. The default textBaseline value is "alphabetic" . This value can sometimes be difficult to work
with when positioning text; setting the textBaseline to "top" or "bottom" may be easier to get text
exactly where you want it.
The final property, ctx.font , enables you to set the font using a CSS-style font string. This string can
contain anything from just a size and font-family declaration up to a full style, variant, weight, size, and family
declaration. If you pass an invalid font declaration, the assignment fails silently.
ctx.font = "20px Arial"; // Set the font to 20px
// Font set to italic, bold 40px Lobster, line height isn't actually
used
ctx.font = "italic normal bold 40px/20px Lobster";
// Setting just the size or family isn't valid and is ignored
ctx.font = "40px"; // INVALID
ctx.font = "Arial"; // INVALID
// Still returns "italic normal bold 40px/20px Lobster"
console.log(ctx.font);
Any font available on the page is available in canvas. This means any fonts you load via @font-face are
fair game.
You can also measure the width of a string of text using the ctx.measureText method. It returns a Tex-
tMetrics object which, from the HTML5 specification, looks like it should have lots of interesting properties
such as horizontal and vertical bounding boxes and em height information. In practice, browsers have only im-
plemented the width property of the text that you render.
Search WWH ::




Custom Search