Search code examples
fabricjs

set Min and Max resize limits for fabric object


I am using fabric js for resizing object i want user to resize the object with in min&max limits. How to do this with fabric js.

I tried properties like

lockScalingX,lockScalingY,lockMomentX,lockMomentY but no luck.

Any help will be grateful.

Thanks,


Solution

  • There is no way to do it natively in fabric but you can hook in to the scaling event and make any modification to the object you should like. In this code I stop the scaling as well as correct fabric from shifting the top/left when I am over riding the scaling.

    window.canvas = new fabric.Canvas('c');
    
    var rect = new fabric.Rect({ 
      left: 100, 
      top: 100, 
      width: 50, 
      height: 50, 
      fill: '#faa', 
      originX: 'left', 
      originY: 'top',
      stroke: "#000",
      strokeWidth: 1,
      centeredRotation: true
    });
    
    canvas.add(rect);
    
    var maxScaleX = 2;
    var maxScaleY = 2;
    
    rect.on('scaling', function() {
      if(this.scaleX > maxScaleX) {
        this.scaleX = maxScaleX;
        this.left = this.lastGoodLeft;
        this.top = this.lastGoodTop;
      }
      if(this.scaleY > maxScaleY) {
        this.scaleY = maxScaleY;
        this.left = this.lastGoodLeft;
        this.top = this.lastGoodTop;
      }
      this.lastGoodTop = this.top;
      this.lastGoodLeft = this.left;
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
    <canvas id="c" width="600" height="600"></canvas>