首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在画布中包装中文字体

如何在画布中包装中文字体
EN

Stack Overflow用户
提问于 2013-09-11 13:35:05
回答 1查看 1.1K关注 0票数 1

我用canvas.fillText在画布上画中文字体,但这些字没有包装。我读过画布教程这里,但是它用空格分裂单词,这对中文字体不起作用。有人能在这方面有经验吗?或者告诉我在哪里能找到解决办法?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-11 16:14:28

您将需要通过添加一个和一个字形来使用measureText()来测量线宽,直到您得到超过可用空间的值,这是您包装文本的地方。

例如,我做了这个循环,当没有更多的空间时,这个循环将对行进行包装:

在线演示

代码语言:javascript
复制
var txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    i = 0, ...;

/// loop trough the txt which holds the string
for(; i < txt.length; i++) {

    /// measure current width
    lw = ctx.measureText(line).width;

    /// if within available space add a char to line
    if (lw < w - ctx.measureText(txt[i]).width) {
        line += txt[i];

    } else {
        /// didn't fit so draw what we have
        ctx.fillText(line, x, y);

        /// reset line with the left-over char
        line = txt[i];

        /// reset x (not used in demo) and increment y position
        x = 0;
        y += 50;
    }
}

/// if anything was left in line draw it here
if (line.length > 0) ctx.fillText(line, x, y);

PS:我没有方便的中文字体演示,但你会看到原则。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18742738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档