Marker-pen highlight on mark

The text below is one element drawn by a canvas. Its <mark> elements have no background. The canvas draws a pen stroke for each line that a mark covers, from the boxes that getClientRects() returns, and draws the text over it. Select some words and press Highlight selection to wrap them in a new <mark>. Tap a mark to redraw it with the chosen pen. Switch on editing and type: the strokes follow the new line breaks.

Notes on the mark element

The mark element flags a run of text as relevant. A browser paints it with a flat yellow background. In this canvas that background is off and the canvas draws each stroke under the text, from the boxes that getClientRects() returns. There is one box for each line. Select some words and press the button, or switch on editing and type. The strokes follow the old new line breaks, and a mark that wraps onto a second or a third line gets a separate stroke for each of them. A box is four strokes.

 

Show the code line boxes of a mark, strokes under the text
  1. The text. An article with <mark> elements, as a child of the canvas.
  2. The styles. The mark background is off inside the canvas. --ink carries the colour.
  3. The boxes. One for each line a mark covers, relative to the article.
  4. The strokes. Each pen is a list of polylines with a seeded wobble.
  5. On paint. Paper, ink, then the article with drawElementImage().
  6. Highlight selection. Wrap the selected range in a new <mark>. The change fires paint.

How it works

The article is a child of a <canvas content="drawable">. On every paint event the page asks each <mark> for its client rects. An inline element that wraps returns one rect for each line, so a mark over three lines gives three boxes. The page turns each box into strokes for the mark's pen (data-pen), in the colour of its --ink custom property, and draws them on the canvas. Highlighter and underline strokes are drawn before the article, so the glyphs are on top of the ink. Circle, box and strike strokes are drawn after it.

A stroke is a polyline with small random offsets. The random numbers come from a generator seeded per mark, so the stroke has the same shape on every frame and after an edit. A new mark is drawn in over time: the page draws only the first part of each polyline and asks for another frame until the stroke is complete. When nothing is animating the page requests no frames. Typing, selecting and resizing fire paint themselves.

The text stays a normal element. It can be selected, copied, edited and found. Highlight selection changes the document: it wraps the selected range in a <mark>, which a screen reader and a copy to the clipboard both see.

Live checks

These run on their own fixtures in the corner of the window, after a tap on the button.

Findings