Snap edges of objects to each other and prevent overlap

I solved the problem on my own.
See jsfiddle: http://jsfiddle.net/gcollect/FD53A/

This is the code:

this.canvas.on('object:moving', function (e) {
var obj = e.target;
obj.setCoords(); //Sets corner position coordinates based on current angle, width and height
canvas.forEachObject(function (targ) {
    var objects = this.canvas.getObjects(),
        i = objects.length;
    activeObject = canvas.getActiveObject();

    if (targ === activeObject) return;


    if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
        activeObject.left = targ.left - activeObject.currentWidth;
    }
    if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
        activeObject.left = targ.left + targ.currentWidth;
    }
    if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
        activeObject.top = targ.top - activeObject.currentHeight;
    }
    if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
        activeObject.top = targ.top + targ.currentHeight;
    }
    if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {
        targ.strokeWidth = 10;
        targ.stroke="red";
    } else {
        targ.strokeWidth = 0;
        targ.stroke = false;
    }
    if (!activeObject.intersectsWithObject(targ)) {
        activeObject.strokeWidth = 0;
        activeObject.stroke = false;
    }
});

Works pretty legit! Cheers!

Leave a Comment