Canvas Textalign
## HTML Canvas `textAlign` Property
The `textAlign` property of the Canvas 2D API specifies the current text alignment used when drawing text.
It is important to understand that alignment is relative to the **anchor point** (the `x` coordinate specified in `fillText()` or `strokeText()`). For example, if `textAlign` is set to `"right"` and you draw text at `x = 150`, the text will end at `x = 150`.
---
## Syntax & Usage
```javascript
context.textAlign = "left" | "right" | "center" | "start" | "end";
```
### Property Values
| Value | Description |
| :--- | :--- |
| **`start`** | **Default.** The text is aligned at the start of the line. For left-to-right (LTR) text, this behaves like `"left"`. For right-to-left (RTL) text, it behaves like `"right"`. |
| **`end`** | The text is aligned at the end of the line. For LTR text, this behaves like `"right"`. For RTL text, it behaves like `"left"`. |
| **`left`** | The text is left-aligned. The left edge of the text is placed at the specified `x` coordinate. |
| **`right`** | The text is right-aligned. The right edge of the text is placed at the specified `x` coordinate. |
| **`center`** | The text is center-aligned. The midpoint of the text is placed at the specified `x` coordinate. |
---
## Code Example
The following example draws a red vertical line at `x = 150` to act as the anchor point. It then demonstrates how each of the five `textAlign` values aligns text relative to this line.
### HTML & JavaScript Implementation
```html
```
---
## Key Considerations
### 1. Directionality (`direction` Property)
The behavior of `"start"` and `"end"` depends on the current direction of the canvas context (which is determined by the `direction` property or inherited from the HTML document's `dir` attribute).
* In **Left-to-Right (LTR)** layouts (default for English, Spanish, Chinese, etc.):
* `start` behaves as `left`.
* `end` behaves as `right`.
* In **Right-to-Left (RTL)** layouts (such as Arabic or Hebrew):
* `start` behaves as `right`.
* `end` behaves as `left`.
Using `start` and `end` is highly recommended for internationalization (i18n) because it automatically adapts to the language direction.
### 2. Drawing the Text
Setting `textAlign` only configures the alignment state. To actually render the text onto the canvas, you must call either:
* `fillText(text, x, y [, maxWidth])` β to draw filled text.
* `strokeText(text, x, y [, maxWidth])` β to draw outlined text.
---
## Browser Compatibility
| Feature | Chrome | Edge/IE | Firefox | Safari | Opera |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`textAlign` Support** | Yes (All) | IE 9+ / Edge | Yes (All) | Yes (All) | Yes (All) |
*Note: Internet Explorer 8 and earlier versions do not support the `
YouTip