FabricJs - 限制主对象内添加对象的移动区域

时间:2016-05-19 14:34:35

标签: javascript fabricjs

使用fabric,我可以使用以下代码限制画布内对象的移动:

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);
            }
        });

如果我想限制所选对象在我定义的主对象区域内的移动(不包括边界区域)怎么办?

提前致谢

2 个答案:

答案 0 :(得分:0)

在缩放功能中尝试以下操作。 Obj引用子对象,master引用父对象。

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();    
}

答案 1 :(得分:0)

我通过使用几行代码解决了这个问题:

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
  });
});

其中 clamp 是:

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