Search code examples
javascriptjqueryfabricjs

How to update text in Fabric JS IText clicking a button?


I'm newbie using this tool and I have this problem. I want to update the text clicking a button, so I have this:

<canvas id="xcanvas" width="200" height="400"></canvas>
<button type="button" id="set_text" class="btn btn-primary">set text</button>

And my code:

var canvas = new fabric.Canvas('xcanvas');
var text1 = new fabric.IText("old", { 
    borderColor: '#eaeaea',
    cornerColor: '#eaeaea',
    cornerSize: 9,
    cornerStyle: 'circle',
    transparentCorners: false,
    lockUniScaling: false,
    fontFamily: 'Arial',
    fill: '#000',
    stroke: '#000',
    fontWeight:"normal",
    strokeWidth: 0,
    strokeUniform: true,
    id:92929
});

canvas.add(text1);

According to docs, I can remove and insert text using removeChars() and insertChars(), so I tried this:

$("#set_text").click(function(){
  text1.removeChars(0, 1000);
  text1.insertChars("hello!");
});

But it doesn't work, I get this result:

BEFORE:

enter image description here

AFTER:

enter image description here

Clicking the button many times:

enter image description here

I want to get this result:

enter image description here

I'd like to receive your help.


Solution

  • Finally I solved:

    text1.setText( "Hello!" );
    canvas.renderAll();