我有一个小功能,我发现需要从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);
}
是否有可能实现什么,我试图让?或者是有没有办法简单地移动文本面积是到画布?
使用以下命令:
var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);
现在我所做的就是先分割字符串使用换行符,然后像之前一样再次分裂它。注意:您还可以使用jQuery结合正则表达式如下:
var splitted = $('#textArea').val().split("\n"); // will split on line breaks
希望可以帮助你!
(注:这个问题已经被问一次here)。
在JavaScript字符串分割
var array = str.match(/[^\r\n]+/g);
要么
var array = str.split(/\r?\n/);
这是我用来打印文本到画布上。输入不从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;
}
下面是我用[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);
}
你应该尝试检测第一线。
那么:
if(n == 0){
line = words[n]+"\n";
}
我不知道,但也许它帮助。