Let user delete a selected fabric js object

后端 未结 5 772
青春惊慌失措
青春惊慌失措 2021-02-05 02:03

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.newA         


        
相关标签:
5条回答
  • 2021-02-05 02:44

    Delete all selected objects:

    canvas.getActiveObjects().forEach((obj) => {
      canvas.remove(obj)
    });
    canvas.discardActiveObject().renderAll()
    
    0 讨论(0)
  • 2021-02-05 02:45

    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();
    }
    
    0 讨论(0)
  • 2021-02-05 02:55

    you can delete active object by using backspace key

    $(document).keydown(function(event){
        if (event.which == 8) {
            if (canvas.getActiveObject()) {
                canvas.getActiveObject().remove();
            }
        }
    });
    
    0 讨论(0)
  • 2021-02-05 03:00

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

    canvas.remove(canvas.getActiveObject());
    
    0 讨论(0)
  • 2021-02-05 03:09

    Edit: This is for older versions now.

    You can use the remove() method, eg.

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

    jsfiddle

    0 讨论(0)
提交回复
热议问题