GoldenGonaz
GoldenGonaz

Reputation: 1166

FabricJS iText grow from center

How can you make a text object on the FabricJS canvas grow/shrink from the center and expand bidirectionally when text is added or removed?

I have tried adding centeredScaling: true but this is only for resizing (scaling) the object, not adding/removing text.

If you check my demo you'll see that when you click the text and add more characters to the object it expands to the right only, leaving the text off center.

var canvas = this.__canvas = new fabric.Canvas('c');
var cWidth = 600;
var cHeight = 200;

canvas.setWidth(cWidth);
canvas.setHeight(cHeight);


function Addtext() {
  canvas.add(new fabric.IText('Text', {
    left: (cWidth / 2) - 83,
    top: (cHeight / 2) - 25,
    fontFamily: 'arial black',
    fill: '#333',
    fontSize: 50,
    centeredScaling: true,
  }));
}
 #c {
   border: 1px solid red;
   top: 22px;
   left: 0px;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>

<button onclick="Addtext()">Add Text</button>

<canvas id="c"></canvas>

Upvotes: 0

Views: 1320

Answers (1)

Matej Marconak
Matej Marconak

Reputation: 1413

Add align and origin of x and y to center.

var canvas = this.__canvas = new fabric.Canvas('c');
var cWidth = 600;
var cHeight = 200;

canvas.setWidth(cWidth);
canvas.setHeight(cHeight);


function Addtext() {
  canvas.add(new fabric.IText('Text', {
    left: (cWidth / 2) - 83,
    top: (cHeight / 2) - 25,
    fontFamily: 'arial black',
    fill: '#333',
    fontSize: 50,
    align: 'mid', //added
  originX: 'center', //added
  originY: 'center', //added
    centeredScaling: true,
  }));
}
 #c {
   border: 1px solid red;
   top: 22px;
   left: 0px;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>

<button onclick="Addtext()">Add Text</button>

<canvas id="c"></canvas>

Upvotes: 2

Related Questions