I'm drawing n rectangles on a canvas. The rectangles are draggable and scalable. I want to prevent them from overlapping or intersecting. The best case is, if they just snap to each other.
I figured out to check the intersection. In my example I set the opacity of touching objects to 0.1.
Coincidentally in my attempt to solve this problem, my objects cant be released when they touch another object. See http://jsfiddle.net/gcollect/jZw7P/
It's because of line 91, where the alert is not executed. alert(math.abs(distx));
Actually its a kind of solution, but definitely not an elegant one.
Any ideas?
I figured it out how to prevent the collision on the x-axis. By adding these lines:
See JSFiddle. Actually it's pretty cool and the objects snap to each other on the x-axis. Troublemaker is now the y-axis. An approach from top or below will move the object to the left or right edge... Will work on this issue.
I've been contemplating a similar problem and I + the last fiddle here from @kangax. One could even use this type of mechanism to do collision detection for paths themselves if one has a path collision detection algorithm like the polygon intersection code found here: http://www.kevlindev.com/geometry/2D/intersections/index.htm.
But what I don't like about this 'sticky' solution is that to me the object should actually slide along the surface for my application instead of forcing the user to 'unstick' the object. For this kind of effect, I realized that a 2D physics engine would probably do a great job of enabling this type of functionality, and some of the example uses of http://brm.io/matter-js/ demonstrate solving the problem and the positioning and rotation should surely be able to map into fabric.js. However, if fixed rotation is required, it looks like the probability of success would be reduced.
This is based on gco's answer, updated to work with FabricJS 1.5.0, with the following improvements:
JS Fiddle: https://jsfiddle.net/aphillips8/31qbr0vn/1/
For those who are still interested in the solution: I solved it here: https://stackoverflow.com/a/22649022/3207478 See jsfiddle: http://jsfiddle.net/gcollect/FD53A/
Working with
these solutions are pretty good, but non of them working with rotated objects. I came up with this. It's preventing intersecting of objects..Even rotated.
I made up this fiddle. Check it out.
[Fiddle]
(http://jsfiddle.net/m0jjc23v/9)Explanation:
Workaround is that you have to save last non-intersectiong top & left position while moving object. When object is intersecting or isContained with another object, just use previously saved top & left position and reposition object. There's a lot of possible improvements. Feel free to use this code and make improvements.
Code: