Search code examples
htmlhtml5-canvasfabricjs

fabricJS text with uniform lineheight for each line


I want the text lines to exactly have the same lineHeights but the first line doesn't have the line height

Please check this fiddle https://jsfiddle.net/fahadnabbasi/zukc6pvc/1/

var canvas = new fabric.Canvas('c');

var text_temp = new fabric.IText("One Two Three\nFour Five Six\nSeven Eight Nine", {
    left: 20,
    top: 20,
    fontSize: 48,
    fill: "#000000",
    lineHeight : 2
});
        
canvas.add(text_temp)

I want it something like this attached image

enter image description here


Solution

  • var canvas = new fabric.Canvas('c');
    
    // override this to get always full line height
    fabric.Text.prototype.calcTextHeight = function() {
          var lineHeight, height = 0;
          for (var i = 0, len = this._textLines.length; i < len; i++) {
            lineHeight = this.getHeightOfLine(i);
            height += lineHeight;
          }
          return height;
        };
        
    fabric.Text.prototype._getTopOffset = function() {
      return -this.height / 2 + this.getHeightOfLine(0) / this.lineHeight;
    };
    
    var text_temp = new fabric.IText("One Two Three\nFour Five Six\nSeven Eight Nine", {
                left: 20,
                top: 20,
                fontSize: 48,
                textBackgroundColor: 'red',
                backgroundColor: 'yellow',
                fill: "#000000",
                lineHeight : 2
            });
            
            canvas.add(text_temp)
            
            
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
    <canvas id="c" width="600" height="600"></canvas>

    I'm not sure this is a complete solution, nor i want to go deeper in modifying a core behaviour of the library. This snippet can helpyou but can also fail in more advanced use cases.