JSFiddle - React, Tailwind, and code Playground

by Eugene Vilder

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.0/fabric.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>

CSS

#paper {
  border: solid 1px red;
}

JavaScript

const canvas = new fabric.Canvas('paper');

const text = new fabric.Textbox("Style Test", {
    left: 10,
    top: 10,
    width: 50,
    height: 50,
    fontSize: 20,
    fill: 'red',
    insertNewStyleBlock: function(insertedText, start, copiedStyle) {
      var cursorLoc = this.get2DCursorLocation(start, true),
          addedLines = [0], linesLenght = 0;
      for (var i = 0; i < insertedText.length; i++) {
        if (insertedText[i] === '\n') {
          linesLenght++;
          addedLines[linesLenght] = 0;
        }
        else {
          addedLines[linesLenght]++;
        }
      }
      if (addedLines[0] > 0) {
        this.insertCharStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex, addedLines[0], copiedStyle);
        copiedStyle = copiedStyle && copiedStyle.slice(addedLines[0] + 1);
      }
      linesLenght && this.insertNewlineStyleObject(
        cursorLoc.lineIndex, cursorLoc.charIndex + addedLines[0], linesLenght);
      for (var i = 1; i < linesLenght; i++) {
        if (addedLines[i] > 0) {
          this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
        }
        else if (copiedStyle) {
          this.styles[cursorLoc.lineIndex + i][0] = copiedStyle[0];
        }
        copiedStyle = copiedStyle && copiedStyle.slice(addedLines[i] + 1);
      }
      // we use i outside the loop to get it like linesLength
      if (addedLines[i] > 0) {
        this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
      }
    },
});

text.setSelectionStyles({
	fill: 'blue',
  fontSize: 40,
  fontFamily: "tahoma"
}, 6, 10).setCoords();

canvas.add(text);
canvas.renderAll();