'I want to fill the background as big as fabric.js canvas, but I can't do math
In the case of a square image, it is a function that centralizes it, but there is a problem. As I set the maximum width and maximum height, if I upload a picture of a smartphone that exceeds the maximum width, the ratio decreases, so I want the picture of a smartphone to fit the size of the canvas. Thank you in advance, are you a good math person? I'm depressed because I'm not good at math and I can't even implement this simple function.
const setBackground = (url, canvas) => {
fabric.Image.fromURL(url, (img) => {
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
setBackgroundFromDataUrl: setBackgroundFromDataUrl(url, canvas),
});
});
};
// 캔버스 배경 중앙정렬
const setBackgroundFromDataUrl = (dataUrl, canvas, options = {}) => {
if (!dataUrl) {
return true;
}
let img = new Image();
img.setAttribute("crossOrigin", "anonymous");
img.onload = () => {
let maxWidth = 1080;
let maxHeight = 1920;
// maxWidth // Max width of the canvas
// maxHeight //Max height of canvas
let imgWidth = img.width; // Current image width
let imgHeight = img.height; // Current image height
let widthAspectRatio = maxWidth / imgWidth;
let heightAspectRatio = maxHeight / imgHeight;
let finalAspectRatio = Math.min(widthAspectRatio, heightAspectRatio);
let finalHeight = imgHeight * finalAspectRatio;
let finalWidth = imgWidth * finalAspectRatio;
let imgTop = 0;
if (maxHeight > finalHeight) {
imgTop = (Math.round(maxHeight) - Math.round(finalHeight)) / 2;
}
let imgLeft = 0;
if (maxWidth > finalWidth) {
imgLeft = (Math.round(maxWidth) - Math.round(finalWidth)) / 2;
}
let nsgImage = new fabric.Image(img).scale(finalAspectRatio);
nsgImage.set({
left: imgLeft,
top: imgTop
});
canvas.setBackgroundImage(nsgImage, () => canvas.renderAll());
};
img.src = dataUrl;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

