gpt4 book ai didi

javascript - .drawImage 函数为 Canvas 抛出 "TypeError: Image or Canvas expected"

转载 作者:行者123 更新时间:2023-11-29 18:39:20 52 4
gpt4 key购买 nike

我正在尝试在我的 discord 机器人中添加排名卡,为此我正在尝试使用 canvas,但是当我使用 canvas 时一切正常,直到我点击 .drawImage 方法.它给我一个错误提示“TypeError: Image or Canvas expected”。尽管我已经在全局范围内需要 canvas,但与 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

最佳答案

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

关于javascript - .drawImage 函数为 Canvas 抛出 "TypeError: Image or Canvas expected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424581/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com