node.jstypescriptfontsnode-canvas

node-canvas importing .ttf file into TS for registerFont


I want to use local fonts (ttf format) in a canvas created by node-canvas.

I've created a typings file and added it to my tsconfig:

fonts.d.ts

declare module '*.ttf';

and my fonts are imported and registed:

fonts/index.ts

import * as Font_ComicSans from './comic-sans.ttf';

const Fonts = {
    Font_ComicSans
};

export default Fonts;

component.ts

import Fonts from '../fonts';
import { registerFont } from 'canvas';
...
registerFont(Font_ComicSans, { family: 'Comic Sans' });

However, when the code runs I get the error:

"errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module './comic-sans.ttf'"

I'm using Typescript and NodeJS. Is this the wrong way to import a font (to be used like this)?

I won't use Comic Sans ever again, I promise.


Solution

  • You can just import the font directly in the registerFont function like this:

    registerFont('./comic-sans.ttf', { family: 'Comic Sans')