在HTML5画布中包装的单词

时间:2013-04-25 16:55:42

标签: javascript html5 html5-canvas

我正在尝试在HTML5 Canvas中进行自动换行,但我很挣扎!

我创建了一个TextTyper对象,它将管理多行自动换行文本。

我遇到的问题是我的循环无限!

我需要一个使用纯JavaScript(无jQuery)和HTML5 Canvas的解决方案。

我已经建立了一个JSFiddle来帮助解决我的问题并测试不同的策略:http://jsfiddle.net/Jamesking56/eECar/

到目前为止,这是我的TextTyper对象:

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

任何想法?

1 个答案:

答案 0 :(得分:2)

嗯,这就是我用于HTML5游戏的内容: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 );
}

希望有所帮助。