跳到主要内容
食谱编号221

排版食谱 · 第13章 · CMS集成

自己的Canvas:renderPage 与 caretAt

不用 postext-viewer,自己写一个页面视图:renderPage 把每页画一次,rangeRects 画出选区,caretAt 和 caretRect 定位光标。

本页内容
难度
高级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
应用自己画布上的两页:选区用 rangeRects 得到的四边形画出,插入符来自 caretRect,上方是选中的文字和它们的 Markdown 范围。
应用自己画布上的两页:选区用 rangeRects 得到的四边形画出,插入符来自 caretRect,上方是选中的文字和它们的 Markdown 范围。
  • 英文样例:尚无中文版本
  • 成品尺寸130 × 195 mm
  • 1栏
  • Source Serif 4 9.5/13.5
  • Source Sans 3
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时61 ms
  • 157行代码

简单来说

一本讲灯塔的书的两页,用网站自己写的代码显示在网页里。一段文字被选成蓝色,一个细细的橙色光标停在一个词中间,上方的栏显示选中的文字。

成品一览

《A Light on Skerry Rock》是一本讲灯塔的书,这里把它的第二章放进网站自己编写的页面视图里。这里没有查看器包:每页都是网站自己的 canvas,由 renderPage 画一次。网站在上面画出覆盖整段的蓝色选区,以及停在 “clockwork” 一词中间的橙色光标。在页面上按住拖动即可选择;移动指针,光标会跟着它,从一个字符边界移到下一个。页面上方的栏把选区显示为 Markdown 及其位置,这正是审校工具存在评论旁边的内容。

这道食谱解答

  • 不用postext-viewer,怎样在Canvas上做自己的页面视图,并支持选区?

简短回答

script.js · 第132–171行在完整代码中
function paint({ page, pageIndex, scale, base, canvas }) {
  const ctx = canvas.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.drawImage(base, 0, 0);
  ctx.setTransform(scale, 0, 0, scale, 0, 0); // from here on, page px as the layout gives them
  const [start, end] = [state.anchor, state.focus].sort((a, b) => a - b);
  ctx.fillStyle = 'rgb(47 111 214 / 0.28)';
  for (const piece of rangeRects(doc, { start, end }).filter((p) => p.pageIndex === pageIndex)) {
    ctx.beginPath(); // a quad, not a rect: right for turned frames and vertical pages too
    piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
    ctx.fill();
  }
  const caret = caretRect(doc, state.caret); // a line from the text's top to its foot
  if (caret?.pageIndex !== pageIndex) return;
  Object.assign(ctx, { strokeStyle: '#d9480f', lineWidth: 2.5 });
  ctx.beginPath();
  ctx.moveTo(caret.from.x, caret.from.y);
  ctx.lineTo(caret.to.x, caret.to.y);
  ctx.stroke();
}
// The pointer in page px, and the character boundary nearest it.
const hitOf = ({ page, pageIndex, canvas }, e) => {
  const r = canvas.getBoundingClientRect();
  return caretAt(doc, pageIndex, (e.clientX - r.left) * (page.width / r.width),
    (e.clientY - r.top) * (page.height / r.height));
};
for (const view of views) {
  view.canvas.addEventListener('pointerdown', (e) => {
    const hit = hitOf(view, e); // a press starts a new selection where it lands
    if (!hit) return;
    Object.assign(state, { anchor: hit.offset, focus: hit.offset, caret: hit.offset, drag: true });
    update();
  });
  view.canvas.addEventListener('pointermove', (e) => {
    const hit = hitOf(view, e); // the caret follows the pointer; a drag moves the focus too
    if (!hit) return;
    Object.assign(state, { caret: hit.offset }, state.drag && { focus: hit.offset });
    update();
  });
}

用料

类型
Source Serif 4, Source Sans 3(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 排一张普通的书页

script.js · 第32–52行在完整代码中
const opener = { enabled: true, minHeight: mm(36), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase',
    color: col('accent'), placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Source Serif 4',
    fontSize: pt(22), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: { anchor: { to: '#kicker', edge: 'below' },
      offset: { y: mm(2.5) }, size: { width: mm(90) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Source Sans 3', fontSize: pt(7), fontWeight: 600,
  letterSpacing: pt(0.8), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 7),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 7)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };

页面视图对版式一无所知:下沉的开篇,眉题取自标题的属性,书眉随奇偶页换边。换一套配置就得到别的页面,同样的代码照样在上面绘制。

#2 · 存位置,不存像素

script.js · 第122–128行在完整代码中
// The selection runs from `anchor` (where the press began) to `focus` (where the pointer is),
// in either order; the caret is one offset. A zoom or a new layout leaves them valid.
const at = (words) => markdown.indexOf(words);
const [from, to] = t({ en: ['The lens itself', 'paraffin burner.'],
  es: ['La lente misma', 'quemador de parafina.'] });
const state = { anchor: at(from), focus: at(to) + to.length, drag: false,
  caret: at(t({ en: 'clockwork', es: 'mecanismo de relojería' })) + 5 };

网站只保存三个数:按下的起点、指针当前的位置和光标。三者都是 Markdown 中的位置,所以缩放或重新排版之后含义不变,评论保存的也正是它们。这个 pen 打开时已经选好一段、放好光标,不用操作就能看出它做什么。

#3 · 先画页面,再按页面 px 在上面绘制

代码就是上面的简短回答。每页按显示尺寸画一次;重绘时复制这张位图并设置上下文的缩放,于是 rangeRects 的各个片段和 caretRect 的线可以原样绘制,单位是页面 px。每个片段按它的 quad 绘制,这里是矩形,在别的页面上可能是旋转或竖排的形状。caretAt 把换算成页面 px 的指针位置变成最近的位置。页面上的文字文档列出了所有字段。

完整食谱

// ═══ Postext Cookbook · Nº 221 · Your own canvas page view ═════════════════════════════
// https://postext.dev/en/cookbook/own-canvas-page-view
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A page view built by hand, without postext-viewer: each page painted once with renderPage,
// then a selection drawn from rangeRects and a caret from caretAt and caretRect, both following
// the pointer. The pen opens with a selection made and the caret in the next paragraph.
import {
  buildDocumentWithFonts, renderPage, renderPageToCanvas, rangeRects, caretAt, caretRect,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'own-canvas-page-view';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1c1e21', // text
  accent: '#9a3b1f', // a lamp-room red: kicker, rule, folios
  muted: '#62676d', // running heads
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [OUTER, LEAD] = [15, 13.5]; // mm from the outer edge to the folios; pt of body leading

// #region book: a chapter opener and running heads that change side with the page
const opener = { enabled: true, minHeight: mm(36), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Source Sans 3',
    fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase',
    color: col('accent'), placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Source Serif 4',
    fontSize: pt(22), lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: { anchor: { to: '#kicker', edge: 'below' },
      offset: { y: mm(2.5) }, size: { width: mm(90) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'Source Sans 3', fontSize: pt(7), fontWeight: 600,
  letterSpacing: pt(0.8), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#双击选中一个词

wordAt 按文档的语言,把点下的位置扩展到它所在的词(和 caretAt 一起导入)。

+  view.canvas.addEventListener('dblclick', (e) => {
+    const r = view.canvas.getBoundingClientRect();
+    const word = wordAt(doc, view.pageIndex, (e.clientX - r.left) * (view.page.width / r.width),
+      (e.clientY - r.top) * (view.page.height / r.height), markdown);
+    if (!word) return;
+    Object.assign(state, { anchor: word.start, focus: word.end });
+    update();
+  });

致谢

文本
原创文字, CC BY 4.0
字体
Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)