.drawImage函数为画布引发“ TypeError:预期的图像或画布”

时间:2019-10-17 03:42:25

标签: javascript canvas discord.js

我试图在我的Discord机器人中添加等级卡,为此,我尝试使用canvas,但是当我使用canvas时,一切正常,直到点击.drawImage方法。它给我一个错误,提示“ TypeError:预期图像或画布”。尽管我已经在全球范围内都需要使用('canvas'),但是与画布有关的所有其他事情也都可以正常工作。

我试图在函数内部使用require('canvas'),但这也不能解决问题。

    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);

当它发送消息时,它应该附加图像,但现在它只是给我以下错误。

错误:

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

TypeError: Image or Canvas expected

1 个答案:

答案 0 :(得分:3)

node-canvas' loadImage()方法返回一个Promise,该解析为<Image>

您不能直接通过此Promise,必须等待

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);
相关问题