node-canvas: Using custom font
Asked Answered
M

2

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.

Modulate answered 11/9, 2015 at 10:57 Comment(1)
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 moduleSchrimsher
P
9

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

Purveyor answered 5/9, 2017 at 23:27 Comment(0)
S
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.

Schrimsher answered 26/10, 2015 at 1:14 Comment(2)
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.Hothouse
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.Schrimsher

© 2022 - 2024 — McMap. All rights reserved.