Search code examples
jquerycssscale

How to get ratio of scale image, when it's autoscaled by background-cover?


I have some problems:

I need to bind some text to positions om image (you know, like marks on redpen.io an other services). Text is binded to big image, well, like 1900x1200px.

Then on other pages I add this image to background of element, stretched to all window:

#backg {
    width: 100%;
    height: 100%;
    background-image: 'url-to-big-image.jpg'
    background-repeat: no-repeat;
    background-size: cover;
}

And then i have troubles: I can't bind my saved marks to this element! First, I divide original height and width of element to window height and width: Qh and Qw. I take original top and left css of mark, then multiply top*Qh and Qw*left.

It works for width, but not for height! It's somehow scaled by browser, and position of elements on image doesn't match.

How can I get ratio of height scaling, to position my marks?

Thanks in advance!


Solution

  • Despite the 'Hard' issue, the answer was quite simple, though not obvious :) All the matter between scales:

    First, we need to find coefficients of ratio between "real" height and width of picture and shown in the background:

    var imgSize = new Image();
    imgSize.onload = function() {
        $('#ourdiv').css('background-image', 'url("' + imgSize.src + '")');
        h_real = this.height;
        w_real = this.width;
    
        q_h = h_real / $(window).height();
        q_w = w_real / $(window).width();
    };
    imgSize.src = 'path_to_img.jpg';
    

    Then, divide our "real" positions of element to coef's. However,depending on whether the coefficient is greater, we should divide on another:

    if (q_w > q_h)
        {
            top_d = Math.round(top_d / q_h);   
            left_d = Math.round(left_d / q_h);
        }
    else
        {
            top_d = Math.round(top_d / q_w);   
            left_d = Math.round(left_d / q_w);        
        }
    

    And voila! - all elements on same places!