is there an easy way to get the final height and width of a background image with Javascript or jQuery even if a background-size
property was applied?
I mean, I know I can get the background image url and load it to an Image
object and then get the width and height. But it is the size of the source image. If someone scaled it with CSS then the size changed
How can I find its final size?
@edit
it is different from the question marked as similar because it doesnt say how to get the size in pixels if someone changed the background-size
Using
getComputedStyle
, I've created this script that returns the width and height of a given element's background, in pixels. It works with:auto
, either explicitly or because no specific value was given (width and height default toauto
)%
px
width: 100px; height: auto
orwidth: auto; height: 32.4%
orheight: 100px; width: 2%
orwidth: 21.2%
)background-size
set tocover
orcontain
It works if
background-size
is set with an external CSS file, inline CSS, inline header CSS or if it is not set at all (meaning width and height areauto
).Here's a JsFiddle (with cover example)
http://jsfiddle.net/gp4e9d3z/3/
And here's StackOverflow's code snippet (with
percentage auto
units)Using the JSFiddle Here, I found that changing the height or width of the container forces the image to be scaled to the largest height or width. Meaning that the measurement of one edge of the background will be equal to one of the dimension of the container. Using this and some proportions we can calculate the dimensions of the image.
The above code uses the proportion below to calculate it.
I think it should give you the answer you want.