Home > front end >  How can I specify font features when drawing to a HTML canvas?
How can I specify font features when drawing to a HTML canvas?

Time:11-23

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.

CodePudding user response:

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.

CodePudding user response:

You can load fonts with the FontFace API before using it in the canvas:

// new FontFace(familyName, fontSrc, descriptorOnly)
const myFont = new FontFace('My Font', 'url(https://myfont.woff2)');

myFont.load().then((font) => {
  document.fonts.add(font);

  console.log('Font loaded');
});

The font resource myfont.woff2 is first downloaded. Once the download completes, the font is added to the document's FontFaceSet.

The specification of the FontFace API is a working draft at the time of this writing. See browser compatibility table here.

Then, you can use the font parameter to set your font family.

var ctx = document.getElementById('c').getContext('2d');
var kitty = new Image();
kitty.src = 'http://i954.photobucket.com/albums/ae30/rte148/891blog_keyboard_cat.gif';
kitty.onload = function(){
  ctx.drawImage(this, 0,0,this.width, this.height);
  ctx.font         = '68px KulminoituvaRegular';
  ctx.fillStyle = 'orangered';
  ctx.textBaseline = 'top';
  ctx.fillText  ('Keyboard Cat', 0, 270);
};

Note:

  1. You can simply load your font using "@font-face" CSS, but remember, before you draw on canvas, your font must be loaded to the document.

  2. All of your fonts and images (actually all resources) should be and must be within the same origin or cors-origin enabled, otherwise most of the browser will reject the network request.

  • Related