在浏览器中动态加载字体

正在开发一款用于个性化产品的应用,要实现这么一个功能,由用户上传字体文件并实现预览效果,那么要如何动态加载用户上传的文件…

第一种由 CSS 加载实现

1
2
3
4
5
6
7
8
9
10
11
// 已获取到用户上传的文件

const url = (window.URL || window.webkitURL)['createObjectURL'](file);

const style = document.createElement('style');
style.type = 'text/css';
style.innerText = `\n@font-face {
font-family: '${file.name.replace(/\./g, '-')}';
src: url( '${url}' );
}`;
document.head.appendChild(style);

第二种由 FontFace 实现

1
2
3
4
5
6
7
8
const url = (window.URL || window.webkitURL)['createObjectURL'](file);
const font = new FontFace(file.name.replace(/\./g, '-'), `url(${url})`);
(async () => {
await font.load();
document.fonts.add(font);
this.userUploadFileFont.name = file.name.replace(/\./g, '-');
this.userUploadFileFont.file = file;
})();

由于该功能是一个试验性的功能,我们应该结合在一起使用

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%