使用Fabricjs添加文本设置字体不加载

262 阅读1分钟

1,导入字体包

@font-face {
    font-family: Assistant;
    src: url('Assistant.ttf');
}

@font-face {
    font-family: Montserrat;
    src: url('Montserrat.ttf');
}

@font-face {
    font-family: Lato;
    src: url("Lato.ttf");
}

@font-face {
    font-family: Merriweather;
    src: url("Merriweather.ttf");
}

@font-face {
    font-family: OpenSans;
    src: url("OpenSans.ttf");
}

@font-face {
    font-family: Oswald;
    src: url("Oswald.ttf");
}

@font-face {
    font-family: PTSans;
    src: url("PTSans.ttf");
}

@font-face {
    font-family: Roboto;
    src: url("Roboto.ttf");
}

@font-face {
    font-family: Slabo;
    src: url("Slabo.ttf");
}

@font-face {
    font-family: SourceSansPro;
    src: url("SourceSansPro.ttf");
}

@font-face {
    font-family: Zcool_kuaile_regular;
    src: url("zcool-kuaile-regular.woff2");
}

@font-face {
    font-family: long-cang-regular;
    src: url("long-cang-regular.woff2");
}

2,这是字体样式

const changeFont = (t: string) => {
   font.value = t
   canvasContainer.getActiveObject()!.set('fontFamily', font.value)
   canvasContainer.renderAll();
}

3,字体样式不加载

修改字体样式后,network调用了字体包文件,但是canvas画布中字体并没有修改,我自己查询了一系列文档后发现是因为字体包调用成功比设置字体慢

4,解决办法

使用FontFaceObserver库

安装

npm install fontfaceobserver

引入

import FontFaceObserver from 'fontfaceobserver';

使用
const changeFont = (t: string) => {
   font.value = t
   const _font = new FontFaceObserver(t)
   _font.load()
       .then(() =>{
          canvasContainer.getActiveObject()!.set('fontFamily', font.value)
          canvasContainer.renderAll();
       })
}

备注:

canvasContainer = canvas;