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:
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.