How to select Fabric.js object programmatically with JavaScript?

Sometimes, we want to select Fabric.js object programmatically with JavaScript.

In this article, we’ll look at how to select Fabric.js object programmatically with JavaScript.

How to select Fabric.js object programmatically with JavaScript?

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.

For instance, we write:

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

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

We add the fabric.js script and the canvas element.

Then we write:

const canvas = new fabric.Canvas('canvas');

canvas.add(new fabric.Rect({
  left: 80,
  top: 80,
  width: 75,
  height: 50,
  fill: 'green',
  stroke: 'black',
  strokeWidth: 3,
  padding: 10
}));

canvas.add(new fabric.Circle({
  left: 50,
  top: 50,
  radius: 30,
  fill: 'gray',
  stroke: 'black',
  strokeWidth: 3
}));

canvas.setActiveObject(canvas.item(0));

We use the fabric.Canvas constructor with the ID of the canvas to create a fabric canvas.

Then we call canvas.add to add a rectangle and circle at various positions, shapes, fill and sizes.

Then we set the select item to the item we added first, which is the rectangle, by writing:

canvas.setActiveObject(canvas.item(0));

We call canvas.setActiveObject with canvas.item(0) to select the first object to be selected,.

Conclusion

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.