En el caso de una imagen cuadrada, es una función que la centraliza, pero hay un problema. Como configuro el ancho máximo y la altura máxima, si subo una imagen de un teléfono inteligente que excede el ancho máximo, la proporción disminuye, por lo que quiero que la imagen de un teléfono inteligente se ajuste al tamaño del lienzo. Gracias de antemano, ¿eres una buena persona para las matemáticas? Estoy deprimido porque no soy bueno en matemáticas y ni siquiera puedo implementar esta función simple.
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; };