Text in HTML5 canvas

interactive text canvas

html5 canvas element has a robust set of methods for rendering text. This functionality is accessed by calling methods of the canvas context object.

The basic syntax is:

context.fillText("text", x, y);

context is the context for the target canvas, "text" is the text to be rendered, and x and y dictate the location of the text on the canvas. Text outlines are rendered using the strokeText method in place of fillText:

context.strokeText("text", x, y);

Additional methods are available to modify the vertical alignment, horizontal alignment, font, font size, fill and stroke color. The canvas below shows the canvas text methods in action. The sliders and buttons around the canvas allows the text to be modified:




Text: Font: Unit: style:

Size:
HTML5 compatible browser required to view content
Fill Color:

Stroke Color:
Baseline: Show: on | off
Alignment: Show: on | off


The canvas is 400 px wide and 160 px high. The following code produces the text shown in the canvas above:

Other bold and italics modifiers can be added to the .font method::

c.font = "bold 10pt serif"

c.font = "italic 20pt sans-serif"

c.font = "bold italic 15pt fantasy"