Search code examples
javascriptfabricjs

how to hide the handle that changes the aspect ratio in fabric.js


I don't want to change the aspect ratio of the object, so I want to hide the handles other than the four corners.

In the following page, if you select "select rectangle", handles will be displayed in between the four corners, and if you operate it, the aspect ratio will change.

https://codepen.io/janih/pen/zGxoZv

handle image


<html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <!-- http://stackoverflow.com/questions/20096949/how-to-select-fabric-js-object-programmatically -->
        <!-- http://jsfiddle.net/ThzXM/1/ -->
        <style>
            canvas {
                border: 1px solid #ccc;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
        <script type="text/javascript">
            $( document ).ready(function() {
                var canvas = new fabric.Canvas('canvas');
                canvas.add(new fabric.Rect({
                    left: 100,
                    top: 100,
                    width: 75,
                    height: 50,
                    fill: 'green',
                    stroke: 'black',
                    strokeWidth: 3,
                    padding: 10
                  }));

                 canvas.add(new fabric.Circle({
                    left: 200,
                    top: 200,
                    radius: 30,
                    fill: 'gray',
                    stroke: 'black',
                    strokeWidth: 3
                  }));


                $( "#selectrectangle" ).click(function() {
                 canvas.setActiveObject(canvas.item(0));
                });

                $( "#selectsecond" ).click(function() {
                 canvas.setActiveObject(canvas.item(1));
                });
                canvas.renderAll();
            });
        </script>

        </head>

        <body>
            <input id = "selectrectangle" type="button" value="select rectangle"/>
            <input id = "selectsecond" type="button" value="select second object"/>
            <canvas id="canvas" width="400" height="400" style="border:1px solid red"/>
        </body

</html> 


version

fabric.js v4.6.0


Solution

  • You use the setControlsVisibility method on a fabric object:

    obj.setControlsVisibility({
        mt: false,
        mb: false,
        ml: false,
        mr: false
    });
    

    Documentation is here: http://fabricjs.com/controls-customization

    Fiddle: http://jsfiddle.net/av01d/pnrvmc93/