0

I have a div with a background image, which size is set to contain:

.image{
    width: 95%;
    height: 95%;
    position: absolute;
    margin: 0 auto;
    left: 0;
    right: 0;
    top: 50%;
    -webkit-transform: translateY(-50%);
    background-image: url('image_url');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
}

Large images are being "scaled down" to fit in that div. I want to get the width and height of the image AFTER it was scaled down by background-size: contain;

I tried to do the following:

var myImg, frame;
document.addEventListener("DOMContentLoaded", onload);
function onload() {
    myImg= document.getElementById('image');
    frame = document.getElementById('frame');

    var img = new Image();
    img.src = window.getComputedStyle(myImg).getPropertyValue("background-image").replace(/url\(|\)$/ig, "");
    img.onload = function() {
        var imgHeight = img.height;
        console.log(imgHeight);
    }
}

The problem is I'm getting the size of the actual image, not the resized one. Can it be done? Also, I need to use plain vanilla JS, not jQuery or any other library...

empiric
  • 7,825
  • 7
  • 37
  • 48
Igal
  • 5,833
  • 20
  • 74
  • 132
  • You could take another approach and instead of getting the image dimensions you could calculate them yourself. Since you have the image dimensions and the div dimensions, this shouldn't be to hard. – Fester Jun 01 '15 at 07:05
  • @Fester Perhaps shouldn't be, but I'm having a few troubles with that... Any idea how to do that? – Igal Jun 01 '15 at 07:45
  • Have a look at this question: http://stackoverflow.com/questions/21127479/getting-the-height-of-a-background-image-resized-using-background-size-contain – Fester Jun 01 '15 at 08:13

0 Answers0