sandro
sandro

Reputation: 11

Detect click on fabric.Rect canvas object

In FabricJS there are many events to detect if object is scaled, moved, rotated or selected. but object:selected doesn't register the last object clicked .

When I create an object, for example a rectangle:

    var id2 = Math.random().toString(36).substr(2, 9);

    var rect = new fabric.Rect({
        left: 100,
        top: 50,
        width: 100,
        height: 100,
        fill: '#dedede',
        opacity: 0.5,
        id: id2
    });

    canvas.add(rect);
    canvas.sendToBack(rect);

then assign an ID to the object.

to detect if the object is clicked I use

canvas.on('object:selected', showCoord);

but object:selected doesn't register the last object clicked.

Doest there exist a click or dbclick event to attach to fabric shape?

Upvotes: 1

Views: 4362

Answers (2)

Malcolm Swaine
Malcolm Swaine

Reputation: 2268

I prefer to just handle the selection at object level rather than trying to filter all events on the canvas

   let newRect = new fabric.Rect(<Your object props>);
    
   newRect.on("selected", (element) => {
      // do stuff here
     console.log("selected", element);
   });

Upvotes: 0

Durga
Durga

Reputation: 15614

You can use events like mousedown, mousedblclick on objects, and mouse:down, mouse:dblclick on canvas.

DEMO

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

const rect = new fabric.Rect({
  left: 10,
  top: 10,
  fill: "#FF0000",
  stroke: "#000",
  width: 50,
  height: 50,
});
canvas.add(rect);
rect.on('mousedblclick', ()=>{
  console.log('on dblClick rect');
});
rect.on('mousedown', ()=>{
  console.log('on mousedown rect');
});
canvas.on('mouse:down', (options)=>{
  console.log('on canvas mousedown', options.target ? options.target.type : '');
});
canvas.on('mouse:dblclick', (options)=>{
  console.log('on canvas mouse dblclick', options.target ? options.target.type : '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script>
<canvas id="c" width="300" height="300" style="border: 2px solid green;"></canvas>

Upvotes: 3

Related Questions