本文へスキップ

章 24.3 · 部 III · 実践

連携:注釈のマーク

layoutAnnotationsは、ハイライト、下線、取り消し線、行間に書く置換、挿入記号、余白のメモ、囲み線を組まれたページの上に配置する。paintAnnotations、annotationsSvg、annotationAtはそれを描き、点の下にあるマークを探す

更新日 2026-12-049分所属する章: 24 連携enescadeelfritptruzhjaar

かんたんな説明

このページは開発者向けです。ページの上に校正の記号を描く方法を示します。ハイライト、下線、取り消し線、行の上に書き込む新しい言葉、文字を入れる位置の印、余白のメモ、囲み線です。マークは行に沿って描かれ、右から左に組んだページや縦組みの段でも同じです。canvasに描くことも、ページ画像に重ねるSVGの図として書き出すこともできます。マークをクリックすると、それがどのマークかがわかります。

7種類のマークを、テキスト自身の座標系に配置し、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
insertrange.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)です。同じ行にある二つの置換は、重ならないように行に沿って押し離されます。
  • 右から左のページでは、テキストは正しい向きで読めます。縦組みのページでは、テキストは正立し、1文字ずつ段を下っていきます。
  • メモの旗は、重ならないように余白に沿って積まれ、ページからはみ出しません。余白に収まらない長いラベルは省略記号で切り詰めます。ラベル全体は注釈に残っているので、ホストはほかの場所で表示できます。noteSide: 'start' | 'end'を指定すると、いちばん近い余白ではなく、指定した側の余白を使います。
  • measure(text, font)は、ブラウザーのcanvasによる計測の代わりになります。Nodeや、独自のフォントメトリクスを持つホスト向けです。paperはラベルの背後の色です(既定は白)。

#図形

各注釈は、それがかかるページごとに1つの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 })は、1ページ分の図形を、原点がページの左上の角にある2Dコンテキストに描きます。先にページを描き(renderPage、renderPageToCanvas)、そのあとでマークを描きます。コンテキストは呼び出す前の状態に戻ります。

#画像に重ねるSVG:annotationsSvg

import { annotationsSvg } from 'postext/annotate';
 
const svg = annotationsSvg(shapes, doc.pages[0], { pageIndex: 0 });
overlay.innerHTML = svg; // ページの<img>の上に、同じ大きさで
Postext · ページ画像に重ねる校正記号
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からインタラクティブなエディターを読み込みます。サンプルは最新リリースのpostextをCDNから読み込みます。

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でこれを代わりに行います。

#レシピ集の例

このページの内容を使うレシピを、いちばん近い節ごとにまとめました。どのレシピもページとスクリプト全体を並べて見せます。