Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

javascript - Delete multiple Objects at once on a fabric.js canvas in html5

I'm actually working on a html5 canvas project which uses the fabric.js Framework for the canvas interactions. Now I'm struggeling with the deletion of multiple objects. The following code does not seem to track the selected objects, but tracks all objects on the canvas.

var deleteSelectedObject = document.getElementById('delete-item');
deleteSelectedObject.onclick = function(){
    var curSelectedObjects = new Array();
    curSelectedObjects = canvas.getObjects(canvas.getActiveGroup);
    canvas.discardActiveGroup();
    for (var i = 0; i < curSelectedObjects.length; i++){
        canvas.setActiveObject(curSelectedObjects[i]);
        canvas.remove(canvas.getActiveObject());
    }
};

Don't get my failure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Due to @Kangax comment which solved most of the problem, I found the following solution to delete the currently selected objects from the canvas.

var deleteSelectedObject = document.getElementById('delete-item');
deleteSelectedObject.onclick = function()
{
if(canvas.getActiveGroup()){
      canvas.getActiveGroup().forEachObject(function(o){ canvas.remove(o) });
      canvas.discardActiveGroup().renderAll();
    } else {
      canvas.remove(canvas.getActiveObject());
    }
};

The function checks whether a group is selected. If a group is selected every object of the group gets removed. If no group is selected the function tries to remove a selected object. If nothing is selected, the canvas is not changed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...