21

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.

4

6 回答 6

37

由于@Kangax 评论解决了大部分问题,我找到了以下解决方案来从画布中删除当前选定的对象。

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());
    }
};

该函数检查是否选择了一个组。如果选择了一个组,则该组的每个对象都将被删除。如果未选择任何组,则该功能会尝试删除选定的对象。如果未选择任何内容,则不会更改画布。

于 2012-08-07T11:11:29.710 回答
5

您的代码似乎正在选择然后取消选择对象。

这可能会更好:

var deleteSelectedObject = document.getElementById('delete-item');
deleteSelectedObject.onclick = function()
{
    var curSelectedObjects = canvas.getObjects(canvas.getActiveGroup);

    canvas.discardActiveGroup();
    for (var i = 0; i < curSelectedObjects.length; i++)
    {
        canvas.remove(curSelectedObjects[i]);
    }
};

好资料链接:

https://github.com/kangax/fabric.js/wiki/Tutorial-2#wiki-modifying-objects

于 2012-08-06T14:49:12.083 回答
3

您可以检查任何对象属性并可以删除

var objects = canvas.getObjects();

for (var i = 0; i < objects.length; ) {
  if (objects[i].name == 'cropArea' || objects[i].name == 'bleedLine') {
    canvas.remove(objects[i]);
    i = 0;
  } else {
    i++;
  }
}
于 2016-10-06T09:25:46.780 回答
0

我这样做了:

  var selectedObj = canvas.getObjects(canvas.getActiveGroup()) 

将所选对象的数组返回给我。:) 您的代码片段中缺少最后一个函数括号

于 2015-06-06T16:35:34.110 回答
0

你知道 canvas.remove 可以接受多个参数吗?所以最简单的方法应该是这个:

canvas.remove(...canvas.getObjects());

除此之外,canvas.clear只会删除画布中的对象,而不会删除背景。

于 2020-01-15T16:11:45.643 回答
0

除了我在 jsfiddle 上找到的一个解决方案之外,上述解决方案(或 stackoverflow 上的任何其他解决方案)都没有对我有用:

function deleteObjects(){
var activeObject = canvas.getActiveObject(),
activeGroup = canvas.getActiveGroup();
if (activeObject) {
    if (confirm('Are you sure?')) {
        canvas.remove(activeObject);
    }
}
else if (activeGroup) {
    if (confirm('Are you sure?')) {
        var objectsInGroup = activeGroup.getObjects();
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function(object) {
        canvas.remove(object);
        });
    }
}
}

http://jsfiddle.net/beewayne/z0qn35Lo/

于 2016-12-22T15:43:29.913 回答