Search code examples
javascriptcanvasdiscorddiscord.jsbots

Discord JS 14. Canvas text on image isn't showing


I try to generate profile picture with a user info, but when i try to add text to it, after generating, text is not showing, only user profile pic.

There is my code:

const { AttachmentBuilder, EmbedBuilder, Client, Events, GatewayIntentBits, Partials } = require('discord.js');
const Canvas = require('@napi-rs/canvas');
const token = require('./config.json');

const client = new Client({ intents: [
    
    GatewayIntentBits.GuildMembers, 
    GatewayIntentBits.GuildPresences,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    ], 
    partials: [Partials.Channel],
});

client.once(Events.ClientReady, () => {
    console.log('Im ready!');
});

client.on('interactionCreate', async i => {
    
    if (i.commandName === "profilepic") {
        const canvas = Canvas.createCanvas(1920, 1080);
        const context = canvas.getContext('2d');
        
        const background = await Canvas.loadImage('./profpic.jpg');
        
        context.drawImage(background, 0, 0, canvas.width, canvas.height);
        
        context.strokeStyle = '#b21f00';
        
        context.strokeRect(0, 0, canvas.width, canvas.height);
        
        context.font = `bold 100px Sans-Serif`
        context.fillStyle = `#ffffff`
        context.fillText("test", 720, canvas.height / 2);
            
        context.beginPath();
        context.arc(879, 350, 115, 0, Math.PI * 2, true);
        context.closePath();
        context.clip();
        
        const avatar = await Canvas.loadImage(i.user.displayAvatarURL({ extension: 'jpg' }));
        
        context.drawImage(avatar, 755, 220, 250, 250);
        
        const attachment = new AttachmentBuilder(await canvas.encode('png'), {name: 'profile-image.png'});
        
        i.reply({files: [attachment]})
}

client.login(token);

I was try to change fonts, size, color(cause maybe i just dont see it lol). But no, there is still no text on my pic


Solution

  • When specifying your font in the line context.font = "bold 100px Sans-Serif"; you don't specify any specific font - You just style it to be sans-serif.

    Look online for different web-safe fonts, and try it like so, replacing Arial with your chosen web font:

    context.font = "bold 100px Arial, sans-serif";
    

    If you require a font of your own, see the section on registering fonts: https://github.com/Automattic/node-canvas#registerfont