Using measureText
The HTML5 Canvas context object includes a useful method, measureText()
. When supplied with a text
string, it will return some properties about that text, based on the
current context settings (font face, size, and so on) in the form of a
TextMetrics
object. Right now, the
TextMetrics
object has only
a single property: width
. The width
property of a TextMetrics
object gives you the exact width
in pixels of the text when rendered on the canvas. This can be very
useful when attempting to center text.
Centering text using width
For the Text Arranger application, we will use the TextMetrics
object to center the text the
user has entered in the textBox
form control on the canvas. First, we retrieve an instance of TextMetrics
by passing the message
variable (which holds the text we
are going to display) to the measureText()
method of the 2D context and
storing it in a variable named metrics
:
var
metrics
=
context
.
measureText
(
message
);
Then, from the width
property
of metrics
, we get the width
value of the text in pixels and store
it in a variable named textWidth
:
var
textWidth
=
metrics
.
width
;
Next, we calculate the center of the screen by taking the
width
value of the canvas and
dividing it in half (theCanvas.width/2
). From that, we subtract
half the width
value of the text
(textWidth/2
). We do this because text on the canvas is vertically aligned to the left when it is displayed without any alignment designation (more on this a bit later). So, to center the text, we need ...
Get HTML5 Canvas, 2nd Edition 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.