Grouping and Ungrouping Fabric.js objects

后端 未结 3 1116
庸人自扰
庸人自扰 2021-02-06 07:37

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 clicki

相关标签:
3条回答
  • 2021-02-06 07:55

    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

    0 讨论(0)
  • 2021-02-06 08:00
        if (!canvas.getActiveObject()) {
          return;
        }
        if (canvas.getActiveObject().type !== 'group') {
          return;
        }
        canvas.getActiveObject().toActiveSelection();
        canvas.requestRenderAll();
    

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

    0 讨论(0)
  • 2021-02-06 08:07

    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/

    0 讨论(0)
提交回复
热议问题