@lew
To get the aspect ratio of an image using JavaScript, you can follow these steps:
Here is an example code snippet that demonstrates this process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function getAspectRatio(imageSrc) { const img = new Image(); img.src = imageSrc; return new Promise((resolve, reject) => { img.addEventListener("load", () => { const aspectRatio = img.naturalWidth / img.naturalHeight; resolve(aspectRatio); }); img.addEventListener("error", (error) => { reject(error); }); }); } // Example usage: const imageSrc = "https://example.com/image.jpg"; getAspectRatio(imageSrc) .then((aspectRatio) => { console.log("Aspect ratio:", aspectRatio); }) .catch((error) => { console.error("Error:", error); }); |
Note that the code uses a Promise to handle the asynchronous loading of the image, ensuring that the aspect ratio is calculated only after the image has been loaded successfully.