How to know what lines / chars are currently visib

2020-04-02 17:51发布

问题:

Online editor with "live preview": there is a textarea on the left and a preview div on the right. Whenever the textarea changes, the preview is updated.

This works well for small documents; for very long documents however, it becomes sluggish, because the preview has lots of DOM elements that are constantly repainted.

It would be better to only send to the preview, the part of the textarea that is currently visible (since it's the one that needs to be previewed).

There is a heuristic way to get the first visible line of the textarea:

  1. determine current scroll offset of the textarea:
    offset = scrollTop / scrollHeight
    (0 < offset < 1)
  2. the first line that is visible in the textarea is:
    (total number of lines) x offset

However this only works for "short" lines, ie lines that don't wrap. In general, the number of "lines" in a textarea is not the number of linebreaks; a long line, without linebreaks, wraps and might occupy many "line spaces".

One could try to calculate the average number of "line spaces" a line occupies (average number of characters between line breaks, width of textarea, size of font...) but this is wildly imprecise.

Is there a way to know the position of the first and last visible characters in a textarea?

回答1:

Well, as a crazy way for doing it you can look how ACE converts the text into canvas-drawn lines. I assume with this approach you can determine the exact position (or better to say, the exact line objects that are currently visible.

But this could also be a kind of vicious circle if the canvas-generated text is compatible in complexity to what you are having in the preview.

Alternatively you can use a fixed-width font which will give you a knowledge of the exact number of chars in the single line, and thus a way of calculating the exact first / last lines.