Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS Catch click on object inside group

I have tried many thing like calculating location, handling with the event we do have in original fabricjs. Does any have done this before?

like image 395
Honchar Denys Avatar asked Dec 02 '15 15:12

Honchar Denys


3 Answers

It is possible to listen for events on the inner object by adding the option: subTargetCheck: true to the fabric.Group object.

    // create a group
    let group = new fabric.Group([circle, rect], {
        subTargetCheck: true
    });

    circle.on('mousedown', function(e) { 
        // e.target should be the circle
        console.log(e.target);
    });
like image 190
Kevin Farrugia Avatar answered Nov 01 '22 18:11

Kevin Farrugia


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;
}
like image 20
Denis Ponomarev Avatar answered Nov 01 '22 19:11

Denis Ponomarev


In FabricJS once the objects have been assembled into a group the Events are only happening there, even the selected events - so you cannot detect which of the items in the group are being selected. Inside the event handler

var g = new fabric.Group([ rect, text ], {
g.on('mousedown', function(e) {
    // Inspect, for a collection of the objects in this group
    this._objects
});

Even attaching event handlers to the objects before assembly into the group the handlers don't fire :(

like image 1
edoceo Avatar answered Nov 01 '22 18:11

edoceo