Thursday, 24 February 2022

Node canvas use fallback font for unknown characters

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?



from Node canvas use fallback font for unknown characters

No comments:

Post a Comment