change text once it is added on canvas

11,714

Solution 1

This works for me:

Bar.setText("my_text");
canvas.renderAll();

Solution 2

When using the "set" function try camelcase for the first argument!

In other words change:

Bar.set('Text','Selectedoooooooo');

to:

Bar.set('text','Selectedoooooooo');

This works for me 🙏🏼

Solution 3

Use the new IText in FabricJS. Here is a nice solution

This is my answer to it

addText(color) {
    color = color ? color : '#333';
    let textEl = new fabric.IText('', {
        fontFamily: 'Open Sans',
        fill: color,
        fontSize: 50
    });
    this.canvas.add(textEl).setActiveObject(textEl);
    textEl.enterEditing();
}

Solution 4

Yes you can set text once it is added to canvas.Here is the jsfiddle

try changing your

Bar.set('Text','Selectedoooooooo');

to

Bar.setText('Selectedoooooooo');

Hope it helps....

Solution 5

You can access children of a group via getObjects() or item() methods:

canvas.on('object:selected', function(e) {
  e.target.item(1).setText('Selectedoooooooo');
});

See http://jsfiddle.net/fabricjs/HAb4N/12/

Share:
11,714
anam
Author by

anam

Let's just say, I am simply enjoying my programming... (Mainly using HTML-CSS-JavaScript,jQuery) ....learning angularjs !!

Updated on June 04, 2022

Comments

  • anam
    anam almost 2 years

    In fabric-js, i am making Group of Rect and text field and then adding it to the canvas. i am using following code , but can i change the Text of text field once it is added in canvas .

    I have made Fiddle Please Check,

    http://jsfiddle.net/HAb4N/5/

    var canvas = new fabric.Canvas('c');
    
    var Bar = new fabric.Text('Bar', {selectable: false, top: 50, left: 10});
    
    
    var rect = new fabric.Rect({width: 100, height: 100, left: 100, top: 100, fill: 'red'});
    var group = new fabric.Group([rect, Bar], {selectable: true, top: 50, left: 100});
    canvas.add(group);
    
    canvas.renderAll();
    
    $(document).click(function(e) {
        console.log('click');
        console.log('ActiveObject', canvas.getActiveObject());
        console.log('ActiveGroup', canvas.getActiveGroup());
        Bar.set('Text','Selectedoooooooo');
    });