HTML and CSS Reference
All text displayed on the canvas afterward would have this baseline. To change the
baseline, you would change the property:
context.textBaseline = "middle";
In reality, you will probably choose a single baseline for your app and stick with it,
unless you are creating a word-processing or design application that requires more
precise text handling.
The context.textAlign property represents the horizontal alignment of the text based
on its x position. These are the available textAlign values:
The dead horizontal center of the text. We can use this alignment to help center
our text in Text Arranger.
Text is displayed directly after the text y position.
All text is displayed before the text y position.
Text is displayed starting with the y position of the text in the leftmost position
(just like start ).
Text is displayed with the y position in the rightmost position of the text (just like
For example, to set the text alignment to center , you would use the code:
context.textAlign = "center";
After this property is set, all text would be displayed with the y value of the text as the
center point. However, this does not mean the text will be “centered” on the canvas.
To do that, you need to find the center of the canvas, and use that location as the y
value for the text position. We will do this in Text Arranger.
These values can also be modified by the dir attribute of the Canvas object (inherited
from the DOM document object). dir changes the direction of how text is displayed; the
valid values for dir are rtl (“right to left”) and ltr (“left to right”).
Handling text baseline and alignment
We are going to handle the text baseline and alignment much like we handled the other
text properties in Text Arranger. First, we will add some variables to the canvasApp()
function in which Text Arranger operates that will hold the alignment values. Notice
that we have set the textAlign variable to center , helping us simplify centering the text
on the canvas: