【问题标题】:Why is Canvas not working inside of an If statement?为什么 Canvas 在 If 语句中不起作用?
【发布时间】:2021-11-14 17:34:22
【问题描述】:

我试图让我的代码只在数据库给出特定值时显示一段文本。

const canvas = Canvas.createCanvas(250, 250);
const ctx = canvas.getContext('2d');

ctx.fillStyle = message.content;
ctx.fillRect(0, 0, canvas.height, canvas.width)

db.get("label"+message.author.id).then(value => {
   console.log(value)
   if(value == 'on') {
     console.log('true')
       ctx.font = '40px Poppins';
       ctx.fillStyle = '#ffffff';
     ctx.strokeStyle = '#000000'
     ctx.lineWidth = 1; 
       ctx.fillText(message.content, canvas.width/10,       canvas.height / 2 + 20);
          ctx.strokeText(message.content, canvas.width/10, canvas.height / 2 + 20);
   }
})
      

这是我目前所拥有的。不幸的是,无论数据库中的值如何,它都不会添加文本。我已经在没有这些东西的情况下对其进行了测试,它添加了文本。谁能告诉我如何解决这个问题?

编辑:这是我针对此问题的完整代码:

  if(message.content.startsWith('#') && message.content.length == 7) {
      const canvas = Canvas.createCanvas(250, 250);
        const ctx = canvas.getContext('2d');

      ctx.fillStyle = message.content;
      ctx.fillRect(0, 0, canvas.height, canvas.width)

      db.get("label"+message.author.id).then(value => {
        console.log(value)
        if(value == 'on') {
          console.log('true')
            ctx.font = '40px Poppins';
            ctx.fillStyle = '#ffffff';
          ctx.strokeStyle = '#000000'
          ctx.lineWidth = 1; 
            ctx.fillText(message.content, canvas.width/10, canvas.height / 2 + 20);
          ctx.strokeText(message.content, canvas.width/10, canvas.height / 2 + 20);
        }
      })
      

      
        
  const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'color.png');
  message.channel.send(attachment)
 }

【问题讨论】:

  • discord 是否支持画布? (我想你正在写某种机器人)。我没有为不和谐写过任何东西,所以我真的不知道
  • 还有什么当你做console.log(value);

标签: javascript canvas discord.js repl.it


【解决方案1】:

您不是在发送 Canvas 图像,您只是在构建它。完成镜像构建后,应使用Canvas#toBuffer 使其与discordjs#MessageAttachment 兼容。

  const { MessageAttachment } = require('discord.js')
  const canvas = Canvas.createCanvas(250, 250);
  const ctx = canvas.getContext('2d');

  ctx.fillStyle = message.content
  ctx.fillRect(0, 0, canvas.height, canvas.width)

  db.get('label' + message.author.id).then(value => {
    console.log(value)
    if (value == 'on') {
      console.log('true')
      ctx.font = '40px Poppins'
      ctx.fillStyle = '#ffffff'
      ctx.strokeStyle = '#000000'
      ctx.lineWidth = 1
      ctx.fillText(message.content, canvas.width / 10, canvas.height / 2 + 20)
      ctx.strokeText(message.content, canvas.width / 10, canvas.height / 2 + 20)
      message.reply({
        files: [new MessageAttachment(canvas.toBuffer(), 'fileName.png')]
      })
    }
  })

【讨论】:

  • 是的,我把那部分从代码中去掉了,但我有。
猜你喜欢
  • 2014-01-17
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多