fabricjs IText Resize

How to resize the fabric.js IText without the ugly text strech.

by Vijay Gujar

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="600" height="600"></canvas>

JavaScript

// Switch fix ON or OFF to see the difference.
var fixOn = true;

var canvas = new fabric.Canvas('c', {
	hoverCursor: 'pointer',
  backgroundColor: 'white',
  selection: true
});

var width = 200;
var height = 100;
var textTopFontSize = 12 * height * 0.02;
var textBottomFontSize = 8 * height * 0.03;

// add Group with 2 IText
var parentGroup = new fabric.Group([], { 
  left: 100, 
  top: 100,
  width: width,
  height: height,
  originX: 'center', 
  originY: 'center'
});

var rect = createRect(height, width, 'green');
var textTop = createTextTop("Top Text", textTopFontSize);
var textBottom = createTextBottom("Bottom Text", textBottomFontSize);

canvas.add(parentGroup);
parentGroup.add(rect);
parentGroup.add(textTop);
parentGroup.add(textBottom);
canvas.renderAll();

// Events
canvas.on('object:scaling', function(event) {
	if (fixOn) {
    var newHeight = event.target.getHeight();
    var newWidth = event.target.getWidth();
    var scaleY = height / newHeight;
    var scaleX = width / newWidth;
    var fontLabel = 12 * newHeight * 0.02;
    var fontData = 8 * newHeight * 0.03;

    textTop.set({
      fontSize: fontLabel,
      scaleX: scaleX,
      scaleY: scaleY
    });
    textTop.setCoords();
    textBottom.set({
      fontSize: fontData,
      scaleX: scaleX,
      scaleY: scaleY
    });
    textBottom.setCoords();
    parentGroup.setCoords();
    canvas.renderAll();
  }
});

canvas.on('mouse:up', function(event) { 
  if (fixOn) {
    height = event.target.getHeight();
    width = event.target.getWidth();
    textTopFontSize = 12 * height * 0.02;
    textBottomFontSize = 8 * height * 0.03;

    parentGroup.set({
      height: height,
      width: width,
      scaleX: 1,
      scaleY: 1
    });
    parentGroup.setCoords();

    parentGroup.remove(rect);
    rect = createRect(height, width, 'green');
    parentGroup.add(rect);
    rect.setCoords();

    parentGroup.remove(textTop);
    textTop = createTextTop("Top Text", textTopFontSize);
   ...