In this example: Fiddle Example
I have a Picture with dimensions 835x470
, That image is added to 2 elements, A hidden <img>
and as a background to a <div>
width class wrapper
, I set the <div>
dimensions to smaller dimensions 519x220
on my screen.
There is a centered circular element on the <div>
with the dimensions 100x100
, I want to set these dimensions with the same ratio the image changed from 835x470
to 519x220
.
So for example if the circle on the original image 835x470
was 200x200
, When the <div>
dimensions are set/changed to 519x220
, The circle would take the same space it took on the original image, Which were 200x200
.
So if the 200x200
represented 15%
for example from the 835x470
, Then the circle would take the same 15%
from the new dimensions 519x220
What I tried to do is that I get the natural dimensions of the image 835x470
and get the new dimension of the image 519x220
and divide each dimension to get a ratio, Then check to get the smallest ratio (Not to make the circle be out of the image), Then multiply this ratio by 200
and set it as width
and height
of the image.
Here is the code:
//Get natural dimensions from the hidden image.
var imgNaturalHeight = document.getElementById('img').naturalHeight,
imgNaturalWidth = document.getElementById('img').naturalWidth,
//Get new dimensions from the wrapper that has the image as a background.
imgNewHeight = document.querySelector('.wrapper').height,
imgNewWidth = document.querySelector('.wrapper').width,
//Get height and width ratios.
widthRatio = imgNewWidth / imgNaturalWidth,
heightRatio = imgNewHeight / imgNaturalHeight,
//Define ratio variable.
ratio;
//Set ratio to the smallest ratio.
if ( widthRatio < heightRatio ) {
ratio = widthRatio;
}else{
ratio = heightRatio;
}
//The new value for width and height
var fixed = ratio * 200;
//Set the new width and height of the circle.
document.querySelector('.overlay').style.width = fixed;
document.querySelector('.overlay').style.height = fixed;
.wrapper{
position: relative;
background: url('https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/docs/images/picture.jpg');
height:220px;
background-repeat: no-repeat;
background-size: 100%;
}
.overlay{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: rgba(0,0,0,0.4);
border-radius: 50%;
width: 100px;
height: 100px;
}
.image{
display:none;
}
<div class="wrapper">
<div class="overlay"></div>
</div>
<img id="img" class="image" src="https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/docs/images/picture.jpg" >
I hope I made it clear.