有没有一种方法可以确定正在呈现的字体系列?

5

有没有办法确定字体样式何时被实际渲染? early stage of breakpoint

在早期阶段(即创建DOM后),在断点上显示段落的字体系列值为 "Montserrat-Bold",该值是通过 @font-face CSS 添加的,但实际显示为默认字体。

break point after some amount of time

这里,在一定时间后的断点显示,段落元素确实被样式化(使用字体系列),如预期所示。

我假设浏览器实际上会渲染(或应用)字体样式。 有没有办法知道或检测何时发生这种情况?


1
这回答你的问题吗?如何在Web字体加载完毕后得到通知 - Dorad
@Dorad 很遗憾没有 :( document.fonts 可以让人知道字体正在被加载,但我的问题是关于它何时实际被“使用”(“渲染”,“应用”)。 - Chanwoo Park
1个回答

1

很遗憾,没有直接的方法(例如通过CSS字体加载API)来获取实际呈现的font-family

解决方法

  1. 通过getComputedStyle(el).fontFamily检查应用的字体系列
  2. 通过FontFaceSet.check()检查字体是否已加载

示例:

let info = document.querySelector('.info');
let textEls = document.querySelectorAll('h1, p, pre');
// check fonts - Monserrat is not yet available
let usedFonts = checkAppliedFont(textEls);

function checkAppliedFont(textEls){
  let usedFonts = [];
  textEls.forEach(function(el,i){
    let nodeType = el.nodeName.toLowerCase();
    let fontFamily = getComputedStyle(el).fontFamily;
    let familyArr = fontFamily.split(',');
    let fontApplied = false;
    let renderedFont = '';
    for(let i=0; i<familyArr.length && !fontApplied; i++){
      let currentFamily = familyArr[i];
      fontApplied = document.fonts.check(`12px ${currentFamily}`);
      if(fontApplied){
        //font is loaded - return family name
        renderedFont = currentFamily;
      }
    }
    usedFonts.push({ type:nodeType, font: renderedFont});
  })
  info.innerText = JSON.stringify(usedFonts)
  return usedFonts;
}


let fontUrl =  "https://fonts.gstatic.com/s/montserrat/v24/JTUHjIg1_i6t8kCHKm4532VJOt5-QNFgpCtr6Hw5aXo.woff2";
let fontFamily = "Montserrat";
let fontOptions = {
  weight: 400,
  style: "normal"
};

let webfont = '';
async function loadFonts() {
  const font = new FontFace(fontFamily, `url(${fontUrl})`);
  font.weight = fontOptions.weight ? fontOptions.weight : 400;
  font.style = fontOptions.style ? fontOptions.style : "normal";
  // wait for font to be loaded
  await font.load();
  webfont = font;
  document.fonts.add(font);
  checkAppliedFont(textEls);
}

function unloadFonts(font) {
  document.fonts.delete(font);
  checkAppliedFont(textEls);
}
h1{
  font-family:"Montserrat", Georgia;
  font-weight:400;
}

p{
  font-family:"Montserrat", Arial
}

pre{
  font-family:"Montserrat", monospace, sans-serif;
  background:#eee;
}
<button onclick="loadFonts()" type="button">Load font</button>
<button onclick="unloadFonts(webfont)" type="button">Delete font</button>
<h1>Should be Monserrat 1234</h1>
<p>Paragraph text.</p>
<pre>Pre text.</pre>
<p class="info"></p>

上面的例子将循环遍历通过getComputedStyle()检索到的CSS规则中指定的所有字体族。
例如:font-family:"Montserrat", monospace, sans-serif
无法使用的字体将被跳过。 第一个可用的字体可能是渲染的字体。

根据您的操作系统或浏览器,这种解决方法可能无法获取实际应用/呈现的字体。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接