Search code examples
fabricjs

Set object drag limit in Fabric.js


i am new in fabric js want to set the drag limitenter image description here

i have also try with https://github.com/kangax/fabric.js/wiki/Working-with-events

not able to get the solution.

please check the attached image, object can move anyware but it should be display in red area only.i want this. help me...thanks in advance !!


Solution

  • What had worked for me is to create an event listener for the object:moving event. When the move is happening you update the goodtop and goodleft variables and once you are out of bounds to reposition the object to the last good points.

    var goodtop, goodleft, boundingObject;
    
    canvas.on("object:moving", function(){
        var obj = this.relatedTarget;
        var bounds = boundingObject;
        obj.setCoords();
        if(!obj.isContainedWithinObject(bounds)){
            obj.setTop(goodtop);
            obj.setLeft(goodleft);
            canvas.refresh();    
        } else {
            goodtop = obj.top;
            goodleft = obj.left;
        }  
    });