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
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