Delete multiple Objects at once on a fabric.js canvas in html5
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.
Your code seems like it is selecting and then de-selecting the objects.
This may work better:
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]);
}
};
Good information link:
https://github.com/kangax/fabric.js/wiki/Tutorial-2#wiki-modifying-objects
You can check any object property and can remove
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++;
}
}