章 24.1 · 篇 III · 实践
集成:页面上的文字
rangeRects、caretRect、caretAt、wordAt、blockAt和wordRangeAt:Markdown中的一段在排好的页面上画在哪里,某个点下面是哪个偏移量、哪个词、哪个块;适用于两端对齐、从右向左、竖排和模板页
简单来说
本页写给开发者。它说明怎样找出原文中的几个词在页面上画在哪里,得到可以在上面涂色的方框。它也说明反过来的做法:有人点了一下,点下面是哪个字、哪个词。这两种做法在从右向左排的页面、竖排的栏和旋转的框里都适用。所有数字都是Markdown原文中的位置,因此和系统存下的数据一致。
从Markdown中的一段找到页面上的方框,再从页面上的一个点回到Markdown。
这些调用读取排好的文档(来自buildDocument或排版worker的VDTDocument),并用canvas、HTML和PDF渲染器绘制文字时所用的同一套代码来定位文字:两端对齐的空格、行末添加的连字符、双向文字的行、从右向左和竖排的页面、首字下沉、章首色带上的标题、经过旋转或缩放的模板页框,以及漫画的对白框。
所有调用都用到两种单位:
- 偏移量是章节Markdown文件中的UTF-16索引,计入front matter,与
sourceAt和VDT中每个sourceStart的计法相同。范围写作{ start, end },不含end。 - 坐标是纸面上的页面px,从纸面左上角算起(页面带裁切线时,纸面包括出血)。乘以绘制页面时的缩放比例即可。
#一段文字在哪里:rangeRects
import { buildDocument, renderPage, rangeRects } from 'postext';
const markdown = '# The apiary\n\nThe keeper walked the hives at dawn, lifting each lid with care.';
const doc = buildDocument({ markdown }, config);
const start = markdown.indexOf('the hives');
const pieces = rangeRects(doc, { start, end: start + 'the hives at dawn'.length });
// [{ pageIndex: 0, blockId: 'b2', rect: { x, y, width, height }, quad: [p0, p1, p2, p3],
// baseline: [left, right], upright: true, fontSize: 13.3 }, …]范围在每一行的每一段连续文字上给出一个片段:跨两行的范围给出两个片段,跨页的范围在两页上各给一个片段。每个片段包含:
| 字段 | 含义 |
|---|---|
pageIndex | 片段所在的页。 |
blockId | 片段所在的块(段落、标题、表格单元格中的块、对白框)。 |
rect | 片段在纸面上与坐标轴对齐的外框:在正立的页面上足够画高亮。 |
quad | 片段的四个角,按行自身的顺序排列(沿行的方向依次为左上、右上、右下、左下)。在竖排页面或旋转的框里,它不是纸面上的矩形:请画出这个多边形。 |
baseline | 片段下方的基线,从片段起点到终点。下划线沿它画。 |
upright | rect与片段完全重合时为真。 |
fontSize | 文字的em,单位px,供需要自己排文字的标记使用。 |
在用renderPage绘制的页面上高亮一个选区:
const scale = 2;
const canvas = renderPage(doc.pages[0], doc, { scale });
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.fillStyle = 'rgb(47 111 214 / 0.3)';
for (const piece of pieces.filter((p) => p.pageIndex === 0)) {
ctx.beginPath();
piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.fill();
}import { buildDocument, renderPageToCanvas, rangeRects, wordAt } from 'https://esm.sh/postext';
const paragraph = 'The keeper walked the hives at dawn, lifting each lid with care and reading the frames for brood, honey and the queen. A hive that hums low in the cold keeps its cluster tight; one that roars at noon wants more room before the flow.';
const markdown = ['# The apiary', paragraph, paragraph].join('\n\n');
const config = {
page: { width: { value: 120, unit: 'mm' }, height: { value: 120, unit: 'mm' } },
bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 12, unit: 'pt' }, lineHeight: { value: 16, unit: 'pt' } },
};
await Promise.all([document.fonts.load('16px "EB Garamond"'), document.fonts.load('bold 16px "Open Sans"')]);
const doc = buildDocument({ markdown }, config);
const page = doc.pages[0];
const canvas = document.getElementById('page');
const scale = 2;
const status = document.getElementById('status');
function paint(range) {
renderPageToCanvas(page, doc, canvas, { scale });
canvas.style.width = `${page.width}px`;
if (!range) return;
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.fillStyle = 'rgb(192 131 0 / 0.35)';
// One piece per run of a line: a word broken by a hyphen gives two.
for (const piece of rangeRects(doc, range).filter((p) => p.pageIndex === 0)) {
ctx.beginPath();
piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.fill();
}
}
canvas.addEventListener('click', (e) => {
// From the screen to page px.
const r = canvas.getBoundingClientRect();
const x = (e.clientX - r.left) * (page.width / r.width);
const y = (e.clientY - r.top) * (page.height / r.height);
const word = wordAt(doc, 0, x, y, markdown);
paint(word);
status.textContent = word ? `“${markdown.slice(word.start, word.end)}” is Markdown ${word.start}–${word.end}` : 'No text there.';
});
paint(null);index.html
<p id="status">Click a word on the page.</p>
<canvas id="page"></canvas>style.css
body {
margin: 0;
padding: 16px;
font-family: system-ui, sans-serif;
background: #ecebe6;
color: #1d1d1f;
}
#status {
margin: 0 0 12px;
min-height: 1.4em;
}
canvas {
display: block;
max-width: 100%;
height: auto;
background: #fff;
box-shadow: 0 2px 10px rgb(0 0 0 / 0.15);
cursor: text;
}从codepen.io加载一个交互式编辑器。示例从CDN导入postext的最新版本。
标注框、插图等不属于正文的块不给出片段;覆盖它们的范围只给出周围文字的片段。被章首色带遮住的文字(色带重复显示的那个标题)不计在内,由色带上的标题给出片段。
#光标:caretRect
caretRect(doc, offset)给出位于字符边界处的光标线:{ pageIndex, blockId, from, to },从文字行的顶部到底部,使用行的坐标系。在竖排页面上,光标横跨栏。偏移量不落在任何已绘制的文字中时,返回null。
#点下面是什么:caretAt、wordAt、blockAt
canvas.addEventListener('click', (e) => {
const r = canvas.getBoundingClientRect();
const x = (e.clientX - r.left) * (doc.pages[0].width / r.width);
const y = (e.clientY - r.top) * (doc.pages[0].height / r.height);
const hit = caretAt(doc, 0, x, y);
// { offset: 57, pageIndex: 0, blockId: 'b2' },点不在文字上时为null
const word = wordAt(doc, 0, x, y, markdown);
// { start: 52, end: 59, pageIndex: 0, blockId: 'b2' }
const block = blockAt(doc, 0, x, y);
// { start: 14, end: 83, pageIndex: 0, blockId: 'b2' }:整个段落的范围
});caretAt给出离点最近的字符边界,就像在文本编辑器里点一下。它找的是最近的块中最近的一行,所以点在两行之间的空白处也会落到其中一行上。在模板页上,画在最上层的框优先。wordAt把这个偏移量扩展为它所在的词,按文档的语言使用Intl.Segmenter切分(中文和日文的词也包括在内),并排除词两端的Markdown强调符号。它接受Markdown原文,也可以接受函数(chapter) => markdown,用于从另一章带过来的文字。blockAt给出块及其在原文中的范围:适合对整个段落加评论。wordRangeAt(markdown, offset, { locale })只在Markdown上做找词这一步,不需要页面。
#章与书
书是一章一章排的,一页上可能有从另一章带过来的文字(VDTBlock.sourceChapter)。选项说明偏移量按哪一份Markdown计算:
rangeRects(doc, range, { chapter: 3, ownChapter: 2 });
caretAt(doc, page, x, y, { ownChapter: 2 }); // 落在带过来的文字上时 → { offset, chapter: 3 }ownChapter是doc所排那一章的位置。chapter等于它或不给,表示文档自己的文件。pages: { from, to }把查找限制在连续的若干页内,用于由几章拼接而成的文档。
点下面的文字属于另一章时,caretAt和wordAt会在回答中给出chapter。
#书写方向与框
调用方式完全不变。在从右向左的页面上,quad从右向左排列,所以quad[0]是片段的右端。在竖排页面上(layout.writingMode: 'vertical-rl'),片段是栏中的一段:它的quad从上往下排,“顶部”是它的右侧,因此沿quad[0]–quad[1]画的下划线就是中文和日文使用的旁线。在旋转了30°的模板页框里,quad也旋转30°。
#底层的部件
postext/geometry导出了构成这些调用的部件,供自己画光标或用自己的方式做点击检测的宿主系统使用:placeLineSegments(行中每一段的绘制位置)、sourceToPlainIndex和plainRangeInLine(Markdown偏移量与绘制文字之间的对应)、blockFrameMatrix和intoBlockSpace(模板页框的矩阵)、bandLineBoxes(章首色带的标题)、sourceHitAt。沙盒自己的canvas预览就用这些部件。
#排版食谱中的示例
用到本页内容的食谱,每道列在最贴切的小节下。每道食谱都把页面和完整脚本并排展示。





