Fonts in node-canvas

Make sure you’re using pango-cairo

Pango handles the tricky task of putting text in the right place. If you use node-canvas without Pango, you’ll get blocky and uneven text.

Set FONTCONFIG_PATH and place fonts.conf there

There’s so much stupid history here.

  1. Create a directory, assets/fonts, and copy/paste the fonts.conf from above into it.
  2. Copy all font files for your project into assets/fonts/. They should be .ttf and .otf files.
  3. Before using node-canvas, set the environment variable FONTCONFIG_PATH to point to the directory that holds fonts.conf. You can either do this in your shell (Bash: FONTCONFIG_PATH=assets/fonts node render.js) or within your script (Node: process.env.FONTCONFIG_PATH = './path/to/assets/fonts').

Force FontConfig on Mac OS X and Windows

Mac OS X and Windows don’t use FontConfig by default, and FontConfig is how we’re configuring fonts. Set the environment variable PANGOCAIRO_BACKEND to fontconfig, either in your shell (Bash: PANGOCAIRO_BACKEND=fontconfig FONTCONFIG_PATH=assets/fonts node render.js) or within your script (Node: process.env.PANGOCAIRO_BACKEND = 'fontconfig').

Use ctx._setFont()

The <canvas> way of setting a font is to call ctx.font = 'bold 30px Helvetica';. node-canvas mimics that, but it doesn’t do what your browser does and it can fail (for instance, if your font names contain commas).

Debug with FC_DEBUG, fc-match, fc-list and pango-view

All that’s left is to check font names (which are not filenames), weights, styles, sizes … and the environment variables you created above.

My parting thoughts

At this point, you probably realize that node-canvas is nothing like HTML5 <canvas>. Oops. But there is a cross-platform way to use fonts.



Journalist, ex software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Hooper

Adam Hooper

Journalist, ex software engineer