问题
使用@font-face引入外部字体后,因为加载需要时间,而script中canvas字体渲染时,没有检测到引入的字体,将会使用默认字体
@font-face {
font-family: 'en';
src: url('./font/font.ttf');
}
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, 200, 200)
ctx.beginPath()
ctx.arc(100, 100, 100, 0, Math.PI * 2)
ctx.fillStyle = '#70c000'
ctx.fill()
ctx.fillStyle = '#fff'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.font = '700 150px en'
ctx.fillText('A', 100, 100)
ctx.clip()
解决方法
通过FontFaceSet对象的方法检测字体加载
document.fonts.ready.then(function () {
// 字体加载完成,重绘画布
})
FentFaceSet 接口
FontFaceSet接口的CSS字体加载API管理字体的加载和下载状态的查询
构造
document.fonts接口返回FontFaceSet文件的接口
语法
let fontFaceSet = document.fonts;
属性
FontFaceSet.status
指示字体的加载状态,‘loading’或’loaded’
FontFaceSet.ready
返回promise,一旦字体加载和布局操作完成就会promise就会resolve
方法
FontFaceSet.add() :将字体添加到字体集
FontFaceSet.check():返回Boolean是否加载了字体,但未加载时不会启动加载
FontFaceSet.clear():从字体集中移除所有手动添加的字体, CSS连接字体不受影响(CSS@font-face规则引入字体)
FontFaceSet.delete():从字体集中移除手动添加的字体,CSS连接字体不受影响(CSS@font-face规则引入字体)
FontFaceSet.load():返回Promise它解析为请求的字体的字体面列表。
事件
FontFaceSet.onloading:已开始加载字体面板集时触发
FontFaceSet.onloadingdone:指示字体面板集已完成加载
FontFaceSet.onloadingerror:指示在加载字体面板集时发生错误.