fabricjsfabricjs2

setText() not working in fabricjs version 2


I am trying to set text to textbox explicitly. In an older fabricjs version

object.setText("something")

was working, but no longer in fabricjs version 2. Is there any other way introduced in this version?

var canvas = new fabric.Canvas('c');
var text1 = new fabric.Textbox('Text', {
    left: 10,
    top: 20,
    width: 300
})

canvas.add(text1);
canvas.on('text:changed', function(e) {
    var objTEmp = e.target;
    objTEmp.setText("some");
});
canvas{
    border:1px solid #000;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.4/fabric.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #000000;"></canvas>


Solution

  • That build doesn't have setter/getter (optional). If you want to set text you can use

    obj.text = text;
    //or
    obj.set({
        text:text
    });
    //or
    obj.set('text', text);
    

    DEMO

    var canvas = new fabric.Canvas('c');
    var text1 = new fabric.Textbox('Text', {
      left: 10,
      top: 20,
       width: 300
    })
    
    canvas.add(text1);
    canvas.on('text:changed', function(e) {
     var objTEmp = e.target;
     objTEmp.set({
      text : "some"
     });
    });
    canvas{
     border:1px solid #000;
    }
    <script type="text/javascript" src="
    https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.4/fabric.js"></script>
    <canvas id="c" width="400" height="400" style="border:1px solid #000000;"></canvas>