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 too long. But it doesn't detect line breaks. This is what it's doing and what it should do:
Input:
Hello This is dummy text that could be inside the text area. It will then get put into the canvas.
Wrong output:
Hello this is dummy text that could be inside the text area. It will then get put into the canvas.
What it should output:
Hello This is dummy text that could be inside the text area. It will then get put into the canvas.
This is the function I'm using:
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); }
Is it possible to achieve what I'm trying to get? Or is there a way to simply move the text area as is into the canvas?
To check whether a JavaScript string contains a line break, we can use the JavaScript regex's exec method. We call /\r|\n/. exec with text to return the matches of newline characters in text .
To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\ n/ . The split method will split the string on each occurrence of a newline character and return an array containing the substrings. Copied!
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Use the following:
var enteredText = document.getElementById("textArea").value; var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length; alert('Number of breaks: ' + numberOfLineBreaks);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With