HTML5 Canvas Canvas write text on real line break


If you want to write some text on a canvas and it will determine, when a text has to be wrapped, You can use the following function, the making of a text array in a function of the Canvas.

Bsp:

var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
//vorher muss Schriftgröße des Canvas gesetzt werden
context.font = "30px arial";
textArr  = textToArray ("Wordpress eigene Farben und CSS Klassen in den Editor einbauen", 300, context);
//textArr enhält ["Wordpress Plugin"] und ["selber erstellen Tutorial"]
textToArray = function(text, maxWidth, context){
    var textArr = new Array();
    var fragment = "";
    var lastCutPostion = 0;
    var lastPossibleCutPosition = 0;
    var charCounter = 0;
    var position = 0;
    $j.each(text, function(index, char) {
        if(char == " " && charCounter != 0)
        {
            fragment  = text.substring (lastCutPostion, position);
            //console.log(fragment);
            textWidth = context.measureText(fragment).width;
            //console.log(textWidth);
            if(textWidth > maxWidth)
            {
                //console.log("max width reched");
                fragment  = text.substring (lastCutPostion, lastPossibleCutPosition);
                //console.log(fragment);
                textArr.push(fragment);
                charCounter = -1 + (position - lastPossibleCutPosition);
                lastCutPostion = lastPossibleCutPosition + 1;
            }
            lastPossibleCutPosition = position;
        }
        position++;
        charCounter++;
    });
    //do not forget the last Word
    if(charCounter > 0)
    {
        fragment  = text.substring(lastCutPostion, text.length);
        textWidth = context.measureText(fragment).width;
        //console.log(textWidth);
        if(textWidth > maxWidth)
        {
            fragment  = text.substring (lastCutPostion, lastPossibleCutPosition);
            lastCutPostion = lastPossibleCutPosition + 1;
            textArr.push(fragment);
            fragment  = text.substring(lastCutPostion, text.length);
        }
        textArr.push(fragment);
    }
    return textArr;
}
  1. leaves following errors:
    Uncaught TypeError: Indicated use ' in’ operator to search for * any number * in * text *..