skip to Main Content

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

2

Answers


  1. Try importing GlobalFonts from @napi-rs/canvas, and then using GlobalFonts.registerFromPath().

    This is my code, which works fine for me:

    import { GlobalFonts } from '@napi-rs/canvas';
    // or require for JS
    
    const __dirname = dirname(fileURLToPath(import.meta.url));
    
    GlobalFonts.registerFromPath(
        resolve(__dirname, '..', 'assets', 'Segoe_UI.ttf'),
        'Segoe UI'
    );
    
    ctx.font = '700 20px Segoe UI';
    
    Login or Signup to reply.
  2. 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' })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search