javascript - HTML5 Canvas 中的文字换行

标签 javascript html 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++;
        }
    }
}

有什么想法吗?

最佳答案

好吧,这就是我在我的 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 );
}

希望对您有所帮助。

关于javascript - HTML5 Canvas 中的文字换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16220562/

相关文章:

javascript - 如何防止 jQuery 解析插入的 HTML?

javascript - 是否可以通过编程方式控制 svg

html - iOS5 Safari 仅将日期选择器附加到一个输入元素

javascript - 如何在 jsGrid 的列中打印原始 HTML 代码?

javascript - 在另一个 Canvas 中添加 Canvas : obj. setCoords 不是函数(fabric js)

javascript - 为什么我不能获得超过 2 个变量来处理 HTML5 Canvas 和 JavaScript?

javascript - 带有手绘线条的 HTML5 Canvas

javascript - Razor2 网页发布 document.createElement

javascript - d3 用循环嵌套在几个键上

javascript - 使用 onchange 函数获取复选框值