Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet:

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 am I missing to show the font correctly?

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

I've reviewed the documentation extensively but can't seem to pinpoint any obvious mistakes.

Answer №1

Some operating systems will have ./ as the current working directory rather than the file directory. To avoid issues, it is recommended to utilize 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' })

Answer №2

One way to solve this problem is by importing the GlobalFonts module from @napi-rs/canvas, and then using the GlobalFonts.registerFromPath() method.

Below is an example of how you can implement this in your code:

import { GlobalFonts } from '@napi-rs/canvas';
// or use 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';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fullcalendar inaccurately displays events

I recently integrated fullcalendar into my website, but I've come across a strange bug. The event is set up correctly with all the necessary information, yet when the calendar loads, it appears in the wrong position and for the wrong duration. However ...

The button component in my React application is not functioning as expected, despite utilizing the useState and useEffect hooks

I'm having trouble with my Button not working, even though I am using useState and useEffect Check out the code below: import React, { useState, useEffect } from "react"; // import Timeout from "await-timeout"; import ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Hide the address bar in a Google Maps iFrame

After numerous attempts, I still can't seem to hide the address bar on this Google Maps iFrame. Can anyone provide a solution or workaround for this issue? I have tried using display:none; in our CSS, which successfully hides the address bar when I d ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

Using Node and Express to navigate to a URL within a React application

My goal is to open a user-provided URL in a reactjs application using node.js and express. I am incorporating material-ui and axios. Below is the code for the UI: This is a Proof of Concept for a UX testing project where the URL of the application to be ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

Managing waste: AngularJS service variable cleanup

I am a beginner in angularjs. Recently, I created an angularJS service based on the following diagram: The Global Service acts as a way for controllers to communicate with each other. It holds data shared between parent and child controllers. The Grand Pa ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...

What is the significance of a window's "o" condition?

Recently, I came across a code snippet that looks like this: if (!('o' in window)) { o = "somelink"; l =["n", "somelink"]; p = [0.8,1]; d = new Date("2018/01/01"); if (Date.now() >= d) { r = Math.random(); v ...

Unexpected results from the match() function

Attempting to utilize the RegExp feature in Javascript (specifically with the match function) to locate instances of a sentence and a specific word within that sentence embedded in the HTML body. Provided is some pseudo-code for reference: <!DOCTYPE ...

"Silent Passageway: Connecting Node JS to ASW RDS MySQL Through a Secret

I am currently collaborating on a project with a partner. The backbone of our project is node js, and we are using an AWS RDS MySQL DB for our database. Our main challenge lies in establishing effective communication with the DB through SSH within NodeJS. ...

Update the CSS styling of a parent div based on the active state of specific child divs

I have a class with 4 distinct columns. div class="mainContent"> <div class="left-Col-1" *ngIf="data-1"> </div> <div class="left-Col-2" *ngIf="!data-1"> ...

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Should we pass <script> tags or unsanitized values to the Handlebars layout?

How can I pass values to handlebars that are not sanitized upon output? For instance, I want to ensure that when using the code res.render('index', {script: '<script src="bundle.js"></script>'}), it is not rendered as {{scri ...

How can I implement socket.io with multiple files?

I'm encountering an issue with Socket.io in my Express application. I am trying to have two .html files that can send messages to the server, but one of the files is throwing an error: Failed to load resource: net::ERR_FILE_NOT_FOUND add.html:26 Uncau ...

Ways to transfer ID to a different HTML page

I have some Javascript code in a file named nextPage.js. When this code is executed by clicking on something, it should transfer the value of category_id to another page called reportlist.html. Can you please provide assistance with this? var base_url = " ...

Developing an expressjs middleware with customizable parameters

I want to develop a middleware that is capable of accepting parameters. How can I achieve this? For example: app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){ }) HasRole = function(role, req, res, next){ if(role != us ...