Kurz gesagt
Zwei Seiten eines Buchs über einen Leuchtturm, gezeigt in einer Website mit eigenem Code der Website. Ein Absatz ist blau ausgewählt, ein dünner orangefarbener Cursor steht in einem Wort, und eine Leiste zeigt den ausgewählten Text.
Was Sie setzen
Das zweite Kapitel von A Light on Skerry Rock, einem Buch über einen Leuchtturm, in einer Seitenansicht, die die Website selbst schreibt. Es gibt kein Betrachter-Paket: Jede Seite ist ein Canvas der Website, einmal von renderPage gemalt. Darüber zeichnet die Website eine blaue Auswahl über einen ganzen Absatz und einen orangefarbenen Cursor im Wort „clockwork“. Drücken und ziehen Sie auf einer Seite, um auszuwählen; bewegen Sie den Zeiger, folgt ihm der Cursor von einer Zeichengrenze zur nächsten. Eine Leiste über den Seiten gibt die Auswahl als Markdown mit ihren Positionen aus, also das, was ein Korrekturwerkzeug neben einem Kommentar speichert.
Dieses Rezept beantwortet
- Wie baue ich meine eigene Seitenansicht auf einem Canvas, mit Auswahl, ohne postext-viewer?
Die kurze Antwort
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();
});
}
Zutaten
- Funktionen
- Textgeometrie (Bereiche und Punkte)Seiten auf einem CanvasAnmerkungszeichenSchriften vor dem LayoutGestaltete AuftakteÜberschriftenattributeKolumnentitel und SeitenzahlenGespiegelte RänderSemantische Farbpalette
- Nutzt außerdem
- Kopfzeilen nach Seitenrolle
- Schrift
- Source Serif 4, Source Sans 3 (SIL OFL 1.1)
- Dateien
- Keine: Jedes Bild wird im Code gezeichnet
Zubereitung
#1 · Eine gewöhnliche Buchseite setzen
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),
] };
Die Seitenansicht weiß nichts von der Gestaltung: eine tief angesetzte Eröffnung mit einer Dachzeile aus den Attributen der Überschrift und Kolumnentitel, die mit der Seite die Seite wechseln. Eine andere Konfiguration ergibt andere Seiten, und derselbe Code zeichnet darauf.
#2 · Positionen speichern, nie Pixel
// 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 };
Die Website hält drei Zahlen: wo der Druck begann, wo der Zeiger jetzt ist, und den Cursor. Alle drei sind Positionen im Markdown, sie bedeuten also nach einem Zoom oder einem neuen Umbruch dasselbe, und genau sie speichert ein Kommentar. Der Pen beginnt mit einem ausgewählten Absatz und gesetztem Cursor, damit er zeigt, was er tut, bevor jemand ihn berührt.
#3 · Die Seite malen, dann in Seiten-px darauf zeichnen
Der Code steht in der kurzen Antwort oben. Jede Seite wird einmal in der Größe gemalt, in der sie erscheint; ein Neuzeichnen kopiert diese Bitmap und setzt die Skalierung des Kontexts, sodass die Stücke von rangeRects und die Linie von caretRect so gezeichnet werden, wie sie kommen, in Seiten-px. Jedes Stück wird aus seinem quad gezeichnet, hier ein Rechteck, auf anderen Seiten eine gedrehte oder senkrechte Form. caretAt macht aus dem Zeiger, auf Seiten-px umgerechnet, die nächste Position. Die Dokumentation zu Text auf der Seite nennt jedes Feld.
Das ganze Rezept
// ═══ 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),
<main id="pages">
<section id="view">
<div id="bar" role="status">
<span id="selection"></span>
<span id="offsets"></span>
</div>
<div id="sheets"></div>
</section>
</main>
/* The host's own page view: a status line over the pages, each page a canvas of its own. */
#view {
display: grid; gap: 16px; justify-items: center; align-content: start;
width: min(810px, 100%); min-height: min(608px, 75vw); /* the card's 4:3, pages and bar inside */
}
#bar {
box-sizing: border-box; width: 100%; display: flex; flex-wrap: wrap;
justify-content: space-between; gap: 4px 24px; padding: 10px 16px; border-radius: 6px;
background: #16181d; border: 1px solid #23262d; color: #f4f1ea;
font: 14px/1.4 system-ui, sans-serif;
}
#offsets { color: #b9bcc4; font-variant-numeric: tabular-nums; }
#sheets { display: flex; flex-wrap: wrap; gap: 24px; justify-content: center; }
#sheets canvas {
display: block; max-width: 100%; background: #fff; cursor: text;
touch-action: none; user-select: none;
box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 18px 40px -16px rgb(0 0 0 / .8);
}
Das zusammengesetzte script.js läuft unverändert: Fügen Sie es in das Modulskript einer beliebigen Seite ein, oder öffnen Sie das Rezept auf CodePen. Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)
Varianten
#Ein Wort per Doppelklick auswählen
wordAt erweitert die Position unter dem Punkt auf das umgebende Wort, in der Sprache des Dokuments (neben caretAt importieren).
+ 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();
+ });Nachweise
- Rezept
- Ignacio Ferro
- Text
- Eigener Text, CC BY 4.0
- Schriften
- Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
- Code
- MIT, wie Postext
Diesen Text bearbeiten ↗ (öffnet sich in einem neuen Tab)Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)



