Explain Codes LogoExplain Codes Logo

How do I style HTML5 canvas text to be bold and/or italic?

html
responsive-design
web-development
best-practices
Alex KataevbyAlex Kataev·Sep 10, 2024
TLDR

Canvas text styling in HTML5 is handled through the font property on the Context 2D object. By using a combination of "bold", "italic", a size (in px) and a font family, you can fashion your text as follows:

var ctx = document.getElementById('myCanvas').getContext('2d'); ctx.font = 'bold italic 20px Arial'; // The magic spell for bold and italic ctx.fillText('Bold Italic Text', 50, 100); // Put the text where you wish

In a nutshell, assign ctx.font with your preferred style, then draw your masterpiece with ctx.fillText.

Applying CSS syntax in text styling

Good practice is to use the CSS syntax for the font property when styling your text. This looks like style, weight, size, and family.

ctx.font = 'italic bold 20px Courier'; // "Bold" huh? The gym's been good to you!

In essence:

  • "italic" and "bold" are style parameters.
  • "20px" is the font size.
  • "Courier" is the font family.

Ensure to place the style before size and family in order to get proper text rendering.

Measuring text width and height

You also need to measure your text so as to be sure where to place it using:

var metrics = ctx.measureText('Your Text Here'); // Yup, you can measure invisible text too! var width = metrics.width;

Use this to arrange text with suitable spacing and aligning.

Hacks for text underline

Although underlining text is not natively feasible in canvas, have no fear! Workarounds to the rescue! You can mimic underlines by drawing lines under your text:

ctx.fillText("Am I underlined yet?", 50, 100); ctx.beginPath(); ctx.moveTo(50, 105); ctx.lineTo(50 + width, 105); ctx.stroke(); // How do you like me now?

Manipulate the moveTo and lineTo values to fit your text width and location.

Ensuring cross-browser compatibility

To make sure your code looks as amazing in Firefox as in Chrome, don't forget the golden order of font styling:

ctx.font = 'italic bold 14px sans-serif'; // It's like a secret handshake

Cross-browser compatibility is in the bag if you always respect this order.

Accessible font styling

The principles of web accessibility transcend HTML5 canvas styling. In addition to looking good, consider:

  • Contrast colors between text and background for visibility.
  • Readable font sizes across different devices.
  • Mindful text spacing for users with dyslexia or visual impairments.

Because, let's face it, accessible design is simply good design.