Drawing Text

suggest change

Drawing to canvas isn’t just limited to shapes and images. You can also draw text to the canvas.

To draw text on the canvas, get a reference to the canvas and then call the fillText method on the context.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillText("My text", 0, 0);

The three required arguments that are passed into fillText are:

  1. The text that you would like to display
  2. The horizontal (x-axis) position
  3. The vertical (y-axis) position

Additionally, there is a fourth optional argument, which you can use to specify the maximum width of your text in pixels. In the example below the value of 200 restricts the maximum width of the text to 200px:

ctx.fillText("My text", 0, 0, 200);

Result:

You can also draw text without a fill, and just an outline instead, using the strokeText method:

ctx.strokeText("My text", 0, 0);

Result:

Without any font formatting properties applied, the canvas renders text at 10px in sans-serif by default, making it hard to see the difference between the result of the fillText and strokeText methods. See the Formatting Text example for details on how to increase text size and apply other aesthetic changes to text.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents