检测字体文件中不支持哪些字符字形;传入一段文字内容,返回字体包不支持的字符
const package = require('../package');
const fs = require('fs');
const opentype = require('opentype.js');
function findUnsupportedChars(fontPath, text) {
const font = opentype.loadSync(fontPath);
const unsupportedChars = [];
for (let i = 0; i < text.length; i++) {
let char = text[i];
// 处理多字节字符(如emoji)
if (char.codePointAt(0) > 0xFFFF) {
char = text.slice(i, i + 2); // 假设是四字节字符,取两个JavaScript字符
i++; // 跳过下一个字符,因为它已经是当前字符的一部分了
}
const glyphs = font.stringToGlyphs(char);
// 检查是否找到了对应的glyph,并且该glyph有有效的Unicode属性
let isSupported = false;
for (const glyph of glyphs) {
// console.log('glyph', char, glyph)
// glyph 订 Glyph {
// index: 6142,
// name: '.notdef',
// unicode: 35746,
// unicodes: [ 35746 ],
// xMin: [Getter/Setter],
// xMax: [Getter/Setter],
// yMin: [Getter/Setter],
// yMax: [Getter/Setter],
// advanceWidth: 1000,
// leftSideBearing: 95
// }
if (glyph.name == '.notdef' && glyph.index > 0 && glyph.unicode !== undefined) {
isSupported = true;
break;
}
if ((glyph.unicode !== undefined || glyph.unicodes.length > 0) && glyph.name != '.notdef' && glyph.unicode !== 0) {
isSupported = true;
break;
}
}
// 如果没有找到支持的glyph
if (!isSupported) {
unsupportedChars.push(char);
}
}
return unsupportedChars;
}
// const fontPath = '/usr/share/fonts/yimeng3-fonts/碳纤维正大黑简体.ttf';
// const text = '蕸紦的一堂缔约良缘永结匹配同称十指相扣终于白首王小姐';
// 从命令行参数获取字体文件路径和文本
const [nodePath, scriptPath, fontPath, ...textArgs] = process.argv;
const text = textArgs.join(' '); // 将所有文本参数连接成一个字符串
// 验证命令行参数
if (!fontPath || text.length === 0) {
console.error('Usage: node script.js <fontPath> <text>');
process.exit(1);
}
const unsupportedChars = findUnsupportedChars(fontPath, text);
console.log(JSON.stringify(unsupportedChars));
执行示例:fontparseNew 碳纤维正大黑简体.ttf "蕸紦的一堂缔约良缘永结匹配同称十指相扣终于白首王小姐"
命令行执行返回结果:["蕸","紦"]
分类:
JavaScript
, 字体
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验