安装
CDN(推荐)
<script src="https://pretext.solaripple.com/lib/pretext/pretext.js"></script>全球 CDN 加速,Gzip 压缩后约 1.2KB,无任何外部依赖。
npm
npm install github:xuegangwu/pretext通过 GitHub 直接安装(需 Node.js 环境)
ES Module
import pretext from 'https://pretext.solaripple.com/lib/pretext/pretext.js';在现代浏览器中直接 import(无需打包工具)
API 参考
pretext.prepare(options)
const handle = pretext.prepare({ text, font?, fontSize?, fontFamily?, letterSpacing? })一次性 Canvas 测量文字,建立词级宽度缓存。同一 text + font 组合只会测量一次,后续调用命中内存缓存。
| 参数 | 类型 | 说明 |
|---|---|---|
text | string | 待测量完整文字 |
font | string | 完整 CSS font 字符串(如 '12px SF Mono, monospace') |
fontSize | number | 字体大小(px),若 font 已含 size 则忽略 |
fontFamily | string | 字体族名 |
letterSpacing | number | 额外字间距(px),默认 0 |
返回值:handle 对象(传入 layout())
pretext.layout(handle, options)
const { height, lines, totalWidth } = pretext.layout(handle, { width })纯算术多行布局计算。无 DOM 访问,无回流。可每秒调用数千次而帧率无影响。
| 参数 | 类型 | 说明 |
|---|---|---|
handle | object | prepare() 返回值 |
options.width | number | 容器最大宽度(px) |
返回值:{ height, lines, totalWidth, lineHeight }
pretext.measureWidth(text, font)
const w = pretext.measureWidth('¥1.234', '12px monospace')单次测量任意字符串宽度,结果会被缓存。适合数字 + 单位等不规则文字的精确宽度。
pretext.clearCache()
pretext.clearCache()清空所有测量缓存。文字内容或字体改变后调用。典型内存占用:1000 个 handle 约 200KB。
Live Demo
pretext.prepare() + pretext.layout() 实战
点击下方按钮查看执行结果...
示例 1: SVG 标签宽度预计算
运行中...
性能
测试环境:Chrome 120 / MacBook Pro M2 · 测量对象:48 个动态标签文字
| 方案 | 单次 | 48 次 | 帧率影响 |
|---|---|---|---|
DOM offsetWidth | ~0.400 ms | ~19.2 ms | 严重卡顿 |
Pretext layout() | ~0.0001 ms | ~0.005 ms | 无影响 |
| 加速比 | ~3,840× | ||