Fabricjs intersectsWithObject returning false when

2020-07-11 09:25发布

问题:

I'm trying to determine when a fabric.Rect overlaps another fabric.Rect while observing the 'object:moving' event but having inconsistent results between fabric.Group vs fabric.Rect

When I move Group over a Rect instance the intersectsWithObject method returns true, but when I'm moving a Rect instance over another Rect instance it returns false.

I'm wondering if I'm doing something wrong here.

Here's my event handler

cvs.observe('object:moving', function(e) {

    var targ = e.target;

    // filter out itself
    var items = cvs.getObjects().filter(function(o){
        return targ !== o;
    });

    var hit = false;

    for (var i = 0, n = items.length; i < n; i++) {
        var m = items[i];

        if (targ.type == "group") {
            if (targ.intersectsWithObject(m)) {
                targ.setFill("red");
                hit = true;
                console.log("GROUP HIT");
            } else {
                if (!hit) {
                    targ.setFill("#CCCCCC");
                }
            }
        } 
        else {
            // this is always returning false! why?
            if (targ.intersectsWithObject(m)) {
                var id = m.data ? m.data.entityId : " ??"
                console.log("OBJECT HIT:" + id);
                targ.setFill("red");
            }
        }
    }
});

I've created a fiddle. Try selecting two or more blocks to group them. You'll see the grouped object turn red when it is dragged over any other fabric.Rect or fabric.Group instance. When you drag a single Rect over another fabric.Object of any type, it never turns red as intersectsWithObject is always returning false...

http://jsfiddle.net/cyberpantz/9MkYJ/27/

回答1:

I found that by explicitly calling myObj.setCoords() prior to calling myObj.intersectsWithObject(otherObj) fixes the issue.

I updated the fiddle here http://jsfiddle.net/cyberpantz/9MkYJ/29/

It appears that fabric.Rect coordinates are not updated automatically while it is being moved while fabric.Group coordinates are, although I could be off-base here...

Updated (and simplified) code

cvs.observe('object:moving', function(e) {

    var targ = e.target;

    // this fixes it
    targ.setCoords();

    var items = cvs.getObjects().filter(function(o){
        return targ !== o;
    });

    var hit = false;

    for (var i = 0, n = items.length; i < n; i++) {
        var m = items[i];

        if (targ.intersectsWithObject(m)) {
            targ.setFill("red");
            hit = true;
        } 
        else {
            if (!hit) {
                targ.setFill("#CCCCCC");
            }
        }
    }
});


标签: fabricjs