将 TTF(TrueType Font)文件转换为 WOFF2(Web Open Font Format 2.0)是网页字体优化的标准操作。WOFF2 采用了强大的 Brotli 压缩算法,通常比 TTF 文件体积缩小 30% 到 50%,能显著提升网页加载速度。
方法一:使用命令行工具(适合开发者/批量处理)
如果你熟悉命令行,使用 Google 官方的 woff2 或者是 Node.js 工具是最高效的。
1. 使用 Google 官方 woff2 工具
运行后会在同目录下生成一个 font.woff2 文件。
2. 使用 Node.js 工具 (ttf2woff2)
如果你在开发前端项目,可以使用 npm 包:
# 全局安装
npm install -g ttf2woff2
# 转换字体
ttf2woff2 input.ttf output.woff2
方法二:使用 Python 脚本(适合自动化)
Python 的 fonttools 库是字体处理的神器,功能非常强大:
pip install fonttools brotli
安装后,直接在终端运行以下命令即可转换:
pyftsubset font.ttf --woff2 --string="*"
使用WOFF2
通过 @font-face 引入。
为了兼顾极少数老旧浏览器,通常会将 WOFF2 作为第一首选:
@font-face {
font-family: 'MyCustomFont';
src: url('font.woff2') format('woff2'), /* 现代浏览器首选,体积最小 */
url('font.ttf') format('truetype'); /* 备用 */
font-weight: normal;
font-style: normal;
font-display: swap; /* 优化加载体验,防止文字闪烁 */
}
body {
font-family: 'MyCustomFont', sans-serif;
}