Maintaining background image aspect ratio when resizing canvas in Fabric.JS

43 Views Asked by At

So i have this canvas made in Fabric.JS and I need it to be as large or smaller that 600x600, so i set up the canvas, make its width and height the same as the image and then set maxWidth and maxHeight to 600. The intended behavior would be for the canvas to have a maximum width and maintaining the aspect ratio of the image, scaling it down. But it just stretches the image to fill the 600x600 space. Any suggestions?

I already tried using scaleImageToWidth() and scaleImageToHeight(), but it doesn't work. Here is my code:

var canvas = new fabric.Canvas('canvas');

fabric.Image.fromURL(path, function (oImg) {

    // sets the background image
    let img = new Image();
    img.src = path;

    img.onload = function () {

        canvas.setDimensions({
            width: this.width,
            height: this.height,
            maxWidth: 600,
            maxHeight: 600
        });
    }

    canvas.setBackgroundImage(oImg, canvas.renderAll.bind(canvas));
}

And here is the result: result image

0

There are 0 best solutions below