.drawImage函数为画布抛出“ TypeError:预期的图像或画布” [英] .drawImage function is throwing a "TypeError: Image or Canvas expected", for canvas

查看:245
本文介绍了.drawImage函数为画布抛出“ TypeError:预期的图像或画布”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我尝试了require('

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.

错误:

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

TypeError: Image or Canvas expected


推荐答案

节点画布' loadImage() 方法返回 Promise ,该值将解析为< Image>

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

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

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

这篇关于.drawImage函数为画布抛出“ TypeError:预期的图像或画布”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆