10

html5 キャンバス内のテキストを揃えて配置するにはどうすればよいですか? 以下のコードでは、テキストを左/右/中央に揃えることがalign="justify"できます。設定する必要があります。

HTML:

<body onload="callMe()">
    <canvas id="MyCanvas"></canvas>
</body>

JS:

function callMe() {
    var canvas = document.getElementById("MyCanvas");
    var ctx = canvas.getContext("2d");
    var txt = "Welcome to the new hello world example";
    cxt.font = "10pt Arial";
    cxt.textAlign = "left";

    /* code to text wrap*/
    cxt.fillText(txt, 10, 20);
}
4

1 に答える 1

5

HTML5 のキャンバスは複数行のテキスト描画をサポートしていないため、配置タイプには実際の影響はありません。

改行をサポートしたい場合は、自分でサポートする必要があります。それに関する以前の議論をここで見ることができます: HTML5 キャンバス - fillText() で改行を使用できますか?

これはワードラップ/ラインフィードの私の実装です:

    function printAtWordWrap(context, text, x, y, lineHeight, fitWidth) {
        fitWidth = fitWidth || 0;
        lineHeight = lineHeight || 20;

        var currentLine = 0;

        var lines = text.split(/\r\n|\r|\n/);
        for (var line = 0; line < lines.length; line++) {


            if (fitWidth <= 0) {
                context.fillText(lines[line], x, y + (lineHeight * currentLine));
            } else {
                var words = lines[line].split(' ');
                var idx = 1;
                while (words.length > 0 && idx <= words.length) {
                    var str = words.slice(0, idx).join(' ');
                    var w = context.measureText(str).width;
                    if (w > fitWidth) {
                        if (idx == 1) {
                            idx = 2;
                        }
                        context.fillText(words.slice(0, idx - 1).join(' '), x, y + (lineHeight * currentLine));
                        currentLine++;
                        words = words.splice(idx - 1);
                        idx = 1;
                    }
                    else
                    { idx++; }
                }
                if (idx > 0)
                    context.fillText(words.join(' '), x, y + (lineHeight * currentLine));
            }
            currentLine++;
        }
    }

そこには配置や正当化のサポートはありません。追加する必要があります

于 2011-06-29T09:00:44.257 に答える