To draw text using HTML5 Canvas, we have access to a few properties and methods such as the font property and the fillText() method of the canvas context. The font property of the canvas context is used to set the font style, size, and family. Similar to CSS, the style can be normal, italic, or bold.

After you set the font property, you can proceed to draw the text with the fillText() method. You can even apply a gradient fill for the text. We will take a look at some examples below.

font Property

The font property sets or returns the current font properties for text content on the canvas. This property uses the same syntax as the CSS font property.

context.font=“font-style font-varient font-weight font-size font-family”;

fillText() Method

The fillText() method draws filled text on the canvas. The default color of the text is black. We can use the font and fillstyle properties to customize the format of the text.

context.fillText(string,x,y,maxWidth);

Syntax

context.font = ‘bold 16px Arial’; context.fillText(string, x, y, maxWidth);

Example

Your browser does not support the HTML5 canvas tag.

textAlign Property

The textAlign property sets or returns the current alignment for text content, according to the starting value. Generally, the text will start in the position specified and paint to the left, but the textAlign property will place the text according to the alignment value.

context.textAlign=“start|end|left|center|right”;

textBaseline Property

The textBaseline property sets or returns the current text baseline used when drawing text. Note that different browsers will interpret this property differently. The default value for this property is alphabetic.

context.textBaseline=“alphabetic|bottom|hanging|ideographic|middle|top”;

strokeText Method

The strokeText() method draws text on the canvas. The default color of the text is black. The strokeText() method adds no fill to the text. You can use a solid color or gradient fill for the outline of the text.

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