Get both real and displayed image width using JavaScript

I have several images in an HTML document. The width of these elements often changes due to the max-width CSS property, which applies to all of them.

I want to know if .jpeg / .png / can be obtained as the actual width. any image files, and the width displayed to the user, this means that I want to know if the images are changing due to the max-width property or not.

Resizing images using JavaScript after loading the page instead of using max-width not acceptable.

+4
source share
2 answers

The answer (pointed out by someone who just deleted it) should use naturalWidth .

0
source

 window.addEventListener("load", function() { var imgs = document.querySelectorAll('img'); for (var i = 0; i < imgs.length; i++) { var imgTag = imgs[i]; var image = new Image(); image.src = imgTag.src; output.innerHTML = "Width: " + image.width + " Height: " + image.height; } }); 
 img { max-width: 200px; } 
 <img src="http://www.google.com/images/srpr/logo11w.png"/> <p id="output"></p> 

I just put it together and it seems to have worked.

It depends on the type of JavaScript Image . I also used "onload", not DOMContentLoaded, so when requesting an image, we can be sure that it is already loaded and that we do not need to wait for its onLoad callback.

0
source

Source: https://habr.com/ru/post/1481019/


All Articles