Move object within canvas boundary limit

前端 未结 6 1621
野性不改
野性不改 2020-12-08 00:58

I am trying to limit the moving object within the canvas but i am getting some difficulty to moving object with limit area on top and left side and when i scale the object w

6条回答
  •  一整个雨季
    2020-12-08 01:29

    As i needed this, here is my overworked function based on Balaji's code to set a offset, so objects can be only partly showed within the canvas.

    canvas.on('object:moving', function (e) {
          var obj = e.target;
    
          // if object is too big ignore
          if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
              return;
          }        
    
          // set offset for moving out the canvas (20 % of object persists in canvas)
          var offsetWidth = obj.getBoundingRect().width * 0.8;
          var offsetHeight = obj.getBoundingRect().height * 0.8;
    
          obj.setCoords();        
    
          // top-left  corner
          if(obj.getBoundingRect().top < -offsetHeight || obj.getBoundingRect().left < -offsetWidth){
              obj.top = Math.max(obj.top, obj.top-(obj.getBoundingRect().top+offsetHeight));
              obj.left = Math.max(obj.left, obj.left-(obj.getBoundingRect().left+offsetWidth));
          }
          // bot-right corner
          if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height + offsetHeight || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width + offsetWidth){
              obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top+offsetHeight);
              obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left+offsetWidth);
          }
    });      
    

提交回复
热议问题