javascript - How to get the current, "real", background image size, when background-size is cover? -


this might have been asked before , tried answer given in thread: how dimensions background image when background-size set contain?

but in case, background-size set cover, instead of contain.

the background size 1920x1080. have div-element scales width , height 100%, meanwhile background-image if said div set cover.

1920 / 1080 gives ratio of 1.7, whenever browser widow scaled div's width/height ration on or under 1.7 aka. not in correct ratio - things break. need way calculate size of background image correctly set things up.

edit: here example jsfiddle of situation: https://jsfiddle.net/ahvonenj/35pbovmz/

if resize result area, can see result area has width , height, 400x600. however, 400 width , 600 height incorrect calculations. need know size of background image is. notice how background keeps ratio leaving of image out.

the result area width , height correct when result area width/height ratio of background image, 1.7 in case.

edit 2: working: https://jsfiddle.net/ahvonenj/35pbovmz/

i found solution myself. here nice jsfiddle visualization, calculate container size , actual background image size separately.

you can resize image container (red border) dragging bottom right corner , see how container size changes separately actual background size: https://jsfiddle.net/ahvonenj/o76k5jbx/

$(document).ready(function() {     var fullhdwidth = 1920;     var fullhdheight = 1080;     var fullhdratio = fullhdwidth / fullhdheight; // 1.7      $('#wrapper').resize(function()     {         var containerwidth = $(this).width();         var containerheight = $(this).height();         var containerratio = containerwidth / containerheight;         var realwidth = null;         var realheight = null;          console.log(containerwidth, containerheight, containerratio);          if(containerratio > fullhdratio)         {             realwidth = containerwidth;             realheight = containerwidth/fullhdratio;         }         else         {             realwidth = containerheight*fullhdratio;             realheight = containerheight;         }        }); }); 

note: using this small library detect size changes on container div element, jquery's resize handler can bound window object.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -