1. Carregue o arquivo de fonte
O objeto FontFace é usado principalmente para carregar arquivos de fontes.
// 字体加载
function loadFont(_fontName, _fontUrl) {
// let reg = new RegExp('\\b' + _fontName + '\\b')
// let _fontFamily = document.body.style.fontFamily
// if (reg.test(_fontFamily)) {
// return
// }
if(checkFont(_fontName)) {
console.log('已有字体:', _fontName)
return
}
let prefont = new FontFace(
_fontName,
'url(' + _fontUrl + ')'
);
prefont.load().then(function (loaded_face) {
document.fonts.add(loaded_face);
// document.body.style.fontFamily = (_fontFamily ? _fontFamily + ',' : _fontFamily) + _fontName;
console.log('字体加载成功', loaded_face, document.fonts)
}).catch(function (error) {
console.log('字体加载失败', error)
})
}
Verifique se o arquivo de fonte foi carregado
// 检测字体文件是否已加载
function checkFont(name){
let values = document.fonts.values();
let isHave=false;
let item = values.next();
while(!item.done&&!isHave)
{
let fontFace=item.value;
if(fontFace.family==name)
{
isHave=true;
}
item=values.next();
}
return isHave;
}
2. Use fontes
Basta usar fontFamily em css para atribuir o nome da fonte que você definiu diretamente na tag correspondente.
<div style="font-family: 'simkai';">字体</div>