gpt4 book ai didi

javascript - 如何使用 Google WebFontLoader 通过 url 加载自定义字体

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:24 24 4
gpt4 key购买 nike

我需要使用 WebFontLoader 在运行时按需加载字体(.ttf、.otf)。

每种字体只有 fontFamily 和 url。

看起来 WebFontLoader 可以选择使用 .css 文件加载字体,例如:

WebFont.load({
custom: {
families: [
'font-family-name'
],
urls: [
'path-to-css'
]
}
});

有没有一种方法可以在没有 .css 文件但使用字体文件的直接路径的情况下实现?

我不想使用任何外部网站来存储我的字体文件。

最佳答案

我发现加载和检测字体已加载的唯一可能方法是创建 <style>元素为 @font-face里面并将其添加到 DOM。

let markup = [
'@font-face {\n',
'\tfont-family: \'', font-family-name, '\';\n',
'\tfont-style: \'normal\';\n',
'\tfont-weight: \'normal\';\n',
'\tsrc: url(\'', font-file-url, '\');\n',
'}\n'
].join('');
});

let style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = markup;

然后就可以使用WebFontLoader来监听事件了:

WebFont.load({
custom: {
families: [
'font-family-name'
],
active: () => {
//triggers when font has been loaded successfully
},
inactive: () => {
//triggers when font loading failed
}
}
});

关于javascript - 如何使用 Google WebFontLoader 通过 url 加载自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com