例如,给出:
font-family: Montserrat, Helvetica, sans-serif;
Montserrat
正在渲染:
有一种方法可以在JavaScript中获取渲染字体吗? (即使它只是在Chrome中起作用)
该解决方案建议Helvetica
getComputedStyle(...).fontFamily
仍然无法从Web-apis访问此信息。 Houdini集团中正在进行的讨论中,关于包括font-MetricsAPI
̂
方法可用的â
和
document.measureElement
font接口
。该接口将公开两个属性:domstring
document.measureText
和一个数字
name
。 但是,这些仍然是讨论,但仍未提议作为草稿,仍有很多讨论要进行,我不会在任何时候在任何时候在任何地方实施我的呼吸。现在,有hacks,例如其他已经告诉的Q/a已经说过
,这意味着要查看渲染的尺寸,以查看最简单的像素,而是为更高级的像素而言,但在所有情况下都无法入侵。 例如,我的系统上可以使用一种自定义字体,该字体只会渲染一些从众所周知的字体借来的字符,没有这样的黑客能够分辨出浏览器是否确实会后备到该字体或实际知名的字体。确定知道的唯一方法是保持控制和使用Web-font。
update3/15/2025
下面的建议在2024年初起作用,但不再。 如果我想出一个新的片段,我会更新。由于还没有人建议,还有一种方法可以找出哪种字体呈现。
https://developer.mozilla.org/en-us/docs/web/api/css_font_loading_api
,例如,让我们想象CSS是:
glyphsRendered
Snippet
.body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI Adjusted", "Segoe UI", "Liberation Sans", sans-serif;
}
const getRenderedFontFamilyName = ( element ) => {
// Font families set in CSS for the element
const fontFamilies = window.getComputedStyle( element, null ).getPropertyValue( "font-family" );
// const hardcodedFamilies = '-apple-system, BlinkMacSystemFont, "Segoe UI Adjusted", "Segoe UI", "Liberation Sans", sans-serif';
// Remove the " sign from names (font families with spaces in their names) and split names to the array
const fontFamiliesArr = fontFamilies.replaceAll('"', "").split(", ");
// Find the first loaded font from the array
return fontFamiliesArr.find( e => document.fonts.check( `12px ${e}`) );
}