demo ยท v144

Hit-test Canvas Text

The headline motivation in the WICG explainer: canvas-based editors (Figma, Google Docs in canvas mode) need to convert a click position into a caret index. Before Chrome 144 they shipped their own glyph layouts. caretPositionFromPoint gives them the answer the browser already knows.

caretPositionFromPoint / getSelectionRects: checking…

click on the text…

the API

const m = ctx.measureText(str);
const idx = m.caretPositionFromPoint(localX, localY);
const rect = m.getSelectionRects(0, idx)[0];   // selection from start to caret
// Pixel -> character index, the answer the browser knows internally.

see also