简体   繁体   中英

How do I set both height and width of image so that it can fit the size of my canvas in fabric.js?

So I have an image in my canvas, and I am trying to make the image fit the canvas (I want image inside the canvas to be of the same size as the canvas). I use scaleToWidth() and scaleToHeight() to set the image size. But only one of them works. If I only use scaleToWidth() then it scales the width correctly, and if I only use scaleToHeight() then it scales the height correctly. In the code below, the height is being scaled correctly as it is written in the line below oImg.scaleToWidth(cDim.clientWidth) . But I want both the width and height to be according to my values. How can I do that?

                const canvas = new window.fabric.Canvas('c');
                const cDim = document.getElementById("canvas-dimension");
                console.log("Canvas Height: " + cDim.clientHeight);
                console.log("Canvas Width: " + cDim.clientWidth)
                let planURL = baseURL + "dream" + "/" +  "plan";
          

                window.fabric.Image.fromURL(planURL, (oImg) => {
                    
                    //let scaleW = cDim.clientWidth / oImg.getWidth;
                    // let scaleH = cDim.clientHeight / oImg.getHeight;
                   // oImg.scaleX(scaleW)

                    oImg.scaleToWidth(cDim.clientWidth)
                    oImg.scaleToHeight(cDim.clientHeight)
             
      
                    canvas.setBackgroundImage(oImg);
                    canvas.renderAll();

                },{ crossOrigin: 'anonymous'});
                setCanvas(canvas)

Any help or workaround to this will be appreciated. Thank you!

SOLVED

So I used this approach instead of scaleToWidth and scaleToHeight , and it worked!

let scaleW = cDim.clientWidth / oImg.width;
let scaleH = cDim.clientHeight / oImg.height;
oImg.set({
     opacity: 1,
     scaleX: scaleW,
     scaleY: scaleH,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM