Search code examples
fabricjs

How to change selected text in FabricJS IText object?


Is there any way to change a selected text?

Assume I have a text "Sample Text" and programmatically select a word Sample

...
text.selectionStart = 0;
text.selectionEnd = 6;
...

So, text.getSelectedText() returns Sample, which is what I need... Next step, what I want is to change it to any other text.

Generally speaking, I want to change a text which is between selectionStart and selectionEnd.

Any ideas? Tnx in advance.


Solution

  • var canvas = new fabric.Canvas('c');
    canvas.setHeight(300);
    canvas.setWidth(500);
    var text = new fabric.IText('Sample Text', {
       left: 50,
       top: 100,
       fontFamily: 'arial',
       fill: '#333',
       fontSize: 50
     });
    canvas.add(text);
    function replaceText(){
     var res = text.getSelectedText();
     text.insertChars(res.split('').sort(() => Math.random() * 2 - 1).join(''));//adding shuffled string
     text.selectionStart = 0;
     text.selectionEnd = 6;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
    <button onclick="replaceText()">Replace</button>
    <canvas id="c"></canvas>

    You can use insertChars() method of IText.