HTML5   发布时间:2022-04-26  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何证明在html5画布中对齐文本?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在 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的画布不支持多行文本绘制,因此对齐类型没有实际效果.

如果你想支持换行,你必须自己支持,你可以在这里看到之前的讨论: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],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(' '),y + (lineHeight * currentLinE));
                        currentLine++;
                        words = words.splice(idx - 1);
                        idx = 1;
                    }
                    else
                    { idx++; }
                }
                if (idx > 0)
                    context.fillText(words.join(' '),y + (lineHeight * currentLinE));
            }
            currentLine++;
        }
    }

那里不支持对齐或对齐,你必须添加

大佬总结

以上是大佬教程为你收集整理的如何证明在html5画布中对齐文本?全部内容,希望文章能够帮你解决如何证明在html5画布中对齐文本?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。