NodeJS 如何使用画布图像作为嵌入图像,discord js?

carvr3hs  于 2023-03-07  发布在  Node.js
关注(0)|答案(1)|浏览(189)

我尝试使用画布图像为我的信息使用此指南:https://discordjs.guide/popular-topics/canvas.html#setting-up-napi-rs-canvas。我可以使它在作为附件的邮件上工作,但当我试图将它设置为嵌入邮件的setImage时,我不能。
我搜索了一些关于如何使用embed的主题,最后得到了下面的代码,它不起作用,在AttachmentBuilder行抛出了一个错误。
无法将JavaScript值Undefined转换为rust类型String

const canvas = Canvas.createCanvas(700, 250);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage('./myimage.png');
context.drawImage(background, 0, 0, canvas.width, canvas.height);
const attach = new AttachmentBuilder(canvas.toBuffer(), {
  name: 'image.png',
});

const embed = new EmbedBuilder()
  .setAuthor({ name: 'KP', iconURL: avatar })
  .setDescription('Hello')
  .setColor('#F8C8DC')
  .setThumbnail(thumbnail)
  .setImage('attachment://image.png');
client.channels.cache.get(channelId).send({ embeds: [embed], files: [attach] });

[更新1]

关于使用toDataURL的第一个建议不起作用:

const canvas = Canvas.createCanvas(200, 200);
const context = canvas.getContext('2d');
context.fillStyle = 'red';
context.fillRect(0, 0, 200, 200);
const dataURL = canvas.toDataURL();

const embed = new EmbedBuilder()
  .setAuthor({ name: 'KP', iconURL: avatar })
  .setDescription('description..')
  .setColor('#F8C8DC')
  .setThumbnail(thumbnail)
  .setImage(dataURL);
client.channels.cache.get(myChannel).send({ embeds: [embed] });
r8xiu3jd

r8xiu3jd1#

@napi-rs/canvas中,canvas.toBuffer()方法将MIME类型作为参数。因此,您需要使用image/pngimage/jpegimage/webpimage/avif等类型。在您的情况下,应使用以下方法:

const attach = new AttachmentBuilder(canvas.toBuffer('image/png'), {
  name: 'image.png',
});

相关问题