7

I would like to know how to use custom font with node-canvas.

Here is my attempt but it does not work so far:

var Canvas = require('canvas')
    , Image = Canvas.Image
    , Font = Canvas.Font
    , path = require('path');

var gubblebum = new Font('gubblebum', fontFile('GUBBLO___.ttf'));

function fontFile(name) {
  return path.join(__dirname, '../fonts', name);
}

function draw() {
  var canvas = new Canvas(100, 100)
    , ctx = canvas.getContext('2d');

  ctx.addFont(gubblebum);
  ctx.font = 'bold 40 gubblebum';
  ctx.fillText('test', 25, 45);

  return canvas;
}

module.exports = draw;

When rendered in a browser, the font is left unchanged from the default, as well as the size.

The font file is correctly loaded. Otherwise, an exception would be thrown.

Interestingly, when I do ctx.font = 'bold 40 someGibberish'; the font size is applied correctly.

mc9
  • 6,121
  • 13
  • 49
  • 87
  • It seems right now that fonts on node-canvas are broken, it looks like you need to disable pango, but I'm still trying to figure out how to do that and rebuild for the module – WakeskaterX Oct 20 '15 at 01:03

2 Answers2

9

This should now "Just Work" in node-canvas 2.0+. See the new Canvas.registerFont method: https://github.com/Automattic/node-canvas/#registerfont.

Community
  • 1
  • 1
ZachB
  • 13,051
  • 4
  • 61
  • 89
2

So I ended up getting node canvas to work with custom fonts.

First I used an older version of Cairo. I used Brew to install all of the dependencies, since it told me which ones I had and which ones were linked correctly, and then once all the dependencies were working correctly, I uninstalled the Cairo version from Brew and installed version 1.12.X (patch version 18 I think it was) of Cairo. This solved a Mac OSX Issue with the font size, but I couldn't load in fonts.

So after some investigation I found there was also an issue with the latest Node Canvas module, so I hard set the version to 1.1.0 in my package.json and FINALLY I got custom fonts to load and size correctly.

So TL;DR: Use Cairo version 1.12.X and Node Canvas 1.1.0 and it should work I think? It took me a while to get it working.

WakeskaterX
  • 1,408
  • 9
  • 21
  • Can you elaborate more on setting this up? Did you clone and compile a Cairo 1.12.X from source? Or did you somehow install an older version via brew? So far I've cloned and built the 1.12.X version from source, but trying to run `npm install canvas` yields more errors, even when setting `PKG_CONFIG_PATH` to the src folder where cairo was compiled. – okcoker Jun 04 '16 at 19:44
  • I had to find it via the source. I went and grabbed the tarball and installed it manually and then replaced the brew version with that and then linked it to the correct required packages. IIRC. It's been a while and I swapped from using node-canvas (because it's a pain) to using node-gd which works better. – WakeskaterX Jun 11 '16 at 22:59