如何在fabric js中设置canvas对象的拖动限制?

时间:2016-04-04 07:51:26

标签: javascript fabricjs

我想设置canvas对象的拖动限制,所以不要 移动到剪辑区域之外。这里我的剪辑区域是形状 所以请帮助我。

在此图像中,您可以看到画布区域和剪辑区域

enter image description here

1 个答案:

答案 0 :(得分:1)

Here you can find solution :
On this solution I had included corner size to avoid object placed out of canvas while dragging, scaling.

var canvas = window._canvas = new fabric.Canvas('c');
canvas.selection = false;

fabric.Object.prototype.set({
    transparentCorners: false,
    cornerColor: 'red',
    cornerSize: 12,
    padding: 0
});
text = new fabric.Text('Sample',{
    top: canvas.height/2,
    left: canvas.width/2,
    fill: '#000000'
});

canvas.add(text);
canvas.setActiveObject(text);

canvas.observe('object:scaling', function (e) {
    var obj = e.target;
  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);    
  }
});

canvas.observe('object:moving', function (e) {
    var obj = e.target;
  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);    
  }
});

http://jsfiddle.net/jw1827fm/1/