Snap edges of objects to each other and prevent overlap

前端 未结 4 2010
庸人自扰
庸人自扰 2020-12-01 08:48

My goal is to prevent overlapping of two or more rectangles inside my FabricJS canvas.

Imagine two rectangles having info on position and size and you can drag and d

4条回答
  •  甜味超标
    2020-12-01 09:00

    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!

提交回复
热议问题