Fabric.js: Get objects by name

canvas, fabricjs

Solution

You can do this on application level with the following code:

/**
 * Item name is non-unique
 */
fabric.Canvas.prototype.getItemsByName = function(name) {
  var objectList = [],
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].name && objects[i].name === name) {
      objectList.push(objects[i]);
    }
  }

  return objectList;
};

If the object name is unique you can do something like this:

/**
 * Item name is unique
 */
fabric.Canvas.prototype.getItemByName = function(name) {
  var object = null,
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].name && objects[i].name === name) {
      object = objects[i];
      break;
    }
  }

  return object;
};

Now you can call `canvas.getItemByName('name1');` or `canvas.getItemsByName('name1');`.

Problem

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);`

Original source