Torgia
Torgia

Reputation: 328

FabricJs - Limit the movement area of an added object inside a master object

using fabric, i can limit the movement of the objects inside the canvas with this code :

canvas.observe('object:moving', function (e) {
            debugger;
            var obj = e.target;
            obj.opacity = 0.5;
            if(obj.getHeight() > obj.canvas.height || obj.getWidth() > obj.canvas.width){
                obj.setScaleY(obj.originalState.scaleY);
                obj.setScaleX(obj.originalState.scaleX);
            }
            obj.setCoords();
            if(obj.getBoundingRect().top - (obj.cornerSize / 2) < 0 ||
                obj.getBoundingRect().left -  (obj.cornerSize / 2) < 0) {
                obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top + (obj.cornerSize / 2));
                obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left + (obj.cornerSize / 2));
            }
            if(obj.getBoundingRect().top+obj.getBoundingRect().height + obj.cornerSize  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width + obj.cornerSize  > obj.canvas.width) {

                obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top - obj.cornerSize / 2);
                obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left - obj.cornerSize /2);
            }
        });

what if i want to limit the movement of a selected object inside the area of a master object i define (excluding bounding area)?

thanks in advance

Upvotes: 2

Views: 2726

Answers (2)

DarioTecchia
DarioTecchia

Reputation: 41

I solved it by using a few lines of code:

canvas.on('object:moving', (e) => {
  var obj = e.target;

  obj.set({
    top: this.clamp(obj.top, 0, obj.canvas.height - obj.height),
    left: this.clamp(obj.left, 0, obj.canvas.width - obj.width),
  })
  obj.setCoords();

  this.editSettingsService.updateEditText({
    elem: e.target,
    reposition: true
  });
});

where clamp is:

private clamp(num:number, min:number, max:number) {
  return Math.min(Math.max(num, min), max);
};

Upvotes: 2

isuru
isuru

Reputation: 3565

Try following in your scaling function. Obj refers child object and master refers your parent object.

if(obj.getBoundingRect().top < master.top){ //Top boundary
    obj.top = master.top;
}
master.bottom = master.top+master.height;
if(obj.getBoundingRect().top+obj.getBoundingRect().height > master.top+master.height){  //Bottom boundary
    obj.top = master.bottom-obj.getHeight();   
}
if(obj.getBoundingRect().left < master.left){  //Left boundary
    obj.left = master.left;
}
master.right = master.left+master.width;
if(obj.getBoundingRect().left+obj.getBoundingRect().width > master.left+master.width){  //Right boundary
    obj.left = master.right-obj.getWidth();    
}

Upvotes: 0

Related Questions