如何证明在HTML5画布对齐文本?

问题描述 投票:6回答:1

我如何能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);
}
html5 canvas html5-canvas
1个回答
2
投票

HTML5的画布不支持多行文字绘图所以要对齐类型没有真正的影响。

如果你想支持线的饲料,你必须自己支持它,你可以在这里看到关于它的前面的讨论:HTML5 Canvas - can I somehow use linefeeds in 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++;
        }
    }

没有用于对齐或有正当理由不支持,你就必须添加它

© www.soinside.com 2019 - 2024. All rights reserved.