Scale Element Proportional to Background Cover with Jquery

How to scale background image proportionally which is in css background of a div?

try this

<div style="height:100px;width:100px;
background-color:red;
background-image:url('test.jpg');
background-size:contain;
background-repeat:no-repeat;
background-position:center;"></div>

<div style="height:100px;width:100px;
background-color:red;
background-image:url('test.jpg');
background-size:cover;
background-repeat:no-repeat;
background-position:center;"></div>

working in gecko/webkit/opera and probably newers msie

full documentation at:

https://developer.mozilla.org/en/CSS/background-size

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

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!

How to scale a background image to cover, times an extra scaling factor?

I have created a Fiddle for you to check out. I believe I understood the question correctly but please let me know if I am off base.

I wrapped the div that has the background-image in another div like so:

<div class="hero-container">
<div class="row" id="hero"></div>
</div>

and applied the styles like so:

.hero-container {
overflow: hidden;
width: 100%;
height: 100vh;
}
#hero {
background: url('https://i.ytimg.com/vi/ReF6iQ7M5_A/maxresdefault.jpg') no-repeat center center scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
position: relative;
width: 100%;
height: 110vh;
margin-bottom: 0px;
right: 0;
}

Play around with the fiddle by changing the height: 110vh and let me know if this is what you were looking for, or if I am at least on the right track.

Hope this helps!

EDIT*: I removed the transition and the padding as these are not necessary.

If you would like to do this with a container that has a fixed height you can change the .hero-container height to 500px or something and then just use 110% instead of 110vh in the height for the #hero div.

retrieve the size of a background image set to cover

You're gonna want to preload the image.

var background = new Image();
background.src = "your-image.jpg";

var bgHeight = background.height;
var bgWidth = background.width;

Alright, here's the real answer. It took some thinking, and some borrowing of code from this answer: How can I determine the background image URL of a div via JavaScript?

But, I finally got it. I see you wanted a jQuery answer, but I work only in Native, JS, so sorry about the disconnect.

EDIT: I found some missing logic, so I threw it in. Now it should be good to go, hopefully.

http://jsfiddle.net/TLQrL/2/ - New link reflecting new logic

var div = document.getElementById("myDiv");
var style = div.currentStyle || window.getComputedStyle(div, false);
var bg = style.backgroundImage.slice(4, -1);

var background = new Image();
background.src = bg;

background.onload = function() {
if (background.width > background.height) {
var ratio = background.height / background.width;
if (div.offsetWidth > div.offsetHeight) {
var bgW = div.offsetWidth;
var bgH = Math.round(div.offsetWidth * ratio);
if (bgH < div.offsetHeight) {
bgH = div.offsetHeight;
bgW = Math.round(bgH / ratio);
}
} else {
var bgW = Math.round(div.offsetHeight / ratio);
var bgH = div.offsetHeight;
}
} else {
var ratio = background.width / background.height;
if (div.offsetHeight > div.offsetWidth) {
var bgH = div.offsetHeight;
var bgW = Math.round(div.offsetHeight * ratio);
if (bgW > div.offsetWidth) {
bgW = div.offsetWidth;
bgH = Math.round(bgW / ratio);
}
} else {
var bgW = Math.round(div.offsetWidth / ratio);
var bgH = div.offsetWidth;
}
}
console.log(bgW + ", " + bgH);
}

Proportional rescaling of background-image CSS HTML jQuery

background-size: cover

would usually be my solution. Have you tried using it with the full vendor prefixes, e.g.

-moz-background-size:    cover;
-webkit-background-size: cover;
-ms-background-size: cover;
-o-background-size: cover;
background-size: cover;

Failing that, setting:

background-width:        100%;
background-height: auto;
min-height: 790px;

would rescale the image responsively, but ensure it never dropped below the boundaries of the containing element.

Calculate the size of a specific portion on a background set with background-size: cover;

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);

Proportional rescaling of background-image CSS HTML jQuery

background-size: cover

would usually be my solution. Have you tried using it with the full vendor prefixes, e.g.

-moz-background-size:    cover;
-webkit-background-size: cover;
-ms-background-size: cover;
-o-background-size: cover;
background-size: cover;

Failing that, setting:

background-width:        100%;
background-height: auto;
min-height: 790px;

would rescale the image responsively, but ensure it never dropped below the boundaries of the containing element.

Scaling elements proportionally using CSS and JQUERY

Two issues that I can see from your code. You are running console.log on values that are not changed in the function. You set the variable, run some css transforms and then console.log the same variable, so not sure what you're expecting there.

The second thing is that when you use transform, the height and width values dont change. As you can see from the example below, those numbers stay static. That is actually the beauty of transform - to affect certain HTML elements without having to redraw the page.

$('.box').css('transform','scale(.6)');
console.log($('.box').width())
.box{
width:100px;
height:100px;
background:#000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='box'></div>

Background Size: Contain, get Size after scale

CSS property background-size: contain; scales the image to the largest so that both the height and width will fit inside, retaining the same aspect ratio of course.

Just like @Teemu said, A background image is a kinda pseudo element which you actually can't refer. But I can show you a workaround on how to get the real image size and compute the scaled background-image size.

It works like ratio and proportion where:

real_image_width is to real_image_height as resized_image_width is to resized_image_height

First we need to get the real size of the image:

var img = new Image;
img.src = $('#imageButton').css('background-image').replace(/url\(|\)$/ig, "");
var imgW = img.width;
var imgH = img.height;

Then, compare which dimension is the largest and calculate the proportion:

var newW, newH;

if(imgW > imgH){
newW = $('#imageButton').width(); //100;
newH = imgH / imgW * newW;
}else{
newH = $('#imageButton').height(); //100
newW = imgW / imgH * newH;
}

console.log(newW+':'+newH);

If the image is not yet loaded or cached it will return a size of 0, a good way to fix this is to get the size when the image is has been loaded using .load() function.

Browsers also differ in sub-pixel rendering, I think you need to round off to nearest .5 decimal to get the exact safest value (43.7832 => 43.5). Using: (Math.round(value * 2) / 2).toFixed(1)

That's it! Here is the sample fiddle.



Related Topics



Leave a reply



Submit