1

I want to know if it's possible to determine the (new) dimensions of a background image after it has been resized with css3's 'background-size: cover' using Javascript. (Not working) Example: http://jsfiddle.net/daco/GygLJ/3/

Cheers,

  • Daco
Daco
  • 61
  • 2
  • 6

2 Answers2

2

I don't know enough pure JS to post this without assuming jQuery but it can probably be ported easily.

What you could do is find the src of the background image, then use javascript's built in width / height functions to get its dimensions.

eg:

    //jQuery
var imgSrc = $('#test').css('background-image');
//might need to do a bit of parsing on that, returns: url(http://blahblah)
alert(imgSrc);
imgSrc=imgSrc.replace('url("', '').replace('")', '');
alert(imgSrc);

var newImg = new Image();
newImg.onload=function()
{
    var h = newImg.height;
    var w = newImg.width;
    alert('w:'+w+' h:'+h);
};
newImg.src=imgSrc;

Hope this helps

Example here: http://jsfiddle.net/vap8p/

EDIT: updated source and linked to working example

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85
  • Thanks for your answer, it's however not what I meant. I'm not interested in the *original* dimensions, but the resulting dimensions after the image has been resized with the (uber cool) css3 'background-size: cover' rule. – Daco Aug 12 '11 at 10:11
  • ahh I see. only thing i can think of now would be to emulate whatever calculations CSS3 does to get the image that big... i expect that it scales up the longest (or both if they are equal) side of the image to be the corresponding height or width of the container element. redoing a calculation like that in js using the original image dimensions and the container div width and height might get you something close. – totallyNotLizards Aug 12 '11 at 10:34
0

Assuming background-image css for element with ID 'mydiv'. All native JavaScript. Won't interact with other JavaScript on page.

(function (id) {
    var img = new Image(), elm = document.getElementById(id);
    img.dataset.w = elm.offsetWidth;
    img.dataset.h = elm.offsetHeight;
    img.addEventListener('load', function () {
        var maxw = this.dataset.w,
            maxh = this.dataset.h,
            aspect = this.width / this.height;
        if(maxw > maxh * aspect) alert(maxw + ' x ' + maxw / aspect);
        else alert(maxh * aspect + ' x ' + maxh);
    }, false);
    img.src = window.getComputedStyle(elm).backgroundImage.slice(4, -1);
})('mydiv');​

You might want to round down.

For contain rather than cover, change the compare to the opposite.

if(maxw < maxh * aspect) alert(maxw + ' x ' + maxw / aspect);
Paul S.
  • 64,864
  • 9
  • 122
  • 138