JIMP中如何指定替代字体?加载字体代码触发TypeError错误
JIMP 字体问题解决方案
先解决你遇到的 cb is not a function 错误
你调用 jimp.loadFont 时同时传了自定义字体路径和内置字体常量,这不符合 API 要求——loadFont 只能接受单个参数:要么是自定义 .fnt 文件的路径,要么是 JIMP 内置的字体常量(比如 jimp.FONT_SANS_8_BLACK)。同时传两个参数会让方法误把第二个参数当成回调函数,而你用了 Promise 的 then 语法,自然触发回调不存在的错误。
正确加载单个字体的写法:
// 加载自定义字体 jimp.loadFont("./Want-coffee-black.fnt").then((customFont) => { // 后续操作 }); // 或者加载内置字体 jimp.loadFont(jimp.FONT_SANS_8_BLACK).then((builtInFont) => { // 后续操作 });
如果需要同时用两个字体,要分别加载:
Promise.all([ jimp.loadFont("./Want-coffee-black.fnt"), jimp.loadFont(jimp.FONT_SANS_8_BLACK) ]).then(([customFont, builtInFont]) => { // 两个字体都加载完成,后续处理 });
实现非英文字符的字体 fallback
JIMP 本身没有内置“字体自动降级”的功能,需要自己手动处理字符判断和分段打印。核心思路是:遍历文本的每个字符,检查是否存在于首选字体的字符集中,不存在的部分用备用字体打印,同时计算好每个片段的位置避免重叠。
示例代码:
const jimp = require("jimp"); // 定义打印文本的函数,支持字体 fallback async function printWithFallback(image, text, x, y, primaryFont, fallbackFont) { let currentX = x; for (const char of text) { // 检查当前字符是否在首选字体的字符集中 const hasChar = primaryFont.chars.hasOwnProperty(char.charCodeAt(0)); const fontToUse = hasChar ? primaryFont : fallbackFont; // 获取字符的宽度,用于计算下一个字符的位置 const charWidth = fontToUse.chars[char.charCodeAt(0)]?.xoffset + fontToUse.chars[char.charCodeAt(0)]?.xadvance || 0; // 打印当前字符 image.print(fontToUse, currentX, y, char); currentX += charWidth; } } // 实际使用 async function main() { const [customFont, builtInFont] = await Promise.all([ jimp.loadFont("./Want-coffee-black.fnt"), jimp.loadFont(jimp.FONT_SANS_8_BLACK) ]); const image = await jimp.create(500, 200, 0xFFFFFFFF); await printWithFallback(image, "Hello 你好 World 世界", 50, 50, customFont, builtInFont); await image.writeAsync("output.png"); } main().catch(err => console.error(err));
这个方法会逐个字符判断,首选字体能显示的用首选,不能显示的切换到备用字体,同时自动计算字符位置保证文本连续。
内容的提问来源于stack exchange,提问作者Aditya Narayan
相关产品推荐
相关产品推荐

