Skip to content Skip to sidebar Skip to footer

Grouping And Ungrouping Fabric.js Objects

I've created a kind of 'polygon selector' or 'polygon maker' using fabric.js. Each click creates a corner of the polygon, which can be selected, moved, etc... double clicking the o

Solution 1:

you can use fabric grouping tool

You can group and ungroup objects together, and manipulate them at the same time

for example

var canvas = new fabric.Canvas('paper',{
    isDrawingMode: true
    });
$("#select").click(function(){
    canvas.isDrawingMode = false;
});
$("#draw").click(function(){
    canvas.isDrawingMode = true;
});

$("#group").on('click', function() {
    var activegroup = canvas.getActiveGroup();
    var objectsInGroup = activegroup.getObjects();

    activegroup.clone(function(newgroup) {
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function(object) {
            canvas.remove(object);  
        });
        canvas.add(newgroup);

    });
});

$("#ungroup").click(function(){
   var activeObject = canvas.getActiveObject();
    if(activeObject.type=="group"){
        var items = activeObject._objects;
        alert(items);
        activeObject._restoreObjectsState();
        canvas.remove(activeObject);
        for(var i = 0; i < items.length; i++) {
          canvas.add(items[i]);
          canvas.item(canvas.size()-1).hasControls = true;
        }

        canvas.renderAll();
    }
});

please check following link

http://jsfiddle.net/softvar/NuE78/1/

Solution 2:

if (!canvas.getActiveObject()) {
      return;
    }
    if (canvas.getActiveObject().type !== 'group') {
      return;
    }
    canvas.getActiveObject().toActiveSelection();
    canvas.requestRenderAll();

From : http://fabricjs.com/manage-selection

Solution 3:

if getActiveGroup() is not available then you can use this to group (after mouse selecting multiple objects):

toGroup() is only available if multiple objects are selected

var activeObj = canvas.getActiveObject();
var activegroup = activeObj.toGroup();
var objectsInGroup = activegroup.getObjects();
activegroup.clone(function(newgroup) {
    canvas.remove(activegroup);
    objectsInGroup.forEach(function(object) {
        canvas.remove(object);  
    });
    canvas.add(newgroup);
});

changes http://fabricjs.com/v2-breaking-changes-2

Post a Comment for "Grouping And Ungrouping Fabric.js Objects"