Search code examples
javascriptnode.jsdiscord.js

Error: Unsupported image type / Canvas "Background" || Discord.js V.14


This is my code:

const { createCanvas, loadImage } = require('canvas');

...

// Generate welcome image with user's icon
    const canvas = createCanvas(700, 250);
    const ctx = canvas.getContext('2d');
    const user = interaction.member.user;
    const avatar = await loadImage(user.displayAvatarURL({ format: 'png', size: 256 }));
    const background = await loadImage("https://cdn.discordapp.com/attachments/105735240637265978831/108420311910335197234/image.png"); // Replace with your own background image URL
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2 - 30, 80, 0, Math.PI * 2);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(avatar, canvas.width / 2 - 80, canvas.height / 2 - 110, 160, 160);
    ctx.restore();
    ctx.fillStyle = '#ffffff';
    ctx.font = '36px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(user.username, canvas.width / 2, canvas.height / 2 + 60);
    ctx.font = '24px Arial';
    ctx.fillText(message, canvas.width / 2, canvas.height / 2 + 90);

In the console it replies with:

SetSource.call(img, src)
            ^
Error: Unsupported image type

I checked if the URL in here loadImage("...") is compatible with Canvas and it is (.png). I reinstalled canvas to see if there were any errors but it didn't work.

Some might say that this post is similar to others but trying the other solutions does not work. Any answer is accepted! Thanks!!


Solution

  • It's probably because user.displayAvatarURL({ format: 'png', size: 256 }) will return a webp image in v14 instead of a png and it's an unsupported format.

    To fix this, you will need to replace the format option with extension. The following should work as expected:

    user.displayAvatarURL({ extension: 'png', size: 256 })