Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word Wrapping in HTML5 Canvas

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?

like image 898
Jamesking56 Avatar asked Apr 25 '13 16:04

Jamesking56


People also ask

Is there a way to wrap text in Canva?

To wrap text in Canva, simply click on the “Text” button in the top toolbar. Then, click on the “Wrap Text” icon in the top right-hand corner of the text box (it looks like a spiral).

Can a canvas contain text in HTML?

Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText().

What is word wrap in HTML CSS?

CSS word wrap property is used to break the long words and wrap onto the next line. This property is used to prevent overflow when an unbreakable string is too long to fit in the containing box.


1 Answers

Well, this is what I used for my HTML5 Game : http://jsfiddle.net/eECar/16/

while ( text.length ) {
    for( i=text.length; ctx.measureText(text.substr(0,i)).width > max_width; i-- );

    result = text.substr(0,i);

    if ( i !== text.length )
        for( j=0; result.indexOf(" ",j) !== -1; j=result.indexOf(" ",j)+1 );

    lines.push( result.substr(0, j|| result.length) );
    width = Math.max( width, ctx.measureText(lines[ lines.length-1 ]).width );
    text  = text.substr( lines[ lines.length-1 ].length, text.length );
}

Hope it help.

like image 58
Vincent Thibault Avatar answered Oct 01 '22 00:10

Vincent Thibault