The CanvasRenderingContext2D.fillText() method of the Canvas 2D API fills a given text at the given (x, y) position. If the optional fourth parameter for a maximum width is provided, the text will be scaled to fit that width.
See also the CanvasRenderingContext2D.strokeText() method to draw stroked text.
Syntax
void ctx.fillText(text, x, y [, maxWidth]);
Parameters
-
text -
The text to render using the current
font,textAlign,textBaseline, anddirectionvalues.
-
x - The x axis of the coordinate for the text starting point.
-
y - The y axis of the coordinate for the text starting point.
-
maxWidthOptional - The maximum width to draw. If specified, and the string is computed to be wider than this width, the font is adjusted to use a more horizontally condensed font (if one is available or if a reasonably readable one can be synthesized by scaling the current font horizontally) or a smaller font.
Examples
Using the fillText method
This is just a simple code snippet which uses the fillText method.
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "48px serif";
ctx.fillText("Hello world", 50, 100);
Edit the code below and see your changes update live in the canvas:
Specifications
| Specification | Status | Comment |
|---|---|---|
| WHATWG HTML Living Standard The definition of 'CanvasRenderingContext2D.fillText' in that specification. |
Living Standard |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | 3.5 (1.9.1) | 9 | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | 1.0 (1.9.1) | (Yes) | (Yes) | (Yes) |
See also
- The interface defining it,
CanvasRenderingContext2D CanvasRenderingContext2D.strokeText()