Grouping and ungrouping Fabric.js objects

I created a kind of "polygon selector" or "polygon maker" using fabric.js. Each click creates a polygon corner that can be selected, moved, etc. .... double-clicking on the starting point “closes” the polygon. At this moment, I take all the circles / lines that make up the polygons and group them. So far so good.

If such a group is pressed twice, I would like it to ungroup and return to the moving nodes (i.e. moving the circles changed the polygon, etc.); but some kind of weird thing happens - check what happens when you move the circles, some lines seem to be “not connected” to the circles ...

I have already covered every fabric.js theme related to / ungroup (here / there / everywhere). It seems that not one of them covers the type of “related” objects that I have.

The script I put together to show the problem says it is better than I can: http://jsfiddle.net/bhilleli/4v8mkw6q/

Broken code bit: @:

       //dbl clicked a group so lets ungroup it!
        items = p._objects; // grab the items from the group you want to

        // translate the group-relative coordinates to canvas relative ones
        p._restoreObjectsState();
        // remove the original group and add all items back to the canvas
        canvas.remove(p);
        for (var i = items.length - 1; i >= 0; i--) {
            canvas.add(items[i]);
        }
        canvas.renderAll();
+4
source share
1 answer

you can use the fabric grouping tool

You can group and ungroup objects together and manage them at the same time.

eg

 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();
    }
});

check the following link

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

+6
source

All Articles