之前做類似易企秀的項目需要動態(tài)引入字體脆侮,上代碼
### 按需加載方式
initFont() {
let fontList = [
{
fontUrl: "**.ttf",
fontFamily: "myFirstFont",
label: "草體"
}
];
let code = fontList.reduce((accumulator, currentValue) => {
return accumulator + `@font-face { font-family: ${currentValue.fontFamily};src: url('${currentValue.fontUrl}'); }`;
}, "");
var style = document.createElement("style");
style.type = "text/css";
style.rel = "stylesheet";
style.appendChild(document.createTextNode(code));
var head = document.getElementsByTagName("head")[0];
head.appendChild(style);
console.warn("字體庫加載完成躬窜!", code);
}
全部加載方式
initFont() {
let fontList = [
{
fontUrl: "**.ttf",
fontFamily: "myFirstFont",
label: "草體"
}
];
for (let i in fontList ) {
loadFonts(records[i].fontFamily, records[i].fontUrl);
}
async function loadFonts(fontFamily, fontUrl) {
const font = new FontFace(fontFamily, `url(${fontUrl})`);
await font.load();
document.fonts.add(font);
}
}
參數說明
- fontList為字體資源列表亡呵,然后在需要使用的地方動態(tài)設置fontFamily就行了
- fontUrl 為ttf字體資源鏈接