Removing multiple objects on Fabric.js canvas

前端 未结 2 1364
我在风中等你
我在风中等你 2021-01-15 19:52

Struggling to remove multiple objects from the fabric canvas. Everything seems to be in working order but when the code runs it does not remove the multiple selected objects

2条回答
  •  孤独总比滥情好
    2021-01-15 20:25

    Object of active group are indeed on the canvas but removing them from canvas will not remove them from the rendering pipeline if they are in active group.

    When fabricjs draws everything, it checks for object on canvas and presence of activeGroup. If activeGroup is present, its objects get rendered later, regardless they are on canvas or not.

    So you are effectively removing the objects from the canvas, but untill you clear the selection of the active group, the objects are still there. Correct procedure is removing the object from the canvas and from the activeGroup.

    check the snippet, select all objects with mouse and the press remove all button.

    var canvas = new fabric.Canvas('canvas');
    var r1 = new fabric.Rect({width:50,height:50});
    var r2 = new fabric.Rect({width:50,height:50,top:110, left:110});
    var r3 = new fabric.Rect({width:50,height:50,top:60, left:60});
    canvas.add(r1,r2,r3);
    
    function removeAll() {
    var o = canvas.getActiveGroup();
    o._objects.forEach(function (object, key) {
    canvas.remove(object);
    o.removeWithUpdate(object);
    });
    canvas.discardActiveGroup();
    canvas.renderAll();
    }
    
    
            

提交回复
热议问题