我发现了一个小函数,它从 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);
}
是否有可能实现我想要得到的?或者有没有办法简单地将文本区域按原样移动到画布中?
ENTER
创建的换行符,例如可以通过使用 \n
拆分来找到它们。
-jquery
每次我们进行 JavaScript 搜索的人。 😒︎
在 JavaScript 中拆分字符串
var array = str.match(/[^\r\n]+/g);
或者
var array = str.split(/\r?\n/);
https://i.stack.imgur.com/vjU9C.png
如果您需要从 JSON 中拆分字符串,则字符串的 \n 特殊字符替换为 \\n。
用换行符分割字符串:
Result.split('\n');
在 JSON 中接收到的拆分字符串,其中特殊字符 \n 在 JSON.stringify(在 javascript 中)或 json.json_encode(在 PHP 中)期间替换为 \\n。因此,如果您的字符串包含在 AJAX 响应中,则已对其进行处理以进行传输。如果它没有被解码,它将把 \n 替换为 \\n** 并且你需要使用:
Result.split('\\n');
https://i.stack.imgur.com/2b9MR.png
这就是我用来将文本打印到画布上的方法。输入不是来自 textarea
,而是来自 input
,我只是按空格分隔。绝对不完美,但适用于我的情况。它返回数组中的行:
splitTextToLines: function (text) {
var idealSplit = 7,
maxSplit = 20,
lineCounter = 0,
lineIndex = 0,
lines = [""],
ch, i;
for (i = 0; i < text.length; i++) {
ch = text[i];
if ((lineCounter >= idealSplit && ch === " ") || lineCounter >= maxSplit) {
ch = "";
lineCounter = -1;
lineIndex++;
lines.push("");
}
lines[lineIndex] += ch;
lineCounter++;
}
return lines;
}
您可以使用 split()
函数在换行的基础上中断输入。
yourString.split("\n")
您应该尝试检测第一行。
然后:
if(n == 0){
line = words[n]+"\n";
}
我不确定,但也许有帮助。
这是我 [OP] 使用的最终代码。可能不是最佳实践,但它确实有效。
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var breaks = text.split('\n');
var newLines = "";
for(var i = 0; i < breaks.length; i ++){
newLines = newLines + breaks[i] + ' breakLine ';
}
var words = newLines.split(' ');
var line = '';
console.log(words);
for(var n = 0; n < words.length; n++) {
if(words[n] != 'breakLine'){
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;
}
}else{
context.fillText(line, x, y);
line = '';
y += lineHeight;
}
}
context.fillText(line, x, y);
}
str.split(/\r?\n/g);
适用于\r\n
和\n
str.split(/\r\n|\r|\n/g)
如果您也有\r
只有换行符(如 I )