0

I am trying to build an hybrid app and I need to get the size of a specific porition of the background.

  • The background has those properties : background-size: 100% 100%; background: url('back.jpg') no-repeat center center fixed;
  • I would like to place a div over that background and set the size of the div to the size of a precise portion of the background.

Here is an image to clarify what I would like to do : Background example with a red rectangle on it

The red rectangle on the backgroud image above is an example of the portion of the image I would like to calculate the size on a responsive screen.

I know how to make the elements follow the right absolute position on the background thanks to this topic Position element over background image, but not how to resize them to the right scale.

Can anyone help ?

Community
  • 1
  • 1
Djagu
  • 163
  • 1
  • 12
  • 1
    Just to clarify; does that image have the red square on it and you want to place a div over the red square? Or, is that red square just a representation of how it should look (i.e. there is no red square on the actual image)? – Duncan Tidd Feb 23 '16 at 15:31
  • The red square is on the image and I have to put a div exactly on the same place to replace the red scare by something in my div (ex: a photo), but the div has to have the same size as the red square (responsivly speaking) – Djagu Feb 23 '16 at 15:40

1 Answers1

0

I finally managed to fix the problem, which was not as complicated as I thought.

  • The first thing is to know the background width and height
  • The second is to know the size of the element we want on the background (for exemple the red scare)

    // In css : background-size: 100% 100%;
    var background = {width: 1200, height: 900 };
    var redScare = {selector: '.redScare', width: 400, height: 342, x: 50, y: 60};
    
    var xFactor = $( window ).width() / background.width;
    var yFactor = $( window ).height() / background.height;
    
    
    // New width proportionally to the window size
    redScare.width = redScare.width * xFactor;
    // New height proportionally to the window size
    redScare.height = redScare.height * yFactor; 
    
    //Setting the new dimensions
    
    $(redScare.selector).css('width', redScare.width);
    $(redScare.selector).css('height', redScare.height);
    
Djagu
  • 163
  • 1
  • 12