Node canvas use fallback font for unknown characters
Asked Answered
B

1

8

I'm using Node-Canvas to print text on an image and trying to figure out how to ensure strange characters are displayed correctly, even if the main font can't display them.

From what I found online you have to use registerFont with a font that can display those characters to fall back on, but it seems like it doesn't use it automatically, and I couldn't find anything on how to tell it do use a fallback font.

When registering a font that can display the character (Code2000) it still appears like this (the "ᗩ" character isn't displayed correctly):

(Trying to print HELLO WORLD, I'M ᗩcł!)
This is my code:

//load some fallback fonts for custom characters (arial & code2000 in this case)
canvas.registerFont('./Assets/Fonts/arial.ttf', {family: 'Arial'})
canvas.registerFont('./Assets/Fonts/code2000.ttf', {family: 'Code2000'})
//load the Uni Sans Heavy custom font
canvas.registerFont('./Assets/Fonts/Uni_Sans_Heavy.ttf', {family: 'Uni Sans'})
let cnvs = canvas.createCanvas(740, 260)
let ctx = cnvs.getContext('2d')
ctx.fillStyle = "#fff"
ctx.font = '50px Uni Sans'
ctx.fillText(`HELLO WORLD, I'M ᗩcł!`, 50, 100);
    
message.channel.send({files: [{ attachment: cnvs.toBuffer() }]}).catch(allerrors)

The "Code2000" font can display the character correctly for sure, so I thought it'd automatically fall back to that, but it doesn't. Is there a way to use the fallback font automatically? If not, how do I tell it which characters to use it on?

Bobinette answered 15/2, 2022 at 20:36 Comment(1)
You can try blank fonts as a fallback font.Juan
G
3

You just need to specify 'Code2000' when you're setting the font. Consecutive fonts separated by commas are used as fallback fonts.

ctx.font = '50px Uni Sans, Code2000'

I tested this myself, and it worked perfectly.

Grendel answered 28/2, 2022 at 17:19 Comment(3)
Thanks, this worked on my VPS, but for some reason doesn't on my local machine... Any idea what could cause that? I've noticed strange behavior like this to do with fonts a lot, another bug is caused by having a font with the same name installed locally...Bobinette
I would recommend checking what version of node-canvas you have installed on both machines, and ensuring that the font files can be used individually. If there's interference with locally installed fonts, you could try changing the name of the font family when you register it, and use that unique name instead.Grendel
thanks, I'll try that!Bobinette

© 2022 - 2024 — McMap. All rights reserved.