Search code examples
javascriptangularfabricjs

image fit into canvas fabricjs


I am using Fabricjs for upload image with the current code

Image is showing only 1/4th of the full image. It's not showing full image in a canvas in this tscode i am setting width and height of the image manually.

Here is my Ts code

  addImage(canvasInst, imageUrl) {
fabric.Image.fromURL(imageUrl, img => {
  var oImg = img.set({
    left: 0,
    top: 0
  });
  var canvasWidth = canvasInst.width / canvasInst.getZoom();
  oImg.scaleToWidth(canvasWidth);
  canvasInst.add(oImg).renderAll();
  canvasInst.toDataURL({ format: "png", quality: 0.8 });
});

}

But i was trying other way scaletowidth but that is not working here

here is the stackblitz

Example

enter image description here


Solution

  • FabricJS uses the properties scaleX and scaleY to determine the size of the image, while the width and height properties are used to specify how much of the original image dimensions should be used (shrinking these values will crop the image, not scale it).

    In your linked example, you're running scaleToWidth() on the canvas. You need to run it on the image instead.

    fabric.Image.fromURL(imageUrl, img => {
      var oImg = img.set({
        left: 0,
        top: 0
      });
      var canvasWidth = canvasInst.width / canvasInst.getZoom();
      oImg.scaleToWidth(canvasWidth);
      canvasInst.add(oImg).renderAll();
    });