Let user delete a selected fabric js object

雨燕双飞 提交于 2019-12-20 16:30:12

问题


I have a simple fabric js based application where I will let users add shapes connect them and animate them.

Following is my JS

var canvas; 
window.newAnimation = function(){
   canvas = new fabric.Canvas('canvas');
}

window.addRect = function(){
    var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20,
});
    canvas.add(rect);

}

window.addCircle = function(){
    var circle = new fabric.Circle({
  radius: 20, fill: 'green', left: 100, top: 100
});
    canvas.add(circle);
}

This is my Fiddle. You can click on new animation and then add objects as of now.

I want the user to select some object and then also be able to delete it I am not sure how. I found this Delete multiple Objects at once on a fabric.js canvas in html5 But i was not able to implement it successfully. I basically want users to be able to select an object and delete it.


回答1:


You can use the remove() method, eg.

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

jsfiddle




回答2:


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

canvas.remove(canvas.getActiveObject());



回答3:


Delete all selected objects:

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



回答4:


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



回答5:


you can delete active object by using backspace key

$(document).keydown(function(event){
    if (event.which == 8) {
        if (canvas.getActiveObject()) {
            canvas.getActiveObject().remove();
        }
    }
});


来源:https://stackoverflow.com/questions/31727049/let-user-delete-a-selected-fabric-js-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!