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

node-canvas registerFont在Windows正常,Linux环境下失效问题求助

解决node-canvas在Linux VPS无法加载自定义字体的问题
  • 安装系统字体依赖库
    Linux环境下node-canvas依赖fontconfig处理字体,先安装对应包:
    Debian/Ubuntu系统执行:apt-get install fontconfig -y
    CentOS/RHEL系统执行:yum install fontconfig -y
    安装完成后重启你的Node.js服务。

  • 验证字体文件有效性
    用系统命令检查字体是否能被识别,执行:
    fc-scan /你的项目路径/assets/Gabrielle.ttf
    如果输出字体元数据(如家族名、样式),说明文件正常;如果报错,重新上传字体文件,避免传输过程中损坏。

  • 明确指定字体属性
    Linux下字体匹配对属性更严格,修改代码补充weight和style参数:

const font = 'Gabrielle';
registerFont(`assets/${font}.ttf`, { 
  family: font,
  weight: 'normal',
  style: 'normal'
});
ctx.font = `normal 24px ${font}`;
  • 将字体安装到系统目录(最稳定方案)
    把字体文件复制到系统字体目录,更新缓存后无需registerFont即可直接使用:
# 复制字体到系统目录
cp assets/Gabrielle.ttf /usr/share/fonts/
# 更新字体缓存
fc-cache -fv

之后代码里直接用ctx.font = '24px Gabrielle';即可。

  • 升级node-canvas版本
    旧版node-canvas在Linux下存在字体加载bug,执行npm install canvas@latest升级到最新稳定版。

用户提供的原始代码:

const font = 'Gabrielle';
registerFont(`assets/${font}.ttf`, { family: font });
ctx.font = `24px ${font}`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:02:08