node.jsfontspathnode-canvas

Add font to node-canvas


I've been trying for the past hour to add font to my image unsuccessfully. Unfortunately while this may seem like a really easy thing to do I cant get it to work.

const Canvas = require('canvas');
var Font = Canvas.Font;
var BerlinSansFBRegular = Font ? new Font('BerlinSansFBRegular', path.join(__dirname,'./BerlinSansFBRegular.ttf')) : null;

//..

let canvas = new Canvas(GIF_WIDTH, height);
let context = canvas.getContext('2d');
context.addFont(BerlinSansFBRegular);
context.font = `13px BerlinSansFBRegular`;

Directory in windows C:\Users\...\project\fonts\BerlinSansFBRegular.ttf, it probably has something to with the way I am giving my path cause it throws an unhandled promise rejection: Error: Not Found.

Inside the project folder is where my .js file and bat is in.


Solution

  • If I am not mistaken (I don't work on Windows machines anymore), _dirname will return according to Node docs:

    The directory name of the current module That is not the path you are looking for here. You want the path to the Font file, which would be from the root, ../. I think you need to redo your path here:

    new Font('BerlinSansFBRegular', path.join(**__dirname**,'./BerlinSansFBRegular.ttf'))
    

    To make sure I would first put the exact path in the above line:

    new Font('BerlinSansFBRegular', path.join(C:\Users\...\project\fonts\BerlinSansFBRegular.ttf'./BerlinSansFBRegular.ttf'))
    

    and see if it returns correctly, then use the node implementation of root to file.

    Remember, you always have process_cwd to find the current path.

    Hope this helps.