Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric JS Select Object by ID Programmatically

In Fabric JS I need to select object by given object Name/ID "Circle"

var onCircle = function () {
    canvas.add(new fabric.Circle({ id: 'Circle', radius: 30, fill: '#f55', top: 150, left: 150 }));
}

I also know the object can able to select by ItemID:

var SelectObject = function (ObjectName) 
{
    canvas.setActiveObject(canvas.item(0));
}

I need something like:

var SelectObject = function (ObjectName) 
{
    canvas.setActiveObject('my object name');
}
like image 272
Surendhar Avatar asked Dec 11 '22 14:12

Surendhar


1 Answers

you just need to write a function to loop though each object and set it as active when you find it. Below I check id but you can change it to check any property on the object you want to set.

var SelectObject = function (ObjectName) {
    canvas.getObjects().forEach(function(o) {
        if(o.id === ObjectName) {
            canvas.setActiveObject(o);
        }
    })
}
like image 173
StefanHayden Avatar answered Jan 31 '23 21:01

StefanHayden