The CanvasRenderingContext2D
method fillText()
, part of the Canvas 2D API, draws a text string at the specified coordinates, filling the string's characters with the current fillStyle
. An optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size.
This method draws directly to the canvas without modifying the current path, so any subsequent fill()
or stroke()
calls will have no effect on it.
The text is rendered using the font and text layout configuration as defined by the font
, textAlign
, textBaseline
, and direction
properties.
To draw the outlines of the characters in a string, call the context's strokeText()
method.
CanvasRenderingContext2D.fillText(text, x, y [, maxWidth]);
text
DOMString
specifying the text string to render into the context. The text is rendered using the settings specified by font
, textAlign
, textBaseline
, and direction
.x
y
maxWidth
Optional
This example writes the words "Hello world" using the fillText()
method.
First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across.
<canvas id="canvas" width="400" height="150"></canvas>
The JavaScript code for this example follows.
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90);
This code obtains a reference to the <canvas>
, then gets a reference to its 2D graphics context.
With that in hand, we set the font
to 50-pixel-tall "serif" (the user's default serif font), then call fillText()
to draw the text "Hello world," starting at the coordinates (50, 90).
This example writes the words "Hello world," restricting its width to 140 pixels.
<canvas id="canvas" width="400" height="150"></canvas>
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90, 140);
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.fillText' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | 3.5 | 9 | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText