Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So, the problem is actually <strong>how to do word-wrapping in HTML5 canvas</strong>:</p> <blockquote> <p>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.</p> </blockquote> <p>What you might do is <a href="https://developer.mozilla.org/en/Drawing_text_using_a_canvas#measureText%28%29" rel="nofollow"><code>measureText</code></a> subsequently adding one word at a time. Measure the first word, and if it fits to the width of your container (<code>ctx2d.measureText(words).width &lt;= containerWidth</code>), then you can add another word and measure again. Until the string of words doesn't fit. If it doesn't – you have to <code>fillText</code> on the next line.</p> <p>As for the manually inserted line breaks, they are specifically represented in HTML, either by <code>\n</code> or <code>\r</code> characters in textareas or by HTML elements, like <code>&lt;br \&gt;</code>. Thus, before measuring the text you might want to split it by paragraphs.</p> <p>In textareas:</p> <pre><code>var paragraphs = textarea.value.split('\n'); </code></pre> <p>In non-form elements:</p> <pre><code>var paragraphs = []; // getting all &lt;p&gt; and elements in a typical HTML element // as well as individual text nodes (they are just DOM-nodes), // separated by &lt;br /&gt; 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); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload