Search code examples
javascriptnode.jscanvasdiscord.js

Problem with font registration in Canvas JavaScript


I'm trying to register a font in canvas in order to upload the bot to hosting, I don't get any errors, but the font is simply not displayed on the host. Here is the code

const { AttachmentBuilder } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const Canvas = require('@napi-rs/canvas');

const { registerFont } = require('canvas');
registerFont('./Comic Sans MS.ttf', { family: 'Comic Sans' })

const canvas = Canvas.createCanvas(1150, 800);
        const ctx = canvas.getContext('2d');

        const background = await Canvas.loadImage('./image.png');
        ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

        ctx.fillStyle = '#270a1f';
        ctx.fillRect(0, canvas.height - 400, canvas.width, 400);
 
        ctx.strokeStyle = '#ff033e';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = '#0000ff'
        ctx.beginPath();

what do I enter to make the font appear

ctx.font = '50px "Comic Sans"';
 ctx.fillStyle = '#412227';

I looked through the documentation and didn't find any obvious errors


Solution

  • On some systems ./ is the current working directory instead of the file directory. Instead use process.cwd() or the path module.

    registerFont(`${process.cwd()}/path/Comic Sans MS.ttf`, { family: 'Comic Sans' })
    
    const { resolve } = require("path")
    registerFont(resolve('./Comic Sans MS.ttf'), { family: 'Comic Sans' })