admin管理员组

文章数量:1136186

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.

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.

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked Jul 30, 2015 at 14:49 user5049061user5049061
Add a comment  | 

9 Answers 9

Reset to default 97

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

canvas.remove(canvas.getActiveObject());

Edit: This is for older versions now.

You can use the remove() method, eg.

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

jsfiddle

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

It's pretty simple actually.

Just use Fabric's event handling to manage the object selection, and then fire the delete function for whatever object is selected.

I'm using the canvas selection events to cover all the objects of the canvas. The idea is to add a delete button, keeping it hidden unless needed, and then handling its display on canvas selection events.

Deletion is made easy with the help of remove property of the Fabric library, which obviously triggers when the delete button is clicked.

Here is some sample code to demo what I said above.

// Grab the required elements
var canvas = new fabric.Canvas('c'),
    delBtn = document.getElementById('delete')

// Hide the delete button until needed
delBtn.style.display = 'none'

// Initialize a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 100,
  height: 50
})

// Initialize a circle object
var circle = new fabric.Circle({
  left: 250,
  top: 100,
  radius: 20,
  fill: 'purple'
})

// Add objects to the canvas
canvas.add(rect)
canvas.add(circle)

// When a selection is being made
canvas.on({
  'selection:created': () => {
    delBtn.style.display = 'inline-block'
  }
})

// When a selection is cleared
canvas.on({
  'selection:cleared': () => {
    delBtn.style.display = 'none'
  }
})

// Rmove the active object on clicking the delete button
delBtn.addEventListener('click', e => {
  canvas.remove(canvas.getActiveObject())
})
body {
  background-color: #eee;
  color: #333;
}

#c {
  background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.4.0/fabric.min.js"></script>

<h4>Select an object</h4>

<canvas id="c" width="600" height="200"></canvas>

<input type="button" id="delete" value="Delete selection">

Easy, wasn't it? Cheers!

On further improving @Rahul answer, we can also support deletion of selected object using key events like 'Delete', 'Backscape'.

// Grab the required elements
var canvas = new fabric.Canvas('c'),
    delBtn = document.getElementById('delete'),
wrapper= document.getElementById('canvasWrapper')

// Hide the delete button until needed
delBtn.style.display = 'none'

// Initialize a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 100,
  height: 50
})

// Initialize a circle object
var circle = new fabric.Circle({
  left: 250,
  top: 100,
  radius: 20,
  fill: 'purple'
})

// Add objects to the canvas
canvas.add(rect)
canvas.add(circle)

// When a selection is being made
canvas.on({
  'selection:created': () => {
    delBtn.style.display = 'inline-block'
  }
})

// When a selection is cleared
canvas.on({
  'selection:cleared': () => {
    delBtn.style.display = 'none'
  }
})

// Rmove the active object on clicking the delete button
delBtn.addEventListener('click', e => {
  canvas.remove(canvas.getActiveObject())
})

//Remove using keyboard events
wrapper.addEventListener('keyup', e => {
   if (
      e.keyCode == 46 ||
      e.key == 'Delete' ||
      e.code == 'Delete' ||
      e.key == 'Backspace'
    ) {
      if (canvas.getActiveObject()) {
        if (canvas.getActiveObject().isEditing) {
          return
        }
        canvas.remove(canvas.getActiveObject())
      }
    }
})
body {
  background-color: #eee;
  color: #333;
}

#c {
  background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.4.0/fabric.min.js"></script>

<h4>Select an object</h4>
<div tabIndex="1000"id="canvasWrapper" @keyup="checkDelete($event)" >
<canvas id="c" width="600" height="200"></canvas>
</div>
<input type="button" id="delete" value="Delete selection">

Delete object in Fabricjs. This works completely fine.

this.canvas.getActiveObjects().forEach((o) => {
    this.canvas.remove(o);
})
this.canvas.discardActiveObject() // Removes selection box

A much cleaner way to do it is to use the spread operator:

canvas.remove(...canvas.getActiveObjects())

The spread operator will pass each active object as a separate argument to the function.

you can delete active object by using backspace key

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

本文标签: javascriptLet user delete a selected fabric js objectStack Overflow