Creating and selecting a group programmatically using Fabric.js

Let's say I have a canvas containing 6 objects and a button outside the canvas.

When I click this button, 3 of these objects will become a group and will be selected, the objects will retain their positions relative to the canvas.

Is it possible?

I tried so many things, but I could manage it to work. The solution I'm looking for is similar to below.

var objectList=[1,2,3];    
var newgroup = new fabric.Group();

$.each(objectList, function (i) {
    var obj = canvas.item(i);
    newgroup.add(obj.clone());
    canvas.remove(obj);
});

canvas.add(newgroup)
canvas.setActiveGroup(newgroup);
canvas.renderAll();
+4
source share
2 answers

You can use something like this:

(function() {
  var objectList = [1,2,3],
      group = new fabric.Group();

  canvas.forEachObject(function(o, i) {
    if (objectList.indexOf(i) > -1) {
      group.addWithUpdate(o);
      canvas.remove(o);
    }
  });
  canvas.setActiveObject(group);
  canvas.add(group);
})();

Only objects with index 1, 2, or 3 are added to the group.

+6
source
var objectList = [1,2,3],
group = new fabric.Group(objectList);

the above code should work for you it will in any case be group objects 1,2,3

all you have to do is get rid of the original objects and group the clones

0

All Articles