The Canvas textBaseline property controls which vertical baseline is placed at the y coordinate supplied to fillText() or strokeText().
Valid values are top, hanging, middle, alphabetic, ideographic, and bottom. The default is alphabetic.
ctx.textBaseline = 'middle';
ctx.fillText('Canvas text', 80, 100);
top | Top of the em square |
|---|---|
hanging | Hanging baseline used by some scripts |
middle | Middle of the em square |
alphabetic | Normal alphabetic baseline; default |
ideographic | Ideographic baseline |
bottom | Bottom of the bounding box |
textBaseline controls vertical positioning around y; textAlign controls horizontal positioning around x. They can be combined.
The default is alphabetic.
It is defined using the em square, so it is not simply the top pixel of each glyph.
middle aligns the middle of the em square with the y coordinate.
Different fonts have different metrics and glyph shapes even when they use the same baseline setting.
TextMetrics can report baseline and bounding-box measurements; set the intended font and text settings before measuring.
textAlign | fillText() | strokeText() | font | Text demo | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.