我用canvas.fillText在画布上画中文字体,但这些字没有包装。我读过画布教程这里,但是它用空格分裂单词,这对中文字体不起作用。有人能在这方面有经验吗?或者告诉我在哪里能找到解决办法?
谢谢。
发布于 2013-09-11 16:14:28
您将需要通过添加一个和一个字形来使用measureText()来测量线宽,直到您得到超过可用空间的值,这是您包装文本的地方。
例如,我做了这个循环,当没有更多的空间时,这个循环将对行进行包装:
在线演示
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:我没有方便的中文字体演示,但你会看到原则。
https://stackoverflow.com/questions/18742738
复制相似问题