Search code examples
javascriptroundingfabricjsrect

How to maintain rounded corner of Rect when scaling in fabric js


I am using fabric js version 1.7.22.

Original Object:

enter image description here

Current result :

enter image description here

Expected result :

enter image description here


Solution

  • One way would be to watch for scaling events and reset the Rect's scale to 1, modifying its width and height instead:

    const canvas = new fabric.Canvas('c')
    
    const rect = new fabric.Rect({
      left: 10,
      top: 10,
      width: 100,
      height: 100,
      fill: 'blue',
      rx: 10,
      ry: 10,
      objectCaching: false,
    })
    
    rect.on('scaling', function() {
      this.set({
        width: this.width * this.scaleX,
        height: this.height * this.scaleY,
        scaleX: 1,
        scaleY: 1
      })
    })
    
    canvas.add(rect).renderAll()
    canvas {
      border: 1px solid red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
    <canvas id="c" width="300" height="250"></canvas>