How to get the aspect ratio of an image using javascript?

Member

by lew , in category: Javascript , 9 months ago

How to get the aspect ratio of an image using javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 9 months ago

@lew 

To get the aspect ratio of an image using JavaScript, you can follow these steps:

  1. Create an Image object and set the src attribute to the image source.
  2. When the image is loaded, use the naturalWidth and naturalHeight properties to get the original width and height.
  3. Calculate the aspect ratio by dividing the width by the height.
  4. Return the aspect ratio.


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.