How can I specify font features when drawing to a HTML canvas?


The font I am using on my HTML page supports tabular figures, which is great for presenting rows of currency numbers nicely. They can be activated in CSS by using either:

.table {
  font-variant-numeric: tabular-nums;

or the more low-level way with:

.table {
  font-feature-settings: "tnum" on;

But how do I activate tabular figures when drawing on a JavaScript Canvas object using the CanvasRenderingContext2D.fillText() method? I tried putting the font-feature-settings line within the @font-face CSS block that defines the font to be loaded, but that did only affect the rendering within HTML, not the Canvas drawing.


I think it’s just not supported, but would gladly be proven wrong.

As a workaround, you could use measureText() to find the width of the widest digit, and render the digits individually one by one, using the widest digit’s width as a step size.

Or, if your design allows, you could choose a different font whose figures all have the same width to begin with. This is a fairly common default.

Answered By – Thomas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published