Skip to main content
Recipe number 221

Cookbook · Chapter 13 · CMS integration

Your own canvas: renderPage, rangeRects and caretAt

A page view written by hand, without postext-viewer: renderPage paints each page once, rangeRects draws the selection and caretAt and caretRect place the caret.

On this page
Postext
Tested with Postext 1.103.1
Needs ≥ 1.103.0
Licence
Updated 4 Dec 2026
Code MIT · Text CC BY 4.0
Two pages on the app's own canvas: a selection painted as quads from rangeRects and a caret from caretRect, with the selected words and their Markdown range above.
Two pages on the app's own canvas: a selection painted as quads from rangeRects and a caret from caretRect, with the selected words and their Markdown range above.
  • Trim 130 × 195 mm
  • 1 column
  • Source Serif 4 9.5/13.5
  • Source Sans 3
  • 2 pages
  • Level
  • Postext 1.103.1
  • Laid out in 61 ms
  • 157 lines of code

In short

Two pages of a book about a lighthouse, shown inside a web page by code the site wrote itself. A passage is selected in blue, a thin orange caret stands in a word, and a bar above the pages shows the selected text.

What you'll build

The second chapter of A Light on Skerry Rock, a book about a lighthouse, in a page view the site writes itself. There is no viewer package: each page is a canvas of the host's, painted once by renderPage. Over the paint, the host draws a blue selection across a whole paragraph and an orange caret inside the word "clockwork". Press and drag on a page to select; move the pointer and the caret follows it, from one character boundary to the next. A bar above the pages gives the selection as Markdown with its offsets, which is what a review tool stores beside a comment.

This recipe answers

  • How do I build my own page view on a canvas, with selection, without postext-viewer?

The short answer

script.js · lines 132–171in full code
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();
  });
}

Paint the page, then the selection's pieces and the caret, in page px

Ingredients

Type
Source Serif 4, Source Sans 3 (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Set an ordinary book page

script.js · lines 32–52in full code
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),
] };

The page view knows nothing of the design: a sunk opener with a kicker from the heading's attributes, and running heads that change side with the page. A different config gives different pages and the same code draws on them.

#2 · Keep offsets, never pixels

script.js · lines 122–128in full code
// 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 };

The host holds three numbers: where a press began, where the pointer is now, and the caret. All three are offsets into the Markdown, so they mean the same thing after a zoom or a new layout, and they are what a comment keeps. The pen starts with a paragraph selected and the caret placed, so it shows its point before anyone touches it.

#3 · Paint the page, then draw on it in page px

The code is the short answer above. Each page is painted once at the size it is shown, and a repaint copies that bitmap and sets the context's scale, so the pieces of rangeRects and the line of caretRect draw as they come, in page px. A piece is drawn from its quad, which is a rectangle here and a turned or vertical shape on other pages. caretAt turns the pointer, divided down to page px, into the nearest offset. The text on the page docs give every field.

The whole recipe

// ═══ 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),

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Select a word on a double click

wordAt widens the offset under the point to the word around it, in the document's language (import it beside 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();
+  });

Credits

Text
Original prose, CC BY 4.0
Fonts
Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)