.drawImage function is throwing a “TypeError: Image or Canvas expected”, for canvas

帅比萌擦擦* 提交于 2020-01-30 07:42:57

问题


I am trying to add a rank card in my discord bot, and in order to do so I am trying to use canvas but when I use canvas everything works fine until I hit the .drawImage method. Where it gives me an error saying "TypeError: Image or Canvas expected". Although I've already require('canvas') globally, and everything else that has to do with canvas works properly as well.

I've tried to require('canvas') inside the function but that doesn't fix the problem either.

    const canvas = Canvas.createCanvas(934, 282);
    const ctx = canvas.getContext('2d');
    const background = Canvas.loadImage('./images/Rank_Card.jpg');

    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);  
    const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png');
    msg.channel.send(`Testing...`, attachment);

When it sends the message it should attach the image with it, but right now its just giving me the following error.

Error:

C:\Users\Desktop\Discord\iBot\ibot.js:25
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
        ^

TypeError: Image or Canvas expected

回答1:


node-canvas' loadImage() method returns a Promise which get resolved to an <Image>.

You can't pass this Promise directly, you'll have to await for it:

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 = await Canvas.loadImage('./images/Rank_Card.jpg');

ctx.drawImage(background, 0, 0, canvas.width, canvas.height);  
const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png');
msg.channel.send(`Testing...`, attachment);


来源:https://stackoverflow.com/questions/58424581/drawimage-function-is-throwing-a-typeerror-image-or-canvas-expected-for-can

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!