Jason H - Wizard
Jason H - Wizard

Reputation: 25

Discord.JS v14 AttachmentBuilder image not showing up in Embed

So, I'm having a bit of trouble with getting an image made from Canvas to display itself within an Embed. I'm not too sure what's going on here, but if I include the attachment as an attachment to the message it seems to show up fine. However, when trying to include it in the embed itself, it doesn't throw any errors and doesn't show up in the Embed sent to the channel.

I've included relevant code below. Maybe, someone can help me here? Much thanks in advance.

    const canvas = Canvas.createCanvas(2000, 2000);
    const context = canvas.getContext('2d');
    const background = await Canvas.loadImage('redacted-link');
    
    context.drawImage(background, 0, 0, canvas.width, canvas.height);

    context.font = '211px sans-serif';
    context.fillStyle = '#ffc22b';

    context.fillText(`${prodsize}`, 230 / 2, 660 / 2);
    context.fillText(`${prodrate}m`, 170 / 2, 1338 / 2);

    if (landsize.length === 2) {
        context.fillText(`${landsize}`, 3175 / 2, 660 / 2);
    } else if (landsize.length === 3) {
        context.fillText(`${landsize}`, 3050 / 2, 660 / 2);
    }

    const attachment = new AttachmentBuilder(await canvas.encode('png'), { name: 'random.png' });

    const embed = new EmbedBuilder()
        .setTitle(`UI Example`)
        .setImage(`attachment://${attachment.name}`)

    interaction.editReply({ embeds: [embed] })

Upvotes: 0

Views: 2423

Answers (1)

Androz2091
Androz2091

Reputation: 3005

You should make sure the files array is filled with your attachment to make it work:

    const canvas = Canvas.createCanvas(2000, 2000);
    const context = canvas.getContext('2d');
    const background = await Canvas.loadImage('redacted-link');
    
    context.drawImage(background, 0, 0, canvas.width, canvas.height);

    context.font = '211px sans-serif';
    context.fillStyle = '#ffc22b';

    context.fillText(`${prodsize}`, 230 / 2, 660 / 2);
    context.fillText(`${prodrate}m`, 170 / 2, 1338 / 2);

    if (landsize.length === 2) {
        context.fillText(`${landsize}`, 3175 / 2, 660 / 2);
    } else if (landsize.length === 3) {
        context.fillText(`${landsize}`, 3050 / 2, 660 / 2);
    }

    const attachment = new AttachmentBuilder(await canvas.encode('png'), { name: 'random.png' });

    const embed = new EmbedBuilder()
        .setTitle(`UI Example`)
        .setImage(`attachment://${attachment.name}`)

    interaction.editReply({ embeds: [embed], files: [attachment] })

Upvotes: 1

Related Questions