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

 

posted @   沉迷编程的程序员  阅读(241)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
点击右上角即可分享
微信分享提示