1

I have an image of a ball that I get from outer resource and I need to get the size of the image (height and width) for further calculations, but what I tried it shows 0 (but it's 40px actually)

Here is the whole code:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Ball to center</title>
    <style>
      #field {
        width: 200px;
        border: 10px groove black;
        background-color: #00FF00;
        position: relative;
      }

      #ball {
        position: absolute;
      }
    </style>
  </head>
  <body>

    <div id="field">
      <img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    </div>

    <script type="text/javascript">
      let field = document.getElementById('field');
      let ball = document.getElementById('ball');
      console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
      console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);
    </script>
  </body>
</html>
Robert Hovhannisyan
  • 2,938
  • 6
  • 21
  • 43
  • 4
    If you try to get the dimensions of the image before it loads, I imagine that they would be zero. Try doing your logic after the load event happens. – Taplar May 20 '20 at 18:31

2 Answers2

1

The problem with your approach, is that the code is executed before the page is loaded. As seen in here, you can do something like this with vanilla javascript to wait until page is loaded.

let field = document.getElementById('field');
let ball = document.getElementById('ball');

window.onload = () => {
  console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
  console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);  
};
mhSangar
  • 457
  • 3
  • 12
0

You should only check the size of the image after it loads. You could use the loaded property of the image element to see if it's already loaded, otherwise attach a handler to the load event.,

let ball = document.getElementById('ball');

const checkImgSize = el => {
    console.log(`natural height and width: ${el.naturalHeight} - ${el.naturalWidth}`);
    console.log(`client height and width: ${el.clientHeight} - ${el.clientWidth}`);
};

if( ball.loaded )
    checkImgSize(ball);
else 
    ball.addEventListener('load', function(){ checkImgSize(this) }, { once: true });
JakeParis
  • 11,056
  • 3
  • 42
  • 65