How to identify the type of a selected object?

31,634

Solution 1

canvas.getActiveObject().get('type') as simmi simmi said is correct. You can also listen to events:

function onObjectSelected(e) {
  console.log(e.target.get('type'));
}
canvas.on('object:selected', onObjectSelected);

Solution 2

I solved this issue using following code::

  if(canvas.getActiveObject().get('type')==="text")
        {
            //Display text panel
            console.log('text panel Displayed');
            $("#Image_left_panel").css("display", "none");
            $("#shape_left_panel").css("display", "none");
            //$("#left_panel").css("display", "block");
        }
        else if(canvas.getActiveObject().get('type')==="Image")
        {
            //Display Image Panel
            console.log('Image Panel Displayed');
            $("#Image_left_panel").css("display", "block");
            $("#shape_left_panel").css("display", "none");
            $("#left_panel").css("display", "none");
        }
        else
        {

        }


        });

Solution 3

Try isType()

Sample function for getting selected objects

function onObjectSelected(o){
    //activeObject = canvas.getActiveObject()
    activeObject = o.target;

    if(activeObject.isType('text')){
       //display text logic
    }
    else if(activeObject.isType('image')){
      //display image
    }
    else if( activeObject.isType('xyz')){
      //display shape logic
    }
}

canvas.on('object:selected', onObjectSelected);

Solution 4

In fabricjs 3.4 and above, to get the object type, just use:

var objType = canvas.getActiveObject().type;

On IText object, the above will return: i-text

On image, it will return: image

Usage:

Call the following function which adds an additional check to make sure type is a property of the active element.

Note: not all elements have the type property.

 canvas.on('object:selected', onObjectSelected);

 function onObjectSelected() { 
     // check if type is a property of active element
     var objType = (canvas.getActiveObject().type ? canvas.getActiveObject().type : "");

     // your code to process the object
}

   

Share:
31,634
anam
Author by

anam

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

Updated on February 15, 2021

Comments

  • anam
    anam about 3 years

    I am placing Text, Image and Shapes on canvas using Fabric.js. I have made Three different Edit-Panels for all three. When user select text I want to show text panel. like wise for image and shapes.

    How to identify type of selected Object?