I need to centralize background image inside canvas based on zoom factor while retaining aspect ratio of image and without being cropped. I tried in this way but either it gets cropped(cannot make whole image viewable). This is how I have done and this is how it looks
import { fabric } from "fabric";
import "./styles.css";
document.getElementById("app").innerHTML = `
<div>
<canvas class="canvas" id="conCanvas"></canvas>
</div>
`;
let canvas = new fabric.Canvas("conCanvas");
let zoomedScaleFromServer = 1.5;
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
// let imgWidth, imgHeight;
fabric.Image.fromURL(
"https://media.istockphoto.com/photos/modern-interior-design-floor-plan-3d-render-picture-id1210637949?b=1&k=20&m=1210637949&s=170667a&w=0&h=_AYB0vxwWWVFSUjaNpVb3X88ybQLLXtdNJUW8IllR1E=",
function (img) {
canvas.setBackgroundImage(
img,
() => {
canvas.renderAll();
// imgWidth = img.width * img.scaleX;
// imgHeight = img.height * img.scaleY;
}
// { FIX : Aspect ratio
// scaleX: canvas.width / img.width,
// scaleY: canvas.height / img.height
// }
);
// canvas.centerObject(img);
canvas.setWidth(img.width * zoomedScaleFromServer);
canvas.setHeight(img.height * zoomedScaleFromServer);
canvas.zoomToPoint(
new fabric.Point(canvas.width / 2, canvas.height / 2),
zoomedScaleFromServer
);
}
);
Here is the sandbox as well https://codesandbox.io/s/festive-water-izl19?file=/src/index.js