YouTip LogoYouTip

Canvas Filltext

## HTML Canvas fillText() Method The `fillText()` method of the Canvas 2D API draws a text string at the specified coordinates, filling the string's characters with the current `fillStyle`. By default, the filled text is rendered in solid black. To customize the appearance of your text, you can use the `font` property to change the font family and size, and the `fillStyle` property to apply colors, gradients, or patterns. --- ## Syntax ```javascript context.fillText(text, x, y, maxWidth); ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `text` | *String* | Specifies the text string to render onto the canvas. | | `x` | *Number* | The x-coordinate (in pixels) where the text rendering begins, relative to the canvas. | | `y` | *Number* | The y-coordinate (in pixels) where the text rendering begins, relative to the canvas. | | `maxWidth` | *Number* | *Optional.* The maximum allowed width of the text in pixels. If specified and the string is wider than this value, the font is scaled down or a narrower font variant is used. | --- ## Code Examples ### Example 1: Basic Text and Gradient Text This example demonstrates how to draw a basic text string and a styled text string filled with a linear gradient. ```html Your browser does not support the HTML5 canvas tag. ``` --- ## Usage Notes & Considerations ### 1. Text Alignment and Baseline The `x` and `y` coordinates do not necessarily represent the top-left corner of the text. The exact positioning depends on the following context properties: * **`textAlign`**: Defines the horizontal alignment. Default is `"start"`. Other options include `"left"`, `"center"`, `"right"`, and `"end"`. * **`textBaseline`**: Defines the vertical alignment relative to the baseline. Default is `"alphabetic"`. Other options include `"top"`, `"hanging"`, `"middle"`, `"ideographic"`, and `"bottom"`. ### 2. The `maxWidth` Parameter * When using `maxWidth`, the browser will compress the text horizontally (either by scaling down the font size or using a condensed font face) if the rendered text exceeds the specified width. * **Compatibility Note:** Legacy versions of Safari may have limited or inconsistent support for the `maxWidth` parameter. ### 3. Browser Compatibility The `fillText()` method is supported by all modern web browsers: * Google Chrome * Mozilla Firefox * Microsoft Edge / Internet Explorer 9+ * Safari * Opera *Note: Internet Explorer 8 and earlier versions do not support the `` element.*
← Av Met CanplaytypeCanvas Textbaseline β†’