Let user delete a selected fabric js object

让人想犯罪 __ 提交于 2019-12-03 04:29:51

You can use the remove() method, eg.

window.deleteObject = function() {
        canvas.getActiveObject().remove();
}

jsfiddle

Since new version of fabric.js was released - you should use:

canvas.remove(canvas.getActiveObject());

Delete all selected objects:

canvas.getActiveObjects().forEach((obj) => {
  canvas.remove(obj)
});
canvas.discardActiveObject().renderAll()

I am using Fabric JS 2.3.6.

I wanted to allow the user to select one or more objects on the canvas and delete them by clicking the delete button.

Removed methods from old versions

The following methods are no longer available since the introduction of ActiveSelection:

setActiveGroup(group);
getActiveGroup();
deactivateAll();
discardActiveGroup();
deactivateAllWithDispatch();

Here is my code that works great for me and hopefully you as well.

$('html').keyup(function(e){
        if(e.keyCode == 46) {
            deleteSelectedObjectsFromCanvas();
        }
});    

function deleteSelectedObjectsFromCanvas(){
    var selection = canvas.getActiveObject();
    if (selection.type === 'activeSelection') {
        selection.forEachObject(function(element) {
            console.log(element);
            canvas.remove(element);
        });
    }
    else{
        canvas.remove(selection);
    }
    canvas.discardActiveObject();
    canvas.requestRenderAll();
}

you can delete active object by using backspace key

$(document).keydown(function(event){
    if (event.which == 8) {
        if (canvas.getActiveObject()) {
            canvas.getActiveObject().remove();
        }
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!