基于 Pretext 库的文本测量和布局报告工具,支持多语言(包括表情符号、BIDI、CJK)、Canvas 可视化输出。
使用 Pretext 的核心 API:
typescript
// 用例1:简单测量
import { prepare, layout } from '@chenglou/pretext'
const prepared = prepare('你好世界 🚀', '16px Inter')
const { height, lineCount } = layout(prepared, 320, 24)
// 用例2:行级控制
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
const prepared = prepareWithSegments('你好世界 🚀', '16px Inter')
const { lines } = layoutWithLines(prepared, 320, 24)
// 用例3:流式布局
import { layoutNextLine } from '@chenglou/pretext'
let cursor = { segmentIndex: 0, graphemeIndex: 0 }
let y = 0
while (true) {
const width = y < image.bottom ? 300 : 320
const line = layoutNextLine(prepared, cursor, width)
if (line === null) break
ctx.fillText(line.text, 0, y)
cursor = line.end
y += 24
}
typescript
// 测量文本
import { measureText } from '@claw/skills/pretext-reporter-bao'
const result = await measureText('你好世界 🚀', {
font: '16px Inter',
maxWidth: 320,
lineHeight: 24
})
console.log(result)
// {
// text: '你好世界 🚀',
// characterCount: 5,
// lineCount: 1,
// height: 24,
// lines: [{ text: '你好世界 🚀', width: 87.5 }]
// }
typescript
// 生成Canvas可视化
import { generateCanvasReport } from '@claw/skills/pretext-reporter-bao'
const canvas = await generateCanvasReport('你好世界 🚀', {
font: '16px Inter',
maxWidth: 320,
lineHeight: 24,
backgroundColor: '#ffffff',
textColor: '#000000'
})
// 保存或使用Canvas
const png = canvas.toDataURL('image/png')
typescript
// 流式布局(支持图片环绕等)
import { createFlowLayout } from '@claw/skills/pretext-reporter-bao'
const layout = createFlowLayout('你好世界 🚀', {
font: '16px Inter',
lineHeight: 24
})
// 逐行布局
let line
while ((line = layout.nextLine(320)) !== null) {
console.log(line.text, line.width)
}
选项类型默认值说明fontstring'16px Inter'字体(与CSS font属性格式一致)maxWidthnumber320最大宽度(像素)lineHeightnumber24行高(像素)whiteSpace``'normal' | 'pre-wrap'``'normal'空白处理方式backgroundColorstring'#ffffff'Canvas背景色textColorstring'#000000'Canvas文字颜色
markdown
# 文本测量报告
## 基本信息
- 文本:你好世界 🚀
- 字符数:5
- 行数:1
- 字体:16px Inter
## 布局信息
- 最大宽度:320px
- 计算高度:24px
- 行高:24px
## 行详情
| 行号 | 文本 | 宽度 |
|------|------|------|
| 1 | 你好世界 🚀 | 87.5px |
json
{
"text": "你好世界 🚀",
"font": "16px Inter",
"config": {
"maxWidth": 320,
"lineHeight": 24,
"whiteSpace": "normal"
},
"stats": {
"characterCount": 5,
"lineCount": 1,
"height": 24
},
"lines": [
{
"index": 0,
"text": "你好世界 🚀",
"width": 87.5,
"start": { "segmentIndex": 0, "graphemeIndex": 0 },
"end": { "segmentIndex": 0, "graphemeIndex": 5 }
}
]
}
操作时间说明prepare()~19ms500个文本批次(一次性分析)layout()~0.09ms热路径(纯算术计算)layoutWithLines()~0.12ms包含行信息返回
@chenglou/pretext - 核心文本测量库(需手动安装)前置步骤:Pretext 还未发布到 npm,需要手动安装:
bash
# 方式1:从 GitHub 克隆
git clone https://github.com/chenglou/pretext.git
cd pretext
npm install
npm link # 全局链接
# 方式2:在项目中本地引用
# 将 pretext 目录复制到 node_modules/@chenglou/pretext
然后安装本 Skill:
bash
cd skills/pretext-reporter-bao
npm install