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."
We can change the alignment of the text using the text-align property. We can align the text in the center, Left, Right. The text alignment can be done with CSS(Cascading Style Sheets) and HTML Attribute tag. Note: The left alignment of the text is default.
<br>: The Line Break element. The <br> HTML element produces a line break in text (carriage-return).
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.
So, the problem is actually how to do word-wrapping in HTML5 canvas:
This is all for converting some standard HTML elements which hold text and/or a photo into an HTML5 canvas. And unfortunately, the '.fillText()' method is not smart enough to break a piece of text for me, so I need to "manually" detect each line.
What you might do is measureText
subsequently 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 to fillText
on the next line.
As for the manually inserted line breaks, they are specifically represented in HTML, either by \n
or \r
characters in textareas or by HTML elements, like <br \>
. Thus, before measuring the text you might want to split it by paragraphs.
In textareas:
var paragraphs = textarea.value.split('\n');
In non-form elements:
var paragraphs = [];
// getting all <p> and elements in a typical HTML element
// as well as individual text nodes (they are just DOM-nodes),
// separated by <br /> elements
var innerNodes = nonFormElement.childNodes;
for (var i = 0, len = innerNodes.length; i += 1) {
// if a sub-element has some text in it,
// add the text to our list
var content = innerNodes[i].textContent;
if (content) {
paragraphs.push(content);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With