简体   繁体   中英

Getting the width and height of an Image

So I have a element and I want to get the image's height and width property, however this is my css:

 let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px','')); let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px','')); console.log(`width`,w); console.log(`height`,h);
 img#image{ z-index: 0; display: block; top: 0px; margin-left: auto; margin-right: auto; max-height: 100%; max-width: 100%; position: absolute; align-self: center; margin: auto; left: 0; right: 0; }
 <img src="src.jpg" id="image">

as you can see i didn't set a height and width property because I don't want the image to have a fixed width and height, so someone introduced me to use:

window.getComputedStyle(document.getElementById('image')).getPropertyValue('height')

and so I did, but it is not accurate from my experience:

JS :

let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''))
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''))
console.log(`width`,w)
console.log(`height`,h)

here is the screenshot of the results it logged: https://media.discordapp.net/attachments/244238416248569857/812200556403490847/Screenshot_1540.png?width=1067&height=600

and here is the screenshot of the actual width and height of the element: https://media.discordapp.net/attachments/244238416248569857/812200556000313354/Screenshot_1541.png?width=1067&height=600

as you can see the image is 670 x 514 but it logged 459 as its height, anyone can help me with this problem?

Tricky World

The problem is that your image needs to be loaded first.

Well, this is a really interesting problem, though.

Here, in the code below, we're checking if the image is loaded, if so we just get the width and height directly without any problem.

But if the image is not loaded yet, we set an event listener to track it. When it's loaded the function within the event listener will be called, so and that's it. Now you have access to all information about the image.

 const img = document.getElementById("img"); if(img.complete) { console.log(img.width, img.height); } else { img.addEventListener('load', function() { const imageWidthRendered = this.width; const imageHeightRendered = this.height; console.log(imageWidthRendered, imageHeightRendered) }); }
 <img id="img" src="https://source.unsplash.com/random/100x200">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM