Search code examples
javascriptfabricjs

setSelectionStyles not immediately affecting Textbox's _textLines.length


I need to get the number of lines in a Fabric.js Textbox. The text inside the textbox is inputted by the user, and parts of the text can be formatted to bold using [b] and [/b]. This text is then formatted using setSelectionStyles (changing the fontFamily).

for (var i = 0; i < parseResults[1].length; i++) {
  fabricText.setSelectionStyles({fontFamily: "font_SeagullBold"}, parseResults[1][i], parseResults[2][i]);
}
console.log(fabricText._textLines.length);

In an example case, the text to be formatted is 8 lines long. Upon being formatted, because of text wrapping, this number will increase to 9. However, _textLines.length does not seem to reflect this immediately. Is there a way to "wait" for setSelectionStyles to "finish" formatting the text?


Solution

  • Solved by calling canvas.add(fabricText) and canvas.renderAll() before getting _textLines.length.

    for (var i = 0; i < parseResults[1].length; i++) {
      fabricText.setSelectionStyles({fontFamily: "font_SeagullBold"}, parseResults[1][i], parseResults[2][i]);
    }
    canvas.add(fabricText);
    canvas.renderAll();
    console.log(fabricText._textLines.length);