You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Discord.js和node-canvas时画布图片文本无法加载的问题

问题:Discord.js 结合 @napi-rs/canvas 生成的欢迎图片文本不显示

成因分析

  1. @napi-rs/canvas 字体机制限制:该库未内置默认字体集合,当代码中指定 sans-serif 这类通用字体时,库无法自动匹配到可用字体,导致文本绘制失败。
  2. 环境缺失基础字体:如果部署在Linux服务器等无图形界面环境,可能未预装基础字体包,进一步加剧字体找不到的问题。

解决方法

方案1:加载明确字体并指定使用

可以通过加载本地字体文件或确保系统已安装目标字体,让Canvas上下文能识别并渲染文本:

  1. 准备字体文件(比如将Arial.ttf下载到项目的fonts目录下);
  2. 使用 Canvas.loadFont() 提前注册字体;
  3. 在绘图上下文的 font 属性中明确指定该字体名称。

修改后的完整代码示例:

const Canvas = require('@napi-rs/canvas');
const { Client, IntentsBitField, AttachmentBuilder } = require('discord.js');
const path = require('path');

const client = new Client({
    intents: [
        IntentsBitField.Flags.Guilds,
        IntentsBitField.Flags.GuildMembers,
        IntentsBitField.Flags.GuildMessages,
        IntentsBitField.Flags.MessageContent,
    ]
})

client.on('guildMemberAdd', async member => {
    const channel = member.guild.channels.cache.find(channel => channel.name === 'welcome');
    if (!channel) return;

    // 加载本地字体文件,需确保路径正确
    await Canvas.loadFont(path.join(__dirname, 'fonts/Arial.ttf'));

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

    // 绘制背景图
    const background = await Canvas.loadImage('https://raw.githubusercontent.com/discordjs/guide/main/guide/popular-topics/images/canvas.jpg');
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

    // 绘制边框
    ctx.strokeStyle = '#0099ff';
    ctx.strokeRect(0, 0, canvas.width, canvas.height);

    // 指定已加载的字体,确保文本能被渲染
    ctx.font = '30px Arial';
    ctx.fillStyle = '#ffffff';
    // 调整文本起始位置,避免超出画布
    ctx.fillText(`Welcome to the server, ${member.displayName}!`, 50, canvas.height / 2);

    const attachment = new AttachmentBuilder(await canvas.encode('png'), { name: 'welcome-image.png' });
    channel.send({ files: [attachment] });
});

client.login(API_KEY);

方案2:为服务器安装基础字体包

如果部署在Linux服务器,可通过包管理器安装基础字体集合,让系统提供可用的无衬线字体:

  • Debian/Ubuntu系统:执行 sudo apt install fonts-dejavu-core
  • CentOS/RHEL系统:执行 sudo yum install dejavu-sans-fonts

安装完成后,可将代码中的 ctx.font 改为 '30px DejaVu Sans',无需额外加载字体文件即可渲染文本。

额外验证步骤

可以临时调整绘图顺序,先绘制文本再绘制背景图,验证文本本身是否能正常渲染,排除背景覆盖的可能性。

内容的提问来源于stack exchange,提问作者Tabish Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:47:04