[英]Discord.js TypeError: Image or Canvas expected
I train to make a Canvas using the examples from the documentation.我使用文档中的示例进行训练以制作Canvas 。
But for some reason, the code from the example does not work.但是由于某种原因,示例中的代码不起作用。
What's wrong?怎么了?
■■■■■■ERROR■■■■■■■ ■■■■■■错误■■■■■■■■
/discord-bot/index.js:143
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
^
TypeError: Image or Canvas expected
at Client.client.on.message (/discord-bot/index.js:143:9)
at Client.emit (events.js:194:15)
at MessageCreateAction.handle (/discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/discord-bot/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:189:13)
at Receiver.receiverOnMessage (/discord-bot/node_modules/ws/lib/websocket.js:825:20)
■■■■■■CODE■■■■■■■ ■■■■■■代码■■■■■■■■
const Discord = require("discord.js");
const Canvas = require('canvas');
client.on('message', message => {
if (message.content === '!test') {
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 = Canvas.loadImage('./logo.jpg');
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'logo.png');
msg.channel.send(`Testing...`, attachment);
}
});
It takes time for canvas to load an image so it needs to be asynchronous canvas 加载图像需要时间,因此需要异步
const Discord = require("discord.js");
const Canvas = require('canvas');
client.on('message', async message => {
if (message.content === '!test') {
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('./logo.jpg');
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'message.png'); 'logo.png');
msg.channel.send(`Testing...`, attachment);
}
});
Edit: OP used const attachment = new Discord.Attachment(canvas.toBuffer(), 'logo.png');
编辑:OP used
const attachment = new Discord.Attachment(canvas.toBuffer(), 'logo.png');
instead of the right version const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'logo.png');
而不是正确的版本
const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'logo.png');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.