I'm trying to word wrap in HTML5 Canvas but I'm struggling!
I've created a TextTyper object which will manage multiple lines of word wrapped text.
The problem I'm having is I'm getting an infinite loop!
I need a solution that uses pure JavaScript (no jQuery) and HTML5 Canvas.
I've made a JSFiddle to help solve my problems and test different strategies: http://jsfiddle.net/Jamesking56/eECar/
Here's my TextTyper Object so far:
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 < words.length; i++)
{
while (ctx.measureText(line.join(' ')) < maxWidth && i < words.length - 1)
{
line.push(words[i++]);
}
if (i < words.length - 1)
{
//Loop ended because line became too wide
line.pop(); //Remove last word
i--; //Take one step back
}
this.lines++;
}
}
}
Any Ideas?
ctx.measureText
returns a newTextMetrics
object, and not the actual width. You'll probably have to change that toctx.measureText(...).width
. Also, if you never emptyline
after you've counted one line, how do you expect to measure the width of a new range of words?