Scaling Divs Perfectly Within Background-Size: Cover Or Alternatives

51 Views Asked by At

I am trying to create a full screen responsive background image (like css background-size:cover) that contains divs that keep there exact position on the image whilst being scaled via a browser resize.

<div class="full_Screen_background">
     <div class="image_to_fill_and_scale_fullscreen">
        <div class="content_to_be_scaled_with_window_resizing">
  
        </div>
    </div>
</div>

And the css:

.content_to_be_scaled_with_window_resizing{
 border:5px solid #000;
 position:absolute;
 top:30%;
 left:40%;
 height:10%;
 width:10%;
}

.image_to_fill_and_scale_fullscreen{  
background: url(../4706825697_c0367e6dee_b.jpg);  
position: relative;
background-size: cover;
background-position: center;
background-attachment: scroll;
height: 100vh;
background-repeat: no-repeat;
}

The desired outcome is to have the div perfectly scale proportionally with the image as the browser is resized.

Any ideas would be much appreciated?

https://jsfiddle.net/sfLgvyz0/

1

There are 1 best solutions below

7
Christian On

I tried it with a canvas. Hope that works for you. I fixed the rectangle to the head of the biker.

window.onload = drawFullImage;
window.onresize = drawFullImage;

function drawFullImage() {
  var c = document.getElementById("myCanvas");
  var imageDiv = c.parentNode;
  c.width = imageDiv.getBoundingClientRect().width;
  c.height = imageDiv.getBoundingClientRect().height;
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, c.width, c.height);
  var img = document.getElementById("imagetorender");
  ctx.drawImage(img, 0, 0, c.width, c.height);
  ctx.strokeRect(c.width / 100 * 75, c.height / 100 * 30, c.width / 100 * 10, c.height / 100 * 10);
}
body {
  width: 100vw;
  position: relative;
  margin: 0;
}

#imagetorender {
  visibility: hidden;
  max-height: 100%;
  width: 100%;
}

#myCanvas {
  position: absolute;
  top: 0;
  left: 0;
}
<div id="wrapper">
  <img id="imagetorender" src="http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg" />
  <canvas id="myCanvas"></canvas>
</div>

Edit: I used a hidden image to get the aspect ratio right.