Skip to content

FontFace 的使用

web 添加服务器字体或本地字体支持; 可以使用 css 或者 javascript 两种方式进行添加;

CSS

添加 远程服务字体本地字体

css
@font-face {
  font-family: 'YourFontFamily';
  src: url('https://ssqdoit.top/fonts/YourFontFamily.woff');
}
@font-face {
  font-family: 'YourFontFamily';
  src: url('/fonts/YourFontFamily.woff') format('woff');
}

同 FontFamily 下多字体文件应用

e.g. 添加 Arial FontFamily 下的字体, 设置后即可在浏览器中使用 Arialnormal斜体加粗 字体

Click me to view the code
javascript
// 创建字体样式的对象
var fontStyles = [
  {
    fontFamily: 'Arial',
    fontStyle: 'normal',
    fontWeight: 'normal',
    src: 'url(path/to/arial-normal.ttf) format("truetype")',
  },
  {
    fontFamily: 'Arial',
    fontStyle: 'italic',
    fontWeight: 'normal',
    src: 'url(path/to/arial-italic.ttf) format("truetype")',
  },
  {
    fontFamily: 'Arial',
    fontStyle: 'normal',
    fontWeight: 'bold',
    src: 'url(path/to/arial-bold.ttf) format("truetype")',
  },
  // 添加更多样式的字体...
]

// 动态创建 @font-face 规则并添加到文档中
fontStyles.forEach(function (style) {
  var fontFaceRule = `@font-face { font-family: ${style.fontFamily}; font-style: ${style.fontStyle}; font-weight: ${style.fontWeight}; src: ${style.src}; }`

  var styleElement = document.createElement('style')
  styleElement.innerHTML = fontFaceRule
  document.head.appendChild(styleElement)
})

// 应用字体样式到元素
var myElement = document.getElementById('my-element')
myElement.style.fontFamily = 'Arial, sans-serif'
myElement.style.fontStyle = 'italic'
myElement.style.fontWeight = 'bold'

JavaScript

FontFace

使用 URL 指向的外部资源或 ArrayBuffer 构造并返回一个新的 FontFace 对象。

javascript
const fontFile = new FontFace(
  'YourFontFamily',
  'url(https://ssqdoit.top/fonts/YourFontFamily.woff)'
)
document.fonts.add(fontFile)

fontFile.load().then(
  () => {
    // font loaded successfully!
    // 这里可以使用该字体了
  },
  err => {
    console.error(err)
  }
)

同 FontFamily 下多字体文件应用

e.g. 添加 Arial FontFamily 下的字体, 设置后即可在浏览器中使用 Arialnormalitalicbold 字体

javascript
// 字体 style 和 path 信息
// Regular
let fontFamily = 'Arial'
let url = 'xxxx'
let fontStyle = {
  style: 'normal',
  weight: 'normal',
}
const request = this.fetchFont(fontFamily, basePath + path, fontStyle)
requests.push(request)
// 斜体
lurl = 'xxxx'
fontStyle = {
  style: 'italic',
  weight: 'normal',
}
const request = this.fetchFont(fontFamily, basePath + path, fontStyle)
requests.push(request)
// Regular + 粗体
url = 'xxxx'
fontStyle = {
  style: 'normal',
  weight: 'bold',
}
const request = this.fetchFont(fontFamily, basePath + path, fontStyle)
requests.push(request)
// 粗体+斜体
url = 'xxxx'
fontStyle = {
  style: 'italic',
  weight: 'bold',
}
const request = this.fetchFont(fontFamily, basePath + path, fontStyle)
requests.push(request)

// 等待所有请求完成后进行下一步操作
Promise.all(requests)
  .then(results => {
    // 在这里处理所有请求的结果
    that.Status = 0

    if (null != that.callback) that.callback()
    // 进行下一步操作
  })
  .catch(error => {
    // 处理错误
    that.Status = 1
  })

fetchFont 函数实现

Click me to view the fetchFont Function code
javascript
// 异步请求函数 这里使用的 XMLHttpRequest 进行下载
this.fetchFont = function (fontFamily, url, style) {
  return new Promise((resolve, reject) => {
    // 发起异步请求
    let xhr = new XMLHttpRequest()

    xhr.open('GET', url, true)

    if (typeof ArrayBuffer !== 'undefined') xhr.responseType = 'arraybuffer'

    if (xhr.overrideMimeType)
      xhr.overrideMimeType('text/plain; charset=x-user-defined')
    else xhr.setRequestHeader('Accept-Charset', 'x-user-defined')

    xhr.onload = function () {
      if (this.status != 200) {
        reject()
        return this.onerror()
      }

      if (typeof ArrayBuffer !== 'undefined' && this.response) {
        let font
        if (style) {
          font = new FontFace(fontFamily, this.response, style)
        } else {
          font = new FontFace(fontFamily, this.response)
        }

        document.fonts.add(font)
        font.load().then(
          () => {
            console.log(`${fontFamily} font loaded successfully!`)
            resolve()
          },
          err => {
            console.error(err)
          }
        )
      }
    }

    xhr.onerror = function () {
      reject()
      console.error('err')
    }

    xhr.send(null)
  })
}

Released under the MIT License.