canvas绘制网络字体

var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
var link = document.createElement('link')
link.rel = 'stylesheet'
link.type = 'text/css'
link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow'
document.getElementsByTagName('head')[0].appendChild(link)
var image = document.createElement('img')
image.src = link.href
image.onerror = () => {
  document.fonts.load('50px Vast Shadow', '123').then(() => {
    ctx.font = '50px "Vast Shadow"'
    ctx.textBaseline = 'top'
    ctx.fillText('123', 20, 10)
  })
}

我是用Font.js去加载字体,但是第二次才会生效。https://github.com/Pomax/Font.js

优化了下改成,Font.js加载完在onload方法执行以下方法:

var font = new Font(fontFamily);
font.onload=function(evt){
     document.fonts.load('50px Vast Shadow', '123').then(() => {
    //你的代码
  })   
}

重点是必须要使用该字体浏览器才会及时去渲染,

document.fonts.load
原文地址:https://www.cnblogs.com/codeDevotee/p/12340227.html