Discord.js TypeError: Image or Canvas expected

I train to make a Canvas using the examples from the documentation.

But for some reason, the code from the example does not work.

What’s wrong?


    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);  

TypeError: Image or Canvas expected
    at Client.client.on.message (/discord-bot/index.js:143:9)
    at Client.emit (events.js:194:15)
    at MessageCreateAction.handle (/discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
    at WebSocket.onMessage (/discord-bot/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:189:13)
    at Receiver.receiverOnMessage (/discord-bot/node_modules/ws/lib/websocket.js:825:20)


const Discord = require("discord.js");
const Canvas = require('canvas');

   client.on('message', message => {
        if (message.content === '!test') {
        const canvas = Canvas.createCanvas(934, 282);
        const ctx = canvas.getContext('2d');
        // we need to await the Promise gets resolved since loading of Image is async
        const background = Canvas.loadImage('./logo.jpg');
        ctx.drawImage(background, 0, 0, canvas.width, canvas.height);  
        const attachment = new Discord.Attachment(canvas.toBuffer(), 'logo.png');
        msg.channel.send(`Testing...`, attachment);

30 thoughts on “Discord.js TypeError: Image or Canvas expected”

  1. 961921 68650Outstanding post. I was checking constantly this blog and Im impressed! Really useful info specially the last part I care for such info much. I was seeking this specific info for a long time. Thank you and greatest of luck. 89649


Leave a Comment