Fabricjs traverses aWithObject returning false when Object is fabric.Rect

I am trying to determine when fabric.Rect overlaps with another structure. Notice the object: move event, but with inconsistent results between fabric.Group vs fabric.Rect

When I move a group over a Rect instance, the intersectsWithObject method returns true, but when I move a Rect instance on top of another Rect instance, it returns false.

I am wondering if I am doing something wrong.

Here is 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 created a violin. Try to select two or more blocks to group them. You will see that the grouped object turns red when it is dragged over any other fabric.Rect or fabric.Group object. When you drag one Rect over another fabric.Object of any type, it never turns red, since intersectsWithObject always returns false ...

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

+6
source share
1 answer

I found that by explicitly calling myObj.setCoords () before calling myObj.intersectsWithObject (otherObj) fixes the problem.

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

It looks like the coordinates of fabric.Rect are not updated automatically while they move during fabric.Group coordinates, although I could be outside the 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"); } } } }); 
+7
source

All Articles