我发现了一个小函数,它从 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);
}
是否有可能实现我想要得到的?或者有没有办法简单地将文本区域按原样移动到画布中?
原文由 Dustin Silk 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
.split()
:或者使用
.match()
代替:希望有帮助!