如何在 JavaScript 中检测字体是否支持某个 Unicode 字符?
数据小陈
结论
没有标准浏览器 API 可以直接查询某个字体里有没有某个 Unicode 字符对应的 glyph。document.fonts.check() 只判断字体是否可用或已经加载,不检查字符覆盖;canvas.measureText() 只返回排版宽度,不会告诉你实际用了哪个字体。要可靠判断,优先解析字体文件的 cmap 表。只能在前端做时,可以用 canvas 比较目标字体和 fallback 的像素或宽度,但这属于启发式检测,出现误判并不奇怪。
为什么测量容易不准
- 浏览器会按
font-family列表做字体匹配,缺字时自动 fallback。 - 不同字体可能给同一字符相同宽度,只比较
measureText()的宽度会漏判。 - emoji、组合字符、变体选择符和连字都要经过 shaping,单看一个 code point 的覆盖情况并不完整。
- Web font 可能还没加载完,这时测到的是 fallback,不是目标字体。
- 系统字体在不同平台上的可用性不一样,
Arial本身也不是所有环境都有。
推荐:解析字体文件的 cmap
如果字体文件可控,并且同源或允许 CORS,最可靠的做法是读取字体文件,查它的字符映射表。前端可以用 opentype.js:
import opentype from 'opentype.js';
async function fontSupportsCodePoint(fontUrl, char) {
const res = await fetch(fontUrl);
if (!res.ok) throw new Error('字体加载失败');
const buffer = await res.arrayBuffer();
const font = opentype.parse(buffer);
const codePoint = char.codePointAt(0);
const glyphIndex = font.charToGlyphIndex(String.fromCodePoint(codePoint));
return glyphIndex !== 0;
}
glyphIndex !== 0 是常见判断:OpenType 里 0 通常是 .notdef。不过个别字体可能把某些字符映射到 0,或者字符要依赖 GSUB 才出现,所以仍要结合具体字体验证。这个函数只适合单个 code point;emoji ZWJ 序列、变体选择符和复杂文字都需要 shaping 才能得到最终 glyph。
用 fontkit 也能做类似处理:
import fontkit from 'fontkit';
async function fontSupportsCodePointWithFontkit(fontUrl, char) {
const res = await fetch(fontUrl);
const buffer = await res.arrayBuffer();
const font = fontkit.create(buffer);
return font.hasGlyphForCodePoint(char.codePointAt(0));
}
只能在前端检测时:用 canvas 做启发式判断
如果拿不到字体文件,或者必须检测“当前浏览器会不会用这个字体渲染该字符”,可以比较目标字体和 fallback 的渲染结果。像素对比通常比只比宽度更稳一些:
async function supportsCharacter(fontFamily, char) {
// 对 Web font 尽量等待加载;系统字体可能直接可用
try {
await document.fonts.load(`64px '${fontFamily}'`);
} catch (e) {
// 忽略加载失败,后面会走 fallback
}
await document.fonts.ready;
const size = 64;
const canvas = document.createElement('canvas');
canvas.width = size * 4;
canvas.height = size * 2;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
function render(font) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = `${size}px ${font}`;
ctx.textBaseline = 'top';
ctx.fillStyle = '#000';
ctx.fillText(char, 0, 0);
const width = ctx.measureText(char).width;
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
let hash = 2166136261;
for (let i = 0; i < data.length; i += 4) {
hash ^= data[i] + data[i + 1] * 3 + data[i + 2] * 5 + data[i + 3] * 7;
hash = Math.imul(hash, 16777619);
}
return { width, hash: hash >>> 0 };
}
const target = render(`'${fontFamily}', monospace`);
const fallback = render('monospace');
return target.width !== fallback.width || target.hash !== fallback.hash;
}
调用方式:
await supportsCharacter('Arial', '★');
await supportsCharacter('Arial', 'あ');
这个方案比较的是“当前环境下的渲染结果”,并非字体文件的字符覆盖率。目标字体缺字时会 fallback 到 monospace,按说应该和单独渲染 monospace 接近;如果目标字体支持该字符,像素指纹或宽度通常会不同。但它仍可能因为 fallback 同宽、抗锯齿、子像素渲染、字体 feature 或浏览器差异而误判。
注意事项
document.fonts.check('16px Arial')不能检测 glyph 覆盖,只能辅助判断字体是否可用或已经加载。measureText()只看宽度,遇到等宽字符或碰巧同宽时很容易失效;像素对比更好,但它不是标准 API。- 字体名里有空格时,要在 CSS font-family 中加引号,例如
'Noto Sans SC'。 - 跨域字体文件需要 CORS 才能
fetch,同时也要注意字体许可。 - 代理对字符用
codePointAt(0);包含多个 code point 的 grapheme 要另行处理。 - 如果工具要展示权威结果,建议在服务器端解析字体
cmap,前端只把 canvas 检测作为“浏览器实际渲染”的辅助提示。
备注:内容仅供参考。
