Question

How to find an object within a fabric group at the cursor position?

Assume the following canvas initialization:

var text = new fabric.Text('Hello');
var rect = new fabric.Rect({width: 100, height: 50});
var group = new fabric.Group([text, rect], {
    left: 150, top: 100, angle: -10
});
canvas.add(group);

Now I would like to detect the object (i.e. either text or rect) below the cursor. Something like the following:

canvas.on('mouse:move', myFunc);
myFunc = function(o) {
   var target = canvas.findTarget(o.e);
   if (target.type === 'group') {
       var obj = group.findTarget(o.e);
       // obj should be now either rect, text or null
   } 
}

However, I cannot find any function like group.findTarget.

Was it helpful?

Solution

I know it is late. But may be it will helps to someone else. Thanks to asturur, he made a solution. solution

I downloaded fabricjs from asturur repo. build fabric.js file

node build.js modules=ALL exclude=json,gestures

and it works!

Then you can use events on objects in the groups.

canvas._objects[0]._objects[0].on('mousedown', function(e){ this.stroke = 'black'});

In my app i decided to search for events from mousedown callback

group.on('mousedown', function(e){
    var innerTarget  = group._searchPossibleTargets(e.e);
    console.log(innerTarget);
});

group._searchPossibleTargets = function(e) {
    var pointer = this.canvas.getPointer(e, true);
    var i = objects.length,
        normalizedPointer = this.canvas._normalizePointer(this, pointer);

    while (i--) {
        if (this.canvas._checkTarget(normalizedPointer, this._objects[i])) {
            return this._objects[i];
        }
    }
    return null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top