How do I set a background image as the background size: contain on boot, but not resize when the window is resized?
3 answers
Thanks guys, I solved it like this:
$scope.getImageSize = function(div){
var backgroundImage = new Image();
backgroundImage.src = $(div).css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
backgroundImage.onload = function() {
var width = this.width;
var height = this.height;
var object = $(div);
/* Step 1 - Get the ratio of the div + the image */
var imageRatio = width/height;
var coverRatio = object.outerWidth()/object.outerHeight();
/* Step 2 - Work out which ratio is greater */
if (imageRatio >= coverRatio) {
/* The Height is our constant */
var coverHeight = object.outerHeight();
var scale = (coverHeight / height);
var coverWidth = width * scale;
} else {
/* The Width is our constant */
var coverWidth = object.outerWidth();
var scale = (coverWidth / width);
var coverHeight = height * scale;
}
var cover = coverWidth + 'px ' + coverHeight + 'px';
$localStorage.image = {width: coverWidth + "px", height: coverHeight + "px"};
$('.pane').css('backgroundSize', $localStorage.image.width + " " + $localStorage.image.height);
return $localStorage.image;
};
}
Since this is a mobile app and I am blocking orientation, I am assuming the width and height will not change, I change the background-size
same width and height with the changed width from background-size: contain
.
0
source to share