title: Word Wrapping in HTML5 Canvas
body: <p>I'm trying to word wrap in HTML5 Canvas but I'm struggling!</p>
  
  <p>I've created a TextTyper object which will manage multiple lines of word wrapped text.</p>
  
  <p>The problem I'm having is I'm getting an infinite loop!</p>
  
  <p>I need a solution that uses pure JavaScript (no jQuery) and HTML5 Canvas.</p>
  
  <p>I've made a JSFiddle to help solve my problems and test different strategies: <a href="http://jsfiddle.net/Jamesking56/eECar/">http://jsfiddle.net/Jamesking56/eECar/</a></p>
  
  <p>Here's my TextTyper Object so far:</p>
  
  <pre><code>function TextTyper(text, x, y, font, colour) 
  {
      this.text = text || "";
      this.x = x || 20;
      this.y = y || 20;
      this.font = font || false;
      this.colour = colour || [0, 0, 0];
      this.lines = 0;
  
      // Calculate and draw the lines
      this.draw = function () 
      {
          canvas.width = canvas.width;
  
          var maxWidth = (canvas.width - 40);
  
          var words = this.text.split(' ');
          var line = [words[0]]; //begin with a single word
  
          for (var i = 1; i &lt; words.length; i++) 
          {
              while (ctx.measureText(line.join(' ')) &lt; maxWidth &amp;&amp; i &lt; words.length - 1) 
              {
                  line.push(words[i++]);
              }
  
              if (i &lt; words.length - 1) 
              { 
                  //Loop ended because line became too wide
                  line.pop(); //Remove last word
                  i--; //Take one step back
              }
              this.lines++;
          }
      }
  }
  </code></pre>
  
  <p>Any Ideas?</p>