How to set font and size for canvas text in JavaScript

How to set font and size for canvas text in JavaScript

The canvas font property in HTML5 is a string that sets the current text style for all subsequent fillText() and strokeText() calls. It’s not an object or a complex structure – simply a single string with specific syntax that closely mimics the CSS font shorthand property.

Its syntax is simpler but strict:
[font-style] [font-variant] [font-weight] [font-size]/[line-height] [font-family].
Most of these individual pieces are optional except for font-size and font-family. These two must always be present, or the font setting won’t work as intended.

In practice, the most common parts you’ll deal with are font-weight, font-size, and font-family. Optional styles like italic or oblique can be included if you want an angled font.

Here’s a minimal example of setting the font property:

ctx.font = "16px Arial";

This instructs the canvas context to draw text with Arial font at 16 pixels size.

You can chain multiple attributes just like CSS. For example:

ctx.font = "italic bold 14px 'Courier New', monospace";

This sets the font to italic style, bold weight, 14 pixels size, and attempts to use Courier New first; if that’s not available, it falls back to monospace.

The line-height part, although available in CSS, is ignored by canvas fonts. The canvas only respects font-size for vertical spacing.

Font size values generally end with units, commonly px (pixels), but em or pt might be supported inconsistently across browsers. Pixels remain the most reliable, pixel-perfect choice for canvas text rendering.

Remember, the font string is a direct assignment – no intermediate objects or configurations. It requires careful syntax and proper quoting around font family names with spaces:

ctx.font = "bold 18px 'Times New Roman', serif";

Misplaced or missing quotes around the family name, or missing required parts like font size, will cause canvas text drawing to default or fail silently.

Because this property is just a string, dynamically building your font style often involves concatenation or template literals in JavaScript:

let weight = "bold";
let size = 24;
let family = "Verdana";
ctx.font = weight + " " + size + "px " + family;

Or more cleanly with template strings:

ctx.font = ${weight} ${size}px ${family};

The canvas context does not parse or validate this string other than trying to apply it. This means a mistaken property or malformed string simply results in the browser ignoring it or falling back to a default font, without throwing errors.

Practically, you want to keep your font strings clean, predictable, and tested across your target browsers to avoid inconsistent text appearance or sizing issues.

Once your font property is set, any text you draw will render with those exact settings until you assign a new ctx.font. This makes the font property stateful – changing it applies globally within the context for subsequent draw calls.

Defining fonts explicitly ensures consistent text measurement with measureText() too, because the font in effect directly influences the metrics returned.

Keep these rules in your toolkit, and you won’t waste time guessing why your canvas text doesn’t look right or why it suddenly scrambled after a minor tweak to the font string. Setting and managing the font property is one of the most fundamental steps before tackling any canvas text rendering that aims to be precise and professional.

apply font settings effectively to draw text on canvas

After setting the ctx.font property, the natural next step is calling either fillText() or strokeText() to produce the actual visible text on the canvas. Both methods require a string of text along with x and y coordinates to position the baseline of the text.

For example:

ctx.font = "20px Georgia";
ctx.fillStyle = "black";
ctx.fillText("Hello, Canvas!", 50, 100);

This renders the phrase “Hello, Canvas!” in 20px Georgia font, filled in black, starting at position (50, 100) where 100 is the y-coordinate of the text baseline.

It’s important to keep in mind the baseline alignment. The default textBaseline property is “alphabetic”, positioning text relative to typical character baselines, but you can modify it depending on your needs:

ctx.textBaseline = "top";  // position y refers to the top of the text block
ctx.fillText("Aligned Top", 50, 50);

Similarly, you can adjust textAlign to control horizontal alignment:

ctx.textAlign = "center";  // center text horizontally at x coordinate
ctx.fillText("Centered Text", canvas.width / 2, 150);

These alignment properties combined with font settings give you full control over placing and styling text. Without setting the font explicitly beforehand, text will draw using the browser default which is usually a small, sans-serif font that might not fit your design.

When layering multiple text elements on the canvas, change the ctx.font between each set if fonts differ. Fonts do not stack or merge; the last font assignment overrides earlier ones:

ctx.font = "bold 30px Arial";
ctx.fillText("Bold Arial", 20, 50);

ctx.font = "italic 24px Verdana";
ctx.fillText("Italic Verdana", 20, 100);

Using measureText() with the same font setting helps you programmatically position text relative to its width or approximate height. For instance:

ctx.font = "16px Courier New";
let metrics = ctx.measureText("Measure me!");
console.log("Text width: ", metrics.width);
ctx.fillText("Measure me!", 10, 200);
ctx.strokeRect(10, 200 - 16, metrics.width, 16);

This draws the text in Courier New and outlines a rectangle around it using width from the measurement. Although canvas does not provide exact height in TextMetrics, your font size in pixels approximates text height for layout purposes.

Different browsers might render text widths slightly differently depending on the installed fonts and font rendering engine, but consistent ctx.font settings guarantee the closest possible uniformity.

Always pair your font definition with proper fill style or stroke style colors before drawing text. For example:

ctx.font = "italic 22px 'Times New Roman'";
ctx.fillStyle = "#333333";
ctx.fillText("Stylish Italic", 80, 180);

ctx.font = "bold 18px Verdana";
ctx.strokeStyle = "blue";
ctx.strokeText("Outlined Text", 80, 210);

Remember, fill and stroke methods have separate color controls. Setting fillStyle affects fillText(), and setting strokeStyle affects strokeText(). You can combine both commands to create text with both fill and outline.

Efficient canvas text drawing thus involves a tight loop of properly setting font, fillStyle or strokeStyle, and alignment properties before each fillText() or strokeText() call, ensuring your text appears exactly where and how you want.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *