Interactive text fields with Fabric.js

放肆的年华 提交于 2019-12-02 15:52:57

The latest version of fabric.js includes a class IText which incorporates the interaction for editing and selection of text dynamically. try the code below with the latest version of fabric.js

canvas.add(new fabric.IText('Tap and Type', { 
  fontFamily: 'arial black',
  left: 100, 
  top: 100 ,
}));
Tyson

I recently built a mind mapping tool using fabric.js and I encountered the same problem.

To achieve what you have described (changing the text on and after creation of textual elements in the canvas), I used jquery to detect the keydown event. Assuming you have selected the desired textual element in the fabric canvas the following snippet will change the text.

$(document).keydown(function(e){
    var keyPressed = String.fromCharCode(e.which);
    var text = canvas.getActiveObject();
    if (text)
    {
        var newText = '';
        var stillTyping = true;
        if (e.which == 27) //esc
        {
            if (!text.originalText) return; //if there is no original text, there is nothing to undo
            newText = text.originalText;
            stillTyping = false;
        }
        //if the user wants to make a correction
        else
        {
            //Store the original text before beginning to type
            if (!text.originalText)
            {
                text.originalText = text.text;
            }
            //if the user wants to remove all text, or the element entirely
            if (e.which == 46) //delete
            {
                activeObject.element.remove(true);
                return;
            }
            else if (e.which == 16) { //shift
                newText = text.text;
            }
            else if (e.which == 8) //backspace
            {
                e.preventDefault();
                newText = text.text.substr(0, text.text.length - 1);
            }
            else if (e.which == 13) //enter
            {
                //canvas clear selection
                canvas.discardActiveObject();
                canvas.renderAll();
                canvasBeforeSelectionCleared({ memo: { target: text} });

                newText = text.text;
                stillTyping = false;
            }
            //if the user is typing alphanumeric characters
            else if (
                (e.which > 64 && e.which < 91) || //A-Z
                (e.which > 47 && e.which < 58) || //0-9
                (e.which == 32) || //Space
                (keyPressed.match(/[!&()"'?-]/)) //Accepted special characters
            )
            {
                if (text.text == text.originalText) text.text = '';
                if (keyPressed.match(/[A-Z]/) && !e.shiftKey)
                    keyPressed = keyPressed.toLowerCase();
                newText = text.text + keyPressed;
            }
        }
        text.set({ text: newText }); //Change the text
        canvas.renderAll(); //Update the canvas

        if (!stillTyping)
        {
            this.text.originalText = null;
        }
    }
});

Using this technique, I can select a text element in the fabric canvas, begin typing and the text is replaced. You could change it so it didn't erase the text each time you select the element.

There are some compromises with this method. For example you cannot select text as if it were in a regular HTML input text element and there is no blinking cursor, therefore the "virtual" cursor is always at the end of the text.

If you really wanted to you could draw a blinking cursor at the end of the text.

    text.set({ text: newText }); //Change the text
    canvas.renderAll(); //Update the canvas

That was what I was looking for :) Thanks alot!

pawan jain

I guess its too late, but this might be of help to others.

There is a demo on fabricjs to do the exact same thing.

assuming you have both the canvas and the context as variables in your script:

// write text
context.fillText("text1",0,0);


// refresh canvas and write new text
context.clearRect(0,0,canvas.width,canvas.height);
context.fillText("text2",0,0);

Try this(this is from my application):

Text Color: <input id="text-color" type="text" value = "#FF0000" name="textColor" />


textColor.onchange = function() {
            canvas.getActiveObject().setColor(this.value);
            canvas.renderAll();
        };

function updateControls() {         
            textControl.value = canvas.getActiveObject().getText();
        }

        canvas.on({
            'object:selected': updateControls,
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!