Removing multiple objects on Fabric.js canvas

前端 未结 2 1358
我在风中等你
我在风中等你 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:13

    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
    
    
            

提交回复
热议问题