在开发中可能涉及到使用其他字体 但是大多数都太大了 需要优化加载的速度 这时候就可以用到字体大小切割了
这里向大家介绍一下 fontmin库 地址
Fontmin是一个用于优化网页字体文件的JavaScript工具库,核心功能是“字体子集化”。它能从完整的字体文件中提取出网页上实际用到的字符,从而将几兆甚至十几兆的字体文件(尤其是中文字体)压缩到几百KB,显著提升网页加载速度。
核心功能一览
| 功能/插件 | 说明 |
|---|
字体子集化 (glyph) | 核心功能。通过分析指定文本,仅保留所需字符字形,生成极小字体文件。 |
| 格式转换 | 支持 ttf2eot, ttf2woff, ttf2svg, otf2ttf 等多种格式互转。 |
CSS生成 (css) | 自动生成 @font-face 等CSS代码,便于网页使用图标字体或自定义字体。 |
SVG图标合并 (svgs2ttf) | 将多个SVG图标文件合并成一个字体文件,方便制作图标字体。 |
使用方法(以下是用koa框架进行的开发)
const path = require('path');
const Fontmin = require('fontmin');
class AppletService {
async generateFontSubset(text, ttfpath, outputPath) {
const fontmin = new Fontmin().src(ttfpath).use(Fontmin.glyph({
text
})).use(Fontmin.ttf2woff({
deflate: true
})).dest(outputPath);
return new Promise((resolve, reject) => {
fontmin.run((err, files) => {
if (err) reject(err);
else resolve(files);
});
});
}
}
module.exports = new AppletService;
const fs = require('fs').promises;
class AppletController extends BaseController {
static async getFont(ctx) {
const { text, fontFamily } = ctx.query;
if (!text || !fontFamily) {
return ctx.body = BaseController.renderJsonFail(303, '参数错误');
}
try {
const fontPath = `xxxx\\font\\今年也要加油鸭.ttf`;
await fs.access(fontPath);
const files = await AppletService.generateFontSubset(text, fontPath, 'xxxx\\subset.ttf');
console.log('Subset files generated:', files)
const woffFile = files.find(f => f.path.endsWith('.woff'));
if (!woffFile) {
throw new Error('生成字体文件失败');
}
ctx.type = 'font/woff2';
ctx.body = woffFile.contents;
} catch (e) {
return ctx.body = BaseController.renderJsonFail(303, e);
}
}
}
const AppletController = require('../controller/AppletController');
router.get('/font',AppletController.getFont)
<style>
@font-face {
font-family: 'CustomFont';
src: url('http://localhost:3000/api/font?text=示例文本&fontFamily=wwww') format('woff2');
}
.custom-text {
font-family: 'CustomFont', sans-serif;
}
</style>
....
<div class="custom-text">示例文本哦哦哦本</div>
....
效果
