How to get offsetWidth without waiting after setting fontVariationSettings? It is changing after few ms?

huangapple go评论76阅读模式
英文:

How to get offsetWidth without waiting after setting fontVariationSettings? It is changing after few ms?

问题

如何在通过JavaScript设置fontVariationSettings后立即获取offsetWidth而无需等待?然后它在几毫秒后更改,我无法使用等待。

我看到MutationObserver也有延迟!

        span.style.fontFamily = 'Gingham, sans-serif';
        span.textContent = str;
        container.appendChild(span);

        // 设置...
        span.style.fontVariationSettings = 'wdth 140';

        // 获取...
        console.log("当前:", span.offsetWidth) // == 当前:  81
        setTimeout(()=>{
            console.log("1000毫秒后:", span.offsetWidth) // == 1000毫秒后:  74
        },1000)
英文:

How to get offsetWidth without waiting after setting fontVariationSettings via javascript? Then it changes after a few ms and I can't use wait.

I see MutationObserver is also lagging!

        span.style.fontFamily = 'Gingham, sans-serif'; 
        span.textContent = str;
        container.appendChild(span);

        // seting...
        span.style.fontVariationSettings = `'wdth' 140`;

        // geting...
        console.log("now: ", span.offsetWidth) // == now:  81
        setTimeout(()=>{
            console.log("after 1000ms: ", span.offsetWidth) // == after 1000ms:  74
        },1000)

答案1

得分: 1

你不能。您应该等待您的字体被下载并应用以获取更新后的度量信息。

我建议预加载字体,尤其是如果您的代码不是在页面加载时运行。例如,使用数据URL嵌入您的字体。

在我的项目中,我使用了 https://www.npmjs.com/package/fontfaceobserver 来监视字体何时加载,并获取正确的 offsetWidth

英文:

You can't. You should wait your font to be downloaded and applied to get the updated metrics.

I suggest to preload font especially if you code works not on a page load. For example embed your font with a data url.

On my project I used https://www.npmjs.com/package/fontfaceobserver to watch when a font is loaded and get a proper offsetWidth

huangapple
  • 本文由 发表于 2023年6月26日 19:38:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定