章 24.3 · 篇 III · 实践
集成:批注标记
layoutAnnotations在排好的页面上排布高亮、下划线、删除线、写在行间的替换文字、插入符号、页边附注和方框;paintAnnotations、annotationsSvg和annotationAt负责绘制标记,并按点查找标记
简单来说
本页写给开发者。它说明怎样在页面上画校对符号:高亮、下划线、删除线、写在行上方的新词、表示此处插入文字的符号、页边的附注和方框。这些标记沿着文字行走,在从右向左排的页面和竖排的栏里也一样。标记可以画在canvas上,也可以输出为SVG图形,叠在页面图像上。点一下某个标记,就能知道是哪一个。
七种标记,按文字自身的坐标系排布,画在canvas上或输出为SVG。
layoutAnnotations把宿主系统的批注变成纸面上的绘图图元。它了解每一行,所以删除线在字母中部的高度穿过字母,替换文字写在被划掉的词上方的行距里,附注的旗标放到最近的页边,用虚线引线连到它所指的词。
import { layoutAnnotations, paintAnnotations } from 'postext/annotate';
const shapes = layoutAnnotations(doc, [
{ id: 'c1', kind: 'highlight', range: { start: 41, end: 57 } },
{ id: 'c2', kind: 'replace', range: { start: 87, end: 92 }, text: 'young bees' },
{ id: 'c3', kind: 'note', range: { start: 110, end: 115 }, label: '3' },
]);
paintAnnotations(ctx, shapes, { pageIndex: 0, scale: 2 });#标记的种类
| 种类 | 画法 | 使用 |
|---|---|---|
highlight | 在范围的每个片段上铺一层半透明色(35 %,highlightOpacity)。 | color |
underline | 基线下方的一条线;在竖排页面上,是栏右侧的旁线。 | color |
strike | 穿过字母中部的一条线。 | color |
replace | 删除线,并在被划掉的词上方、纸色底衬上写出text。 | text、color |
insert | 在range.start处、行下方的插入符号,上方写出text。 | text、color |
note | 给范围着色,并在页边放一个写有label的旗标,用虚线引线相连。 | label、color |
box | 围绕每个片段的轮廓线。 | color |
批注写作{ id, kind, range, text?, label?, color?, chapter? }。id属于宿主系统,会由annotationAt原样返回。默认颜色(DEFAULT_ANNOTATION_COLORS)与白纸和深色纸(#1e1e1e)的对比度都至少为3:1。按作者或按状态给标记上色的宿主系统,传入color即可。
标记怎样排自己的文字:
- 替换文字和插入文字的字号取自被标记的文字(其em的0.62),字体为
fontFamily(默认system-ui, sans-serif)。同一行上的两处替换文字会沿行推开,绝不重叠。 - 在从右向左的页面上,文字按正确的方向阅读。在竖排页面上,文字正立,一个字一个字沿栏往下排。
- 附注旗标沿页边堆叠,互不重叠,也不会超出页面。页边放不下的长标签用省略号截短;完整的标签仍保存在批注上,宿主系统可以在别处显示。
noteSide: 'start' | 'end'指定使用哪一侧页边,而不是最近的一侧。 measure(text, font)代替浏览器的canvas测量,供Node或自有字体度量的宿主系统使用。paper是标签背后的颜色(默认白色)。
#图形
每条批注在它涉及的每一页上给出一个AnnotationShape:
{
id: 'c2', kind: 'replace', pageIndex: 0, color: '#d6322b',
primitives: [ /* polygon | line | text,按绘制顺序 */ ],
hitAreas: [ /* 纸面上的多边形 */ ],
bounds: { x, y, width, height },
}图元使用纸面上的页面px。宿主系统可以用自己的绘图代码(WebGL、PDF生成器)来画,也可以使用下面两个绘制函数之一。
#画在canvas上:paintAnnotations
paintAnnotations(ctx, shapes, { pageIndex, scale })把一页的图形画在一个2D上下文上,上下文的原点是页面左上角。先画页面(renderPage、renderPageToCanvas),再画标记。上下文会恢复到调用前的状态。
#以SVG叠在图像上:annotationsSvg
import { annotationsSvg } from 'postext/annotate';
const svg = annotationsSvg(shapes, doc.pages[0], { pageIndex: 0 });
overlay.innerHTML = svg; // 叠在页面的<img>上,尺寸相同import { buildDocument, renderPage } from 'https://esm.sh/postext';
import { layoutAnnotations, annotationsSvg, annotationAt } from 'https://esm.sh/postext/annotate';
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: 18, 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 at = (words) => ({ start: markdown.indexOf(words), end: markdown.indexOf(words) + words.length });
// A page image, as a server or the command line would make it.
document.getElementById('page').src = renderPage(page, doc, { scale: 2 }).toDataURL();
const annotations = [
{ id: 'a', kind: 'highlight', range: at('walked the hives') },
{ id: 'b', kind: 'replace', range: at('brood'), text: 'young bees' },
{ id: 'c', kind: 'strike', range: at('low in the cold ') },
// An insertion marks a point: the end of “cluster tight”.
{ id: 'd', kind: 'insert', range: { start: at('cluster tight').end, end: at('cluster tight').end }, text: 'and warm' },
{ id: 'e', kind: 'underline', range: at('roars at noon') },
{ id: 'f', kind: 'note', range: at('queen'), label: '1' },
];
const shapes = layoutAnnotations(doc, annotations);
const overlay = document.getElementById('marks');
overlay.innerHTML = annotationsSvg(shapes, page, { pageIndex: 0 });
// Hit-testing in page px: the mark painted on top first.
overlay.addEventListener('click', (e) => {
const r = overlay.getBoundingClientRect();
const ids = annotationAt(shapes, 0, (e.clientX - r.left) * (page.width / r.width), (e.clientY - r.top) * (page.height / r.height));
const a = annotations.find((x) => x.id === ids[0]);
document.getElementById('status').textContent = a ? `${a.kind} on “${markdown.slice(a.range.start, a.range.end)}”${a.text ? ` → “${a.text}”` : ''}` : 'No mark there.';
});index.html
<figure id="sheet">
<img id="page" alt="The first page of the chapter">
<div id="marks"></div>
</figure>
<p id="status">Click a mark.</p>style.css
body {
margin: 0;
padding: 16px;
font-family: system-ui, sans-serif;
background: #ecebe6;
color: #1d1d1f;
}
/* The SVG has the page's viewBox: it scales with the image under it. */
#sheet {
position: relative;
width: min(100%, 480px);
margin: 0;
box-shadow: 0 2px 10px rgb(0 0 0 / 0.15);
}
#page {
display: block;
width: 100%;
background: #fff;
}
#marks,
#marks svg {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#marks g {
cursor: pointer;
}从codepen.io加载一个交互式编辑器。示例从CDN导入postext的最新版本。
SVG与页面同样大小,viewBox以页面px为单位,所以会随下面的图像一起缩放。每个标记是一个<g data-annotation="c2" data-kind="replace">,可以用CSS设置样式,也能被事件找到。系统已经以图像形式持有页面时,就用这种方法加标记:命令行的postext images、页面缓存、为电子邮件渲染页面的服务器。
#点下面是哪个标记:annotationAt
import { annotationAt } from 'postext/annotate';
const ids = annotationAt(shapes, pageIndex, x, y); // ['c3', 'c1']:最上层的在前每个标记靠它的点击区域查找:范围的各个片段、它的线(留几px余量)、它的标签、它的旗标。一个点落在两个标记上时,两个都返回,按绘制顺序排列,最上层的在前。
#让图形保持最新
图形属于某一次排版。文档重新排版后(文字变了,字号变了),先在新文字中解析批注的锚点,再重新排布批注(见锚点与修改)。查看器在setDocument和setAnnotations时会替你做这件事。
#排版食谱中的示例
用到本页内容的食谱,每道列在最贴切的小节下。每道食谱都把页面和完整脚本并排展示。





