問題描述
我正在嘗試在我的不和諧機器人中添加排名卡,為此我正在嘗試使用畫布但是當我使用畫布時一切正常,直到我點擊 .drawImage
方法.它給了我一個錯誤,說TypeError:Image or Canvas expected".盡管我已經在全局范圍內需要 canvas
,但與 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 required canvas
globally, and everything else that has to do with canvas works properly aswell.
我嘗試在函數內部 require('canvas')
但這也不能解決問題.
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:UsersDesktopDiscordiBotibot.js:25
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
^
TypeError: Image or Canvas expected
推薦答案
node-canvas' loadImage()
方法返回一個 Promise
,它被解析為一個 <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: Image or Canvas expected"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!