Adding long text inside an HTML element such as a DIV, the element wraps that text. Exactly like this Question text, actually.
How can I take the text from such an HTML element and determine where it breaks? i.e. where a new line is inserted.
For instance, in this box, there’s a new line after “…like this”, one after “…where it” and two after “…is inserted.”
So, the problem is actually how to do word-wrapping in HTML5 canvas:
What you might do is
measureTextsubsequently adding one word at a time. Measure the first word, and if it fits to the width of your container (ctx2d.measureText(words).width <= containerWidth), then you can add another word and measure again. Until the string of words doesn’t fit. If it doesn’t – you have tofillTexton the next line.As for the manually inserted line breaks, they are specifically represented in HTML, either by
\nor\rcharacters in textareas or by HTML elements, like<br \>. Thus, before measuring the text you might want to split it by paragraphs.In textareas:
In non-form elements: