Course contentsShow
← Web Development
Lesson 2623 of 2,98247. Data VisualizationFree lesson

Drawing Text

Rendering text with fillText and strokeText, including font, alignment, and baseline properties.

Drawing Text on Canvas

You'll learn how to render text on the HTML canvas using fillText and strokeText, along with essential properties for controlling font style, alignment, and positioning.

Core Idea

Canvas text rendering works like a stamp: you define the text style first (font, alignment, baseline), then "stamp" it onto the canvas at a specific position using either fillText() (solid text) or strokeText() (outlined text).

fillText vs strokeText

fillText(text, x, y) renders solid, filled text at the specified coordinates:

ctx.fillStyle = 'navy';
ctx.fillText('Hello Canvas', 50, 100);

strokeText(text, x, y) renders only the text outline:

ctx.strokeStyle = 'red';
ctx.strokeText('Hello Canvas', 50, 150);

You can use both together for outlined-and-filled effects.

Font Property

The font property uses CSS font syntax:

ctx.font = '24px Arial';
ctx.font = 'bold 32px Georgia';
ctx.font = 'italic 18px "Times New Roman"';

Text Alignment

textAlign controls horizontal positioning relative to the x-coordinate:

ctx.textAlign = 'left';   // default
ctx.textAlign = 'center'; // x is text center
ctx.textAlign = 'right';  // x is text end

Think of it like anchor points: 'center' means the x-coordinate becomes the text's center point.

Text Baseline

textBaseline controls vertical positioning relative to the y-coordinate:

ctx.textBaseline = 'alphabetic'; // default
ctx.textBaseline = 'top';        // y is text top
ctx.textBaseline = 'middle';     // y is text vertical center
ctx.textBaseline = 'bottom';     // y is text bottom

This is crucial for precise vertical alignment, especially when mixing text with other drawn elements.

Key Takeaway: Canvas text requires setting font, textAlign, and textBaseline properties before calling fillText() or strokeText() to render text exactly where you need it—essential for labels in data visualizations.