Snapping of objects

by InferOn

HTML

<canvas id="fabriccanvas" width="800" height="500" style="border:1px solid #ccc"></canvas>

JavaScript

window.canvas = new fabric.Canvas('fabriccanvas');
window.counter = 0;
var newleft = 0,
    edgedetection = 20, //pixels to snap
    canvasWidth = document.getElementById('fabriccanvas').width,
    canvasHeight = document.getElementById('fabriccanvas').height;

canvas.selection = false;
plusrect();
plusrect();
plusrect();

function plusrect(top, left, width, height, fill) {
    window.canvas.add(new fabric.Rect({
        top: 300,
        name: 'rectangle ' + window.counter,
        left: 0 + newleft,
        width: 100,
        height: 100,
        fill: 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ', 0.75)',
        lockRotation: true,
        originX: 'left',
        originY: 'top',
        cornerSize: 15,
        hasRotatingPoint: false,
        perPixelTargetFind: true,
        minScaleLimit: 1,
        maxHeight: document.getElementById("fabriccanvas").height,
        maxWidth: document.getElementById("fabriccanvas").width,
    }));
    window.counter++;
    newleft += 200;
}

this.canvas.on('object:moving', function (e) {
    var obj = e.target;
    obj.setCoords(); //Sets corner position coordinates based on current angle, width and height

    // Prevent object from leaving canvas
    if(obj.getLeft() < edgedetection) obj.setLeft(0);
    if(obj.getTop() < edgedetection) obj.setTop(0);
    if((obj.getWidth() + obj.getLeft()) > (canvasWidth - edgedetection)) obj.setLeft(canvasWidth - obj.getWidth());
    if((obj.getHeight() + obj.getTop()) > (canvasHeight - edgedetection)) obj.setTop(canvasHeight - obj.getHeight());

    canvas.forEachObject(function (targ) {
        activeObject = canvas.getActiveObject();

        if(targ === activeObject) return;

        // Standard snapping when within range
        if(Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
            activeObject.left = targ.left - activeObject.currentWidth;
        }
       ...