Fabric.js: Get objects by name

Viewed 25011

Is it possible to get Fabric.js objects by name? I can add subclass which will allow me to add custom name property to objects. But after that can I call objects by name instead of index? e.g

calling by index canvas.getItem(0);

I want something like canvas.getItemByName(itemName);

3 Answers

Updated:

With LodashJS, you can use:

object = _.find(canvas._objects, function(o) { return o.name === 'name1' })

I expanded the idea a little to include group objects and searching by any attribute, not just name.

When many elements are expected to match (non-unique attribute), or when only one element is expected to match (unique attribute, like ID):

/**
 * Non-unique attributes
 */
fabric.Canvas.prototype.getItemsByAttr = function(attr, val) {
    var objectList = [];
    traverseObjects(this.getObjects(), attr, val, objectList);
    return objectList;
};

/**
 * Unique attribute
 */
fabric.Canvas.prototype.getItemByAttr = function(attr, val) {
    var objectList = [];
    traverseObjects(this.getObjects(), attr, val, objectList);
    return objectList[0];
};

/**
 * Traverse objects in groups (and subgroups)
 */
function traverseObjects(objects, attr, val, objectList){
    for(i in objects){
        if(objects[i]['type'] == 'group'){
            traverseObjects(objects[i].getObjects(),attr,val, objectList);
        } else if(objects[i][attr] == val){
            objectList.push(objects[i]);
        }
    }
}

Now you can call canvas.getItemByAttr('name','name1'); or canvas.getItemsByAttr('someAttr','someValue');.

Related