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);
}
}