I have a small function I found that takes a string from a textarea
and then puts it into a canvas
element and wraps the text when the line gets to
Use the following:
var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);
DEMO
Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:
var splitted = $('#textArea').val().split("\n"); // will split on line breaks
Hope that helps you out!
Here's the final code I [OP] used. Probably not best practice, but it worked.
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);
}
Split string in JavaScript
var array = str.match(/[^\r\n]+/g);
OR
var array = str.split(/\r?\n/);
You should try detect the first line.
Then the:
if(n == 0){
line = words[n]+"\n";
}
I'm not sure, but maybe it helps.
You can use the split()
function to break input on the basis of line break.
yourString.split("\n")
This is what I used to print text to a canvas. The input is not coming from a textarea
, but from input
and I'm only splitting by space. Definitely not perfect, but works for my case. It returns the lines in an array:
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;
}