我发现了一个小函数,它可以从一个 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);
}
我是否能够达到我想要的目标?或者有没有一种方法可以将文本区域简单地移动到画布中?