今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

How to Detect Which Font Is Actually Rendering in a Browser (Not Just the CSS Stack)

SHOTA 2026年06月27日 23:17 2 次阅读 来源:Dev.to

getComputedStyle(element).fontFamily returns the CSS declaration: "Hiragino Kaku Gothic ProN", "Yu Gothic", "Noto Sans JP", sans-serif . That's not the font that rendered. It's a priority list. The browser picks the first one that's available and contains a glyph for the character being rendered. For Latin text, this distinction usually doesn't matter — Windows, macOS, and Linux have converged on a small set of common system fonts. For Japanese, it matters enormously. The visual weight, stroke contrast, and letterform style of Hiragino, Yu Gothic, and Noto Sans JP are genuinely different. A site designed on macOS (where Hiragino is the system Japanese font) looks different on Windows (where Yu Gothic is the fallback). Here's how to figure out what's actually rendering, and what I learned building Japanese Font Finder to automate it. Why getComputedStyle Doesn't Answer the Question getComputedStyle(el).fontFamily gives you the cascade result — what the browser received after applying all CSS rules. But it doesn't tell you which entry in the stack was selected. The underlying question is: does this font exist on this system, and does it have a glyph for this specific character? For Japanese, both conditions matter. A font might exist on the system but only cover a subset of kanji (common with CJK fonts that split across multiple files). The browser will use that font for characters it covers, and fall back for others. Canvas-Based Font Detection The classical technique uses a <canvas> element to measure text rendered with each font in the stack: function getFallbackWidth ( canvas , char ) { const ctx = canvas . getContext ( ' 2d ' ); ctx . font = `16px monospace` ; // known-available baseline return ctx . measureText ( char ). width ; } function testFont ( fontName , char ) { const canvas = document . createElement ( ' canvas ' ); const ctx = canvas . getContext ( ' 2d ' ); ctx . font = `16px " ${ fontName } ", monospace` ; return ctx . measureText ( char ). width ; }

本文内容来源于互联网,版权归原作者所有
查看原文