demo · v144

Selection Drag

Click and drag across canvas text. The demo uses caretPositionFromPoint to convert mouse coordinates to string indices, then getSelectionRects to paint the highlight bands — the same shape every browser-native text widget has, finally available to canvas-based editors.

TextMetrics.getSelectionRects: checking…

selection: none
text:

the API

const ctx = canvas.getContext("2d");
ctx.font = "20px Georgia";
const tm = ctx.measureText(text);

// 1. mouse to caret
canvas.addEventListener("pointerdown", (e) => {
  const pos = ctx.caretPositionFromPoint(e.offsetX, e.offsetY);
  startIndex = pos.offset;
});

// 2. caret range to highlight rects
const rects = tm.getSelectionRects(startIndex, endIndex);
for (const r of rects) ctx.fillRect(r.x, r.y, r.width, r.height);

see also