Reputation: 1351
In CSS I set a button to be 100px x 100px and have the background-size: contain;
In javascript I apply an image to the element that I do not have the Height/width of (nor aspect ratio) .
In another function in javascript I need to be able to get the size of the image/background of this button after it has passed through the contain function.
Is there any way to do this (I have access to Jquery as well)
Small Sample:
<style>
#imageButton{
width: 100px;
height: 100px;
background: url("imageURL");
background-size: contain !important;
}
</style>
<script>
var imageElem = $('#imageButton')[0];
console.log($(imageElem).width());
//100px but need width of image after scaling
</script>
Upvotes: 7
Views: 4389
Reputation: 3799
CSS property background-size: contain;
scales the image to the largest so that both the height and width will fit inside, retaining the same aspect ratio of course.
Just like @Teemu said, A background image is a kinda pseudo element which you actually can't refer. But I can show you a workaround on how to get the real image size and compute the scaled background-image size.
It works like ratio and proportion where:
real_image_width is to real_image_height as resized_image_width is to resized_image_height
First we need to get the real size of the image:
var img = new Image;
img.src = $('#imageButton').css('background-image').replace(/url\(|\)$/ig, "");
var imgW = img.width;
var imgH = img.height;
Then, compare which dimension is the largest and calculate the proportion:
var newW, newH;
if(imgW > imgH){
newW = $('#imageButton').width(); //100;
newH = imgH / imgW * newW;
}else{
newH = $('#imageButton').height(); //100
newW = imgW / imgH * newH;
}
console.log(newW+':'+newH);
If the image is not yet loaded or cached it will return a size of 0, a good way to fix this is to get the size when the image is has been loaded using .load()
function.
Browsers also differ in sub-pixel rendering, I think you need to round off to nearest .5 decimal to get the exact safest value (43.7832 => 43.5). Using: (Math.round(value * 2) / 2).toFixed(1)
That's it! Here is the sample fiddle.
Upvotes: 6