5
HTML5キャンバスで単語の折り返しをしようとしていますが、苦労しています!HTML5キャンバスでの単語の折り返し
私は、複数行の折り返しテキストを管理する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++;
}
}
}
任意のアイデアは?
デベロッパーツールを使用してコードを実行すると、問題が見つかるはずです。 –
'ctx.measureText'は新しい' TextMetrics'オブジェクトを返しますが、実際の幅は返しません。おそらくそれを 'ctx.measureText(...)。width'に変更する必要があります。また、1行を数えた後で 'line'を空にしないと、新しい単語の幅をどのように測ることができますか? – Rikonator