TL;DR
There should be a way in JS to (synchronously) get real width and height of an already loaded image not affected by width
and height
attributes or by anything else.
The naturalWidth
and naturalHeight
properties cannot be used for that anymore since those are now affected by irreversible inconsistent implicit calculations for unknown practical purpose.
Details
The naturalWidth
and naturalHeight
properties were already providing exactly this ability until it has been decided by WHATWG that a sort of correction should be applied to those values by dividing in corresponding pixel ratio.
The correction is applied to images specified via the srcset
attribute. Even worse, resulting values are inaccurate and therefore original values cannot even be restored as is.
For example, for the same 100×100 image:
<img src="example.png" alt="" />
<img srcset="example.png 3x" alt="" />
naturalWidth
is 100
in the first case and 33
in the second one.
We could check if the image has the srcset
attribute and multiply (or not) naturalWidth
/ naturalHeight
by corresponding pixel ratio conditionally. But:
-
to determine the pixel ratio, we are forced to parse
srcset
(oh my…) (please correct me if I’m wrong); -
srcset
value may be invalid; -
there is a precision issue (
33*3
is99
, not the original100
, so information is irreversibly lost).
So the story would get too complicated given that we are trying just to obtain the exact value that browser already knows directly and precisely.
So now we are again (as before introducing naturalWidth
and naturalHeight
) forced to use a redundant asynchronous new Image
request and then read the dummy-image’s width
and height
once it’s loaded, instead of just reading the real dimensions of the already loaded image synchronously and directly.
As a result, some new properties should probably be introduced like realWidth
and realHeight
for the purpose of getting the real original size of image not corrupted by any redundant implicit calculations. In other words, the new properties should return exactly the same values that are returned respectively by width
and height
properties of an image created via new Image
.
Thanks.