Import a font to use it with node-canvas

I want to use custom fonts with canvas but when I import a file, I copy its url and put it at the time of registering it, it gives me directory not found errors. I also used wget but it didn’t work. ¿What can i do?

Hi @Charbelim, first of all, it can not be a URL. You must include the font directly into your project. You can do so by using git.

Looking at Node-Canvas you have to register your font using registerFont().

For example:

const { registerFont, createCanvas } = require('canvas')
registerFont('comicsans.ttf', { family: 'Comic Sans' })

const canvas = createCanvas(500, 500)
const ctx = canvas.getContext('2d')

ctx.font = '12px "Comic Sans"'
ctx.fillText('Everyone hates this font :(', 250, 10)

Ok, but, where i can get my user token or is my username? and when i use git commit -m, i need to use the font url?

Say the URL for your font is: https://example.com/myFont.ttf and you want to download that into your project. To do so you should open the glitch console and write: curl https://example.com/myFont.ttf > /app/myFont.ttf.

In your code where you use node-canvas you simply register the font like this:

const {registerFont, createCanvas} = require("canvas")
registerFont("/app/myFont.ttf", { family: "myFont" })
const canvas = createCanvas(500, 500);
const ctx = canvas.getContext("2d");
ctx.font = "12px 'myFont'";
// ...

I tried using curl https://cdn.glitch.com/9bdc4dac-69a4-49cf-b860-afa9cf935890%2FRobotoCondensed-Bold.ttf /app/RobotoCondensed-Bold.ttf but didn’t work.

That makes sense, I forgot to add the redirect output operator in the curl command. I’ve edited the post, try taking the new command.

Now it works, thank you!