<canvas> 中的文本换行元素 [英] Text wrap in a &lt;canvas&gt; element

查看:19
本文介绍了<canvas> 中的文本换行元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 元素在图像上添加文本.首先绘制图像,然后在图像上绘制文本.到目前为止一切顺利.

I am trying to add text on an image using the <canvas> element. First the image is drawn and on the image the text is drawn. So far so good.

但是我面临的一个问题是,如果文本太长,它会在开始和结束时被画布截断.我不打算调整画布的大小,但我想知道如何将长文本包装成多行,以便显示所有内容.有人能指出我正确的方向吗?

But where I am facing a problem is that if the text is too long, it gets cut off in the start and end by the canvas. I don't plan to resize the canvas, but I was wondering how to wrap the long text into multiple lines so that all of it gets displayed. Can anyone point me at the right direction?

推荐答案

@mizar 答案的更新版本,修复了一个严重错误和一个小错误.

Updated version of @mizar's answer, with one severe and one minor bug fixed.

function getLines(ctx, text, maxWidth) {
    var words = text.split(" ");
    var lines = [];
    var currentLine = words[0];

    for (var i = 1; i < words.length; i++) {
        var word = words[i];
        var width = ctx.measureText(currentLine + " " + word).width;
        if (width < maxWidth) {
            currentLine += " " + word;
        } else {
            lines.push(currentLine);
            currentLine = word;
        }
    }
    lines.push(currentLine);
    return lines;
}

我们使用这段代码已经有一段时间了,但今天我们试图弄清楚为什么有些文本没有绘制,我们发现了一个错误!

We've been using this code for some time, but today we were trying to figure out why some text wasn't drawing, and we found a bug!

事实证明,如果你给 getLines() 函数一个单词(没有任何空格),它将返回一个空数组,而不是一个只有一行的数组.

It turns out that if you give a single word (without any spaces) to the getLines() function, it will return an empty array, rather than an array with a single line.

在我们对此进行调查时,我们发现了另一个(更微妙的)错误,其中的行最终可能比应有的长度略长,因为原始代码在测量行的长度时没有考虑空格.

While we were investigating that, we found another (much more subtle) bug, where lines can end up slightly longer than they should be, since the original code didn't account for spaces when measuring the length of a line.

我们的更新版本适用于我们投入的所有内容,如上所示.如果您发现任何错误,请告诉我!

Our updated version, which works for everything we've thrown at it, is above. Let me know if you find any bugs!

这篇关于<canvas> 中的文本换行元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆