JS中字体文件的加载和使用

1、加载字体文件

加载字体文件主要用到 FontFace 这个对象

// 字体加载
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)
  })
}

检测字体文件是否已加载

// 检测字体文件是否已加载
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、使用字体

直接在对应的标签上使用 css 中的 fontFamily 赋值你定义的字体名字即可

<div style="font-family: 'simkai';">字体</div>

猜你喜欢

转载自blog.csdn.net/qq_31851435/article/details/132907933