How to delete a selected fabric.js object?

Sometimes, we want to delete a selected fabric.js object.

In this article, we’ll look at how to delete a selected fabric.js object.

How to delete a selected fabric.js object?

To delete a selected fabric.js object, we use the canvas.getActiveObjects() method to get all selected objects.

Then we call remove with each selected item as the arguments.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/460/fabric.min.js"></script>

<canvas style='width: 300px; height: 300px' id="canvas"></canvas>

<button id='add'>
  add
</button>

<button id='delete'>
  delete
</button>

to add the fabric.js script with the canvas and add and delete buttons.

Then we write:

const canvas = new fabric.Canvas('canvas');
const add = document.querySelector('#add')
const del = document.querySelector('#delete')

add.addEventListener('click', () => {
  const rect = new fabric.Rect({
    left: Math.floor(Math.random() * 300),
    top: Math.floor(Math.random() * 300),
    fill: 'red',
    width: 20,
    height: 20,
  });
  canvas.add(rect);

  const circle = new fabric.Circle({
    radius: 20,
    fill: 'green',
    left: Math.floor(Math.random() * 300),
    top: Math.floor(Math.random() * 300),
  });
  canvas.add(circle);
})

del.addEventListener('click', () => {
  canvas.getActiveObjects().forEach((obj) => {
    canvas.remove(obj)
  });
  canvas.discardActiveObject().renderAll()
})

We create the fabric.js canvas object with the fabric.Canvas constructor with the ID string.

Then we select the buttons with document.querySelector.

Then we call addEventListener on add to add a click listener to it.

In the event handler, we create a fabric rectangle and circle with the fabric.Rect and fabric.Circle constructors respectively.

We set the left and top to random values to randomly position the shapes.

Then we call del.addEventListener to add a click listener to it.

In the click listener, we get the selected objects with getActiveObjects.

Then we call forEach on it with a callback to remove each selected object.

To remove them we call canvas.remove with obj as the argument.

Then we call canvas.discardActiveObject().renderAll() to refresh the canvas.

Conclusion

To delete a selected fabric.js object, we use the canvas.getActiveObjects() method to get all selected objects.

Then we call remove with each selected item as the arguments.