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.
This should now "Just Work" in node-canvas 2.0+. See the new Canvas.registerFont method: https://github.com/Automattic/node-canvas/#registerfont.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With