字体大小切割

115 阅读2分钟

在开发中可能涉及到使用其他字体 但是大多数都太大了 需要优化加载的速度 这时候就可以用到字体大小切割了

这里向大家介绍一下 fontmin地址

Fontmin是一个用于优化网页字体文件的JavaScript工具库,核心功能是“字体子集化”。它能从完整的字体文件中提取出网页上实际用到的字符,从而将几兆甚至十几兆的字体文件(尤其是中文字体)压缩到几百KB,显著提升网页加载速度。

核心功能一览

功能/插件说明
字体子集化 (glyph)核心功能。通过分析指定文本,仅保留所需字符字形,生成极小字体文件
格式转换支持 ttf2eotttf2woffttf2svgotf2ttf 等多种格式互转
CSS生成 (css)自动生成 @font-face 等CSS代码,便于网页使用图标字体或自定义字体
SVG图标合并 (svgs2ttf)将多个SVG图标文件合并成一个字体文件,方便制作图标字体

使用方法(以下是用koa框架进行的开发)

// 1.编辑Server
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 // 启用WOFF2压缩
        })).dest(outputPath);
        return new Promise((resolve, reject) => {
            fontmin.run((err, files) => {
                if (err) reject(err);
                else resolve(files);
            });
        });
    }
}
module.exports = new AppletService;
// 2.编辑Controller
const fs = require('fs').promises;
class AppletController extends BaseController {
    /** *font
     * 字体分割
     * @param {*} ctx 
     */
    static async getFont(ctx) {
        const { text, fontFamily } = ctx.query;
        if (!text || !fontFamily) {
            return ctx.body = BaseController.renderJsonFail(303, '参数错误');
        }
        try {
            //const fontPath = `./fonts/${fontFamily}.ttf`

            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)
            
            // 找到生成的 woff 文件
            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);
        }

    }
}
// 3.编辑router
const AppletController = require('../controller/AppletController');
router.get('/font',AppletController.getFont)

// 4.使用方法
<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>
....

效果

image.png