最佳答案
我发现了一个小函数,它从 textarea
中获取一个字符串,然后将其放入 canvas
元素中,并在行太长时封装文本。但是它没有检测到断线。这就是它正在做的和它应该做的:
输入:
Hello
This is dummy text that could be inside the text area.
It will then get put into the canvas.
输出错误:
Hello this is dummy text
that could be inside the
text area. It will then
get put into the canvas.
它应该输出什么:
Hello
This is dummy text that
could be inside the text
area. It will then get
put into the canvas.
这是我正在使用的函数:
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}
有可能达到我想要的效果吗?或者有一种方法可以简单地将文本区域移动到画布中?