# 集成：页面上的文字

> rangeRects、caretRect、caretAt、wordAt、blockAt和wordRangeAt：Markdown中的一段在排好的页面上画在哪里，某个点下面是哪个偏移量、哪个词、哪个块；适用于两端对齐、从右向左、竖排和模板页

- HTML版本: https://postext.dev/zh/docs/integration-geometry
- 最后更新: 2026-12-04
- 阅读时间: 7分钟
- 其他语言: [en](https://postext.dev/en/docs/integration-geometry.md), [es](https://postext.dev/es/docs/integration-geometry.md), [ca](https://postext.dev/ca/docs/integration-geometry.md), [de](https://postext.dev/de/docs/integration-geometry.md), [el](https://postext.dev/el/docs/integration-geometry.md), [fr](https://postext.dev/fr/docs/integration-geometry.md), [it](https://postext.dev/it/docs/integration-geometry.md), [pt](https://postext.dev/pt/docs/integration-geometry.md), [ru](https://postext.dev/ru/docs/integration-geometry.md), [ja](https://postext.dev/ja/docs/integration-geometry.md), [ar](https://postext.dev/ar/docs/integration-geometry.md)

## 简单来说

本页写给开发者。它说明怎样找出原文中的几个词在页面上画在哪里，得到可以在上面涂色的方框。它也说明反过来的做法：有人点了一下，点下面是哪个字、哪个词。这两种做法在从右向左排的页面、竖排的栏和旋转的框里都适用。所有数字都是Markdown原文中的位置，因此和系统存下的数据一致。

**从Markdown中的一段找到页面上的方框，再从页面上的一个点回到Markdown。**

这些调用读取排好的文档（来自`buildDocument`或[排版worker](https://postext.dev/zh/docs/configuration-programmatic-usage.md)的`VDTDocument`），并用canvas、HTML和PDF渲染器绘制文字时所用的同一套代码来定位文字：两端对齐的空格、行末添加的连字符、双向文字的行、从右向左和竖排的页面、首字下沉、章首色带上的标题、经过旋转或缩放的模板页框，以及漫画的对白框。

所有调用都用到两种单位：

- **偏移量**是章节Markdown文件中的UTF-16索引，计入front matter，与`sourceAt`和VDT中每个`sourceStart`的计法相同。范围写作`{ start, end }`，不含end。
- **坐标**是纸面上的页面px，从纸面左上角算起（页面带裁切线时，纸面包括出血）。乘以绘制页面时的缩放比例即可。

## 一段文字在哪里：`rangeRects`

```js
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`绘制的页面上高亮一个选区：

```js
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();
}
```

> **可运行的示例: Postext · 点击处的词** — 在用renderPageToCanvas绘制的页面上点一个词：wordAt给出它在Markdown中的范围，rangeRects把它高亮。 ([源代码](https://github.com/drnachio/postext/tree/main/docs/examples/geometry-highlight))

标注框、插图等不属于正文的块不给出片段；覆盖它们的范围只给出周围文字的片段。被章首色带遮住的文字（色带重复显示的那个标题）不计在内，由色带上的标题给出片段。

## 光标：`caretRect`

`caretRect(doc, offset)`给出位于字符边界处的光标线：`{ pageIndex, blockId, from, to }`，从文字行的顶部到底部，使用行的坐标系。在竖排页面上，光标横跨栏。偏移量不落在任何已绘制的文字中时，返回`null`。

## 点下面是什么：`caretAt`、`wordAt`、`blockAt`

```js
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上做找词这一步，不需要页面。

## 章与书

[书](https://postext.dev/zh/docs/sandbox-books-saving.md)是一章一章排的，一页上可能有从另一章带过来的文字（`VDTBlock.sourceChapter`）。选项说明偏移量按哪一份Markdown计算：

```js
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预览就用这些部件。

## 排版食谱中的示例

### 页面上的文字

- [Nº 212 在页面上选择，读取Markdown范围和文字](https://postext.dev/zh/cookbook/selection-as-markdown-range.md)
- [Nº 215 页边批注，以及按页面坐标放置的弹出框](https://postext.dev/zh/cookbook/margin-notes-with-popovers.md)
- [Nº 219 把搜索结果画在排好的页面上](https://postext.dev/zh/cookbook/search-results-on-pages.md)
- [Nº 216 点击页面，找到源文](https://postext.dev/zh/cookbook/click-to-markdown-source.md)
- [Nº 221 自己的Canvas：renderPage 与 caretAt](https://postext.dev/zh/cookbook/own-canvas-page-view.md)
- [Nº 222 从右到左和竖排页面上的同一套标记](https://postext.dev/zh/cookbook/marks-on-rtl-and-vertical-pages.md)
- [Nº 224 读者的笔记本：给选中的文字写笔记](https://postext.dev/zh/cookbook/reader-notebook.md)
- [Nº 223 读者的荧光笔：一段文字，一种颜色](https://postext.dev/zh/cookbook/reader-highlighter.md)
