YouTip LogoYouTip

Canvas Textbaseline

## HTML Canvas `textBaseline` Property The `textBaseline` property of the Canvas 2D API specifies the current text baseline used when drawing text. This property determines the vertical alignment of the text relative to the $y$-coordinate specified in the `fillText()` or `strokeText()` methods. --- ## Definition and Usage When you render text on a canvas, you specify an $(x, y)$ coordinate. While the $x$-coordinate determines the horizontal starting point (further influenced by `textAlign`), the $y$-coordinate's alignment is determined by `textBaseline`. By changing the `textBaseline` value, you can align the top, middle, bottom, or specific typographic baselines of your text to the specified $y$-coordinate. ### Syntax ```javascript context.textBaseline = "alphabetic" | "top" | "hanging" | "middle" | "ideographic" | "bottom"; ``` ### Property Values | Value | Description | | :--- | :--- | | `alphabetic` | **Default.** The text baseline is the standard alphabetic baseline (used by most Latin-based scripts). | | `top` | The text baseline is the top of the em square. | | `hanging` | The text baseline is the hanging baseline (used by Buddhist, Tibetan, and Indic scripts like Devanagari). | | `middle` | The text baseline is the exact middle of the em square. | | `ideographic` | The text baseline is the ideographic baseline (used by Chinese, Japanese, and Korean characters). | | `bottom` | The text baseline is the bottom of the em square. | --- ## Code Example The following example draws a red horizontal line at $y = 100$ and renders the same text using different `textBaseline` values to demonstrate how each value aligns relative to the line. ### HTML & JavaScript ```html Your browser does not support the HTML5 canvas tag. ``` --- ## Key Considerations * **Method Dependency:** The `textBaseline` property must be set *before* calling `fillText()` or `strokeText()` to take effect on the rendered text. * **Browser Consistency:** The exact rendering of some baselinesβ€”particularly `"hanging"` and `"ideographic"`β€”can vary slightly across different browsers and operating systems depending on the font engine and the specific font family being used. * **Browser Support:** The `textBaseline` property is widely supported in all modern browsers, including Google Chrome, Mozilla Firefox, Apple Safari, Opera, and Microsoft Edge (as well as Internet Explorer 9 and above).
← Canvas FilltextCanvas Textalign β†’