Search code examples
javascriptfabricjs

How to set width and height of svg in fabricjs?


I am currently having an issue when setting width and height of a svg object in fabricjs. I tried setting it like this

   svg.width = 100;
   svg.height = 100;

But I am not getting the result I expected. It just crops the svg instead of scaling it. So, how can I set its width and height properly?

Any help will be appreciated. Thanks!


Solution

  • Use scaleToWidth() and scaleToHeight() method to properly set SVG object­*'s* width and height respectively.

    :-: working example :-:

    var canvas = new fabric.Canvas('fabric-canvas');
    fabric.loadSVGFromURL('http://cdn.shopify.com/s/files/1/0496/1029/files/Freesample.svg?5153', function(objects, options) {
       var svg = fabric.util.groupSVGElements(objects, options);
       svg.left = 50;
       svg.top = 50;
       svg.scaleToWidth(100);
       svg.scaleToHeight(100);
       canvas.add(svg);
       canvas.renderAll();
    });
    canvas{border:1px solid #ccc}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.13/fabric.min.js"></script>
    <canvas id="fabric-canvas" width="200" height="200"></canvas>