'How to set dynamic Background Canvas Width in Fabricjs

How set dynamic Width of the canvas depending of the Image background resolution in Fabricjs Library.

It similar with the CSS image height: 100%; then the width will be dynamic and 500px height.

<canvas id="c" height="500" width="500"><canvas>


Solution 1:[1]

  • Here according to canvas you can set image width and height.
    const canvas = new fabric.Canvas("canvas");
    
     fabric.Image.fromURL('https://www.kraftwerk.at/app/uploads/fly-images/962/reference-img-worlds-of-adventure-park-4-1920x9999.jpg', function(img) {
                        canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
                            scaleX: 200,
                            scaleY: canvas.height / img.height
                        });
                    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/460/fabric.min.js"></script>
    <canvas id="canvas" width="500" height="450" style="border:1px solid black"></canvas>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iron Man