Aidan's Bots
Aidan's Bots

Reputation: 5

How do I add text to a image in Node Canvas?

So I have been looking all over the discord.js docs and tried to make a profile card with image manipulation, but for some reason the text comes up as little boxes. Here is the code:


      if (message.content === `-profile`) {\
        const Canvas = require(`canvas`);
        const canvas = Canvas.createCanvas(700, 250);
        const ctx = canvas.getContext('2d');

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

        ctx.strokeStyle = '#74037b';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);

        ctx.font = '100px sans-serif';
        // Select the style that will be used to fill the text in
        ctx.fillStyle = '#34ebc9';
        // Actually fill the text with a solid color
        ctx.fillText(message.author.displayName, canvas.width / 2.5, canvas.height / 1.8);

        ctx.beginPath();
        ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.clip();

        const avatar = await Canvas.loadImage(message.author.displayAvatarURL({ format: 'jpg' }));
        ctx.drawImage(avatar, 25, 25, 200, 200);

        const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'welcome-image.png');

        message.channel.send(`Your profile, ${message.author}!`, attachment);
    }

The image shows and my profile picture shows and everything, but for some reason the text either doesn't show, or it is all messed up. Please help.

Upvotes: 0

Views: 2587

Answers (1)

Your Device maybe doesn't have any default file that Canvas is looking for. You need to install these fonts manually by yourself, you can get some from Google Fonts.

Import the fonts you installed to your Files and use registerFont() to register and use the fonts

//Assume you imported your font in your main folder
const { registerFont, createCanvas } = require('canvas')
registerFont('./comicsans.ttf', { family: 'Comic Sans' })

const canvas = createCanvas(500, 500)
const ctx = canvas.getContext('2d')

ctx.font = '12px "Comic Sans"'
ctx.fillText('Everyone hates this font :(', 250, 10)

Upvotes: 1

Related Questions