Html 如何在画布中包装中文字体
我使用Html 如何在画布中包装中文字体,html,canvas,html5-canvas,Html,Canvas,Html5 Canvas,我使用canvas.fillText在画布上绘制中文字体,但文字没有包装。我读了canvas教程,但它使用空格分割单词,这对中文字体不起作用。有没有人对此有经验,或者只是告诉我在哪里找到解决方案 谢谢。您需要使用measureText()通过添加一个和一个标志符号来测量线宽,直到得到的值超过包装文本的可用空间 例如,我创建了一个循环,当没有更多可用空间时,它将环绕该行: var txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i = 0, ...; /// l
canvas.fillText
在画布上绘制中文字体,但文字没有包装。我读了canvas教程,但它使用空格分割单词,这对中文字体不起作用。有没有人对此有经验,或者只是告诉我在哪里找到解决方案
谢谢。您需要使用
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);
var txt='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
i=0。。。;
///通过保存字符串的txt循环
对于(;i0)ctx.fillText(line,x,y);
PS:我手边没有用于演示的中文字体,但您会看到其原理。您需要使用
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);
var txt='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
i=0。。。;
///通过保存字符串的txt循环
对于(;i0)ctx.fillText(line,x,y);
附言:我手边没有一个中文字体用于演示,但你会看到原理。非常感谢。非常适合中文字体。非常感谢。适合中文字体。