How do I style HTML5 canvas text to be bold and/or italic?
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:
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.
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:
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:
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:
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.
Was this article helpful?