marshy101
marshy101

Reputation: 594

How can I handle events, in Fabric.js, on a individual object within a group?

Lets say i have 3 circles and add them to a group.

var circle1 = new fabric.Circle({
  radius: 50,
  fill: 'red',
  left: 0
});
var circle2 = new fabric.Circle({
  radius: 50,
  fill: 'green',
  left: 100
});
var circle3 = new fabric.Circle({
  radius: 50,
  fill: 'blue',
  left: 200
});

var group = new fabric.Group([ circle1, circle2, circle3 ], {
  left: 200,
  top: 100
});

canvas.add(group);

How can I handle mouse events for just, let's say, circle1?

Or in other words, how can I know which of the objects, in the group, the mouse clicked on?

Upvotes: 3

Views: 5842

Answers (4)

ChiefJ
ChiefJ

Reputation: 11

This is a pretty old post but fabricJS groups have a subTargetCheck option.

According the docs: Indicates if click, mouseover, mouseout events & hoverCursor should also check for subtargets

http://fabricjs.com/docs/fabric.Group.html#subTargetCheck

This does exactly what you requested

Upvotes: 1

Oleg Averkov
Oleg Averkov

Reputation: 342

  circle2.on('mouseup', function(event) {
    console.log(`circle2 mouseup`);
  });

Upvotes: -2

Theo Itzaris
Theo Itzaris

Reputation: 4681

when you group objects together , you make the group object to behave as an object, so it rotates, it moves, it scales, it listens to events like any other individual object. you cant listen to any events on the individual objects just because now all together are form one object only.

of course the group object has item methods item(index), getObjects() so you can get the individual objects and get/update their properties.

  1. a custom solution could be to :

    1. get the mouse:down event
    2. get the pointer position
    3. read through all _objects of the group object
    4. compare the position of the mouse pointer to the position of the activeObj._objects[item]
    5. if it fits you have found the child object

something like this:

canvas.observe('mouse:down', function (options)
{
    pos = canvas.getPointer(options.e);
    console.log("POSITION"+pos);
        activeObj = canvas.getActiveObject();
        if (Math.abs(pos.x - activeObj.left) < 10 && Math.abs(pos.y - activeObj.top) < 30 && Math.abs(pos.y - activeObj.top) > 10) {
            console.log("connector selected");            
        }    
});

another discussion is made here for that issue, if you would like to take a look: https://github.com/kangax/fabric.js/issues/485

hope helps, good luck

Upvotes: 3

Darryl Hebbes
Darryl Hebbes

Reputation: 1028

When the events fires you can inspect the target object through the canvas listener callBack, I am not sure if the object has a property for the shape type. Else you could assign a property on adding the circle saying that its a circle, the pick it up through the event.

canvas.on('mouse:up', function(e) {
  console.log(e.target); // should contain info on the clicked object
});

Upvotes: 0

Related Questions