Select All the objects on canvas using Fabric.js

softvar picture softvar · Dec 15, 2013 · Viewed 26.9k times · Source

Is there a way to explicitly select all the objects present at a particular instance of time. This can be easily done using mouse to select all. Is there a code-solution like a button named Select All so that clicking it would make all the fabric type objects being selected and then I could apply the changes to whole of that ActiveGroup using canvas.getActiveGroup(); and iterate over.

Answer

kangax picture kangax · Dec 15, 2013

Good question.

There's no built-in method for this, but you would need to do something along these lines:

var objs = canvas.getObjects().map(function(o) {
  return o.set('active', true);
});

var group = new fabric.Group(objs, {
  originX: 'center', 
  originY: 'center'
});

canvas._activeObject = null;

canvas.setActiveGroup(group.setCoords()).renderAll();

The code should be self-explanatory, and it's pretty much what's happening under the hood when you use mouse, shift+click, etc.