Removing multiple objects on Fabric.js canvas

ぃ、小莉子 提交于 2019-12-01 12:13:54

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();
}
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.13/fabric.min.js" ></script>
<input type="button" onClick="removeAll()" value="remove"/>
        <canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas>

After version 2 of fabric.js, there is no getActiveGroup. To delete multiple objects, you need to use forEachObject. This example builds on the previous one and can delete single objects or grouped objects.

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 deleteObj(){
var doomedObj = canvas.getActiveObject();
  if (doomedObj.type === 'activeSelection') {
			// active selection needs a reference to the canvas.
			doomedObj.canvas = canvas;
			doomedObj.forEachObject(function(obj) {
      canvas.remove(obj);
			});
 }//endif multiple objects
  else{
  //If single object, then delete it
  var activeObject = canvas.getActiveObject();
    //How to delete multiple objects?
		//if(activeObject !== null && activeObject.type === 'rectangle') {
    if(activeObject !== null ) {
			canvas.remove(activeObject);
		}
  }//end else there's a single object
}//end deleteObj
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js" ></script>
<input type="button" onClick="deleteObj()" value="remove"/>
        <canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!