I have the following simple code to get me the background-image dimensions, but it grabs the size of the original image, not the scaled one I have in my div. I want to get pixel dimensions after scaling, is there any way to do that?
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
actualImage.onload = function () {
width = this.width;
height = this.height;
}
EDIT:
The CSS to scale the background-image:
#chBox {
height:100%;
width:100%;
background-repeat:no-repeat;
background-image: url(../content/frog/1.jpg);
background-position: center;
-webkit-background-size: contain; /*for webKit*/
-moz-background-size: contain; /*Mozilla*/
-o-background-size: contain; /*opera*/
background-size: contain; /*generic*/
}
Instead of getting the dimensions of the actual image, you need to get the $('#someImage').css('width') and $('#someImage').css('height') of the image you want.
edit:
#someImage img {
width: 100px;
height: auto;
}
<td id="image">
<img id="someImage" src="image.jpg">
<script type="text/javascript">
alert($('#someImage').css('width'));
</script>
</td>
the code above would alert "100px". and of course if you use some jQuery to change the width of the image, like $('#someImage').css('width','300px'), the code would the update and alert "300px"
The code is doing what you're telling it to do. I don't believe there is a way to grab the 'scaled' size.
Alright, thanks to everyone for their responses but I thought of a bit of a workaround. I would like to see this feature in a later release of jQuery (grabbing scaled width, height) but with some math, it ain't so bad.
Essentially,
// create a fake image and load the original from background-img src
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
// get original values
var origWidth = this.width;
var origHeight = this.height;
var width = 0;
var height = 0;
// need to bump it 140px as it seems the div's left comes from the super-container
var bump = 140;
// if the image is fat rather than tall,
if(origWidth > origHeight){
// set width for description to width of bg-img container
var width = $("#chBox").width();
// set left
$(".description").css("left", bump);
// calculate height and set bottom
height = (width * origHeight) / origWidth;
var blankSpace = $("#chBox").height() - height;
$(".description").css("bottom", (blankSpace/2));
} else {
// if image is tall,
var height = $("#chBox").height();
// calculate width
width = (height * origWidth) / origHeight;
// set left
var setLeft = $("#chBox").width();
$(".description").css("left", (setLeft/2) - 58); //wtf, 58?
// set bottom to 0
$(".description").css("bottom", 0)
}
$(".description").width(width);
}
There's quite a bit of site-specific stuff there, but basically I ran some algebra to find the proportions of the image. If it's a fat image rather than a tall image, the width of the container is the scaled width. The height is equal to the scaled width * original image height divided by the original image width. For some reason (and if someone could help with this I'd be grateful) the margin: 0 auto; property of my CSS doesn't work when you change up the div width, so I had to manually center it.
Related
How can I resize of a image base on screen size. Example:
I have a tag (width:1349, height: 449) and a image in div (width:78, height:78). When display image in div I fix for width of image is 60 and height is 60. I saw in mobile screen then the size of image still keep state so now I want to image display automatic resize base on screen example: in iPhone 4 the image have size (20x20) or percent of it in the screen. How can I use the formular for calculate it? This is my code jquery for calculate it.
var mw = $("#c").width();
var mh = $("#c").height();
console.log();
var img = new Image();
img.src = './img/photo-circle.png';
var wdImg = img.width;
var hiImg = img.height;
var ratioImg = wdImg/hiImg;
var ratioDiv = mw/mh;
if (ratioDiv > 1) {
var newwd = wdImg*(mh/hiImg);
alert(newwd);
} ;
You should be using percentages to achieve dynamic resizing of your elements. Then, as long as the parents are also dynamically resizing, their children will as well. For example, width: 30%; instead of width: 100px;
use the css unit vh and vw
each unit is worth 1% of the screen size
http://caniuse.com/#feat=viewport-units
example:
.item {
height: 20vw;
width: 20vw;
}
If the screen width is 100pixels, .item would be 20px by 20px
Simply you can use a bootstrap class called "img-responsive" at your img tag .
That's all , It will be responsive on any screen.
I have this code for a responsive banner
.mybanner {
height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
responsive image background works fine, the only problem is .mybanner container's height is not changing
for example when i test with big screen
mybanner div element width = 980px
mybanner div element height = 320px
bakcground_image width = 980px
background_image height = 320px
but when i resized screen, let say width mybanner div element become 680px
mybanner div element width = 680px
mybanner div element height = 320px
bakcground_image width = 680px
background_image height = 220px
from that example there is different value mybannder height with background_image height, so it's become ugly white space
I already tried to modify it like this, to make .mybanner height became auto
.mybanner {
min-height:170px;
max-height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
or this:
.mybanner {
height:100%;
//height:auto;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
but not work....
any idea how to make height of div .mybanner change too depending on image size on his background
You can use javascript to change height.
<body onresize="resizediv()">
<div class="mybanner" id="mybanner">
...
<script>
function resizediv() {
div = document.getElementById('mybanner');
var imageSrc = div.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
div.style.height = image.height;
}
</script>
Or There are all background size valid properties, you can chose best one:
http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Or simple don't use background, put the IMG to the div as a object and set image width 100% don't edit div and image height, it will compute automatically.
Consider these simple CSS rules:
jsFiddle
div#container {
width: 50%;
height: 260px;
background-image: url('Image.png');
background-repeat: repeat-x;
}
The problem is that I only want full images. If there is not enough space for another duplicate, it should NOT be shown.
I've never heard that CSS provides a rule for it. So how can I achieve it in JavaScript (jQuery already included)?
This is not possible with current CSS rules. You can repeat once, or repeat forever. The alternative is to shrink the size of the containing element to fit the nearest repeating point in either CSS (if you know the width before page load) or JS (if you don't).
Here's the latter implentation using jQuery:
var $container = $("#container");
var bgImg = extractUrl($container.css("background-image"));
var $img = $("<img />", { "src" : bgImg }).hide().appendTo("body");
$container.width(nearest($("#container").width(), $img.width()));
$img.remove();
function extractUrl(input) {
// remove quotes and wrapping url()
return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
}
function nearest(n, v) {
n = n / v;
n = Math.floor(n) * v;
return n;
}
Example fiddle
This will work for percentage widths and auto adjusts on sreen resize.
$(window).on('load resize', function () {
var img = $('<img/>');
img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg').load(function () {
var height = this.height;
var width = this.width;
var divWidth = $('#containerwrap').width();
var extra = divWidth % width;
$('div#container').width(divWidth - extra);
});
});
div#container {
width: 670px;
height: 260px;
margin:0 auto;
background: url('http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg') left center;
background-repeat: repeat-x;
}
#containerwrap{
width:100%;
height: 260px;
background-color:#000000;
}
<div id="containerwrap">
<div id="container">
Test
</div>
</div>
http://jsfiddle.net/upjkd/14/show
As the width is fixed by the server, and the server knows the size of the image - why not construct the image to be correct and forget the repeat, or make the width the appropriate size so it will fit whole number of images?
See http://jsfiddle.net/upjkd/10/
var img=document.createElement('img');
img.src="http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg";
document.body.appendChild(img);
var con=document.getElementById('container'),
numImages=Math.round(con.clientWidth/img.clientWidth);
con.style.backgroundSize=con.clientWidth/numImages+'px';
document.body.removeChild(img);
You can use Math.round(con.clientWidth/img.clientWidth) to determine the number of repetitions of the image, and then use con.style.backgroundSize=con.clientWidth/numImages+'px' to be sure that the number of images is an integrer (only full images).
I have concocted a little script here out of bits and pieces I have found and scraped together, but I need a little help to add an extra function to it,
First of all - this is what it is doing for me at the moment:
It resizes and crops/letterboxes an image to completely fill a div
which is a % height and a % width – it keeps doing this whenever and
whatever window resize
It keeps working seamlessly as the window is resized
The image is filling 100% the area the div covers - left to right
and top to bottom.
The image is not being squashed or stretched - just being cropped
or is overflowing.
The image is kept as small as possible, so whatever the resize -
you can still see either the very sides OR the very top and bottom of
the image.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and Safari
over XP and 7
All of these things are very important to me, please don't tell me that all i need is:
<img style="width : 100%;">
This is so much more than that. It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Now, what I want to add:
All it is, I’d like the letter box to centre on the image.
When the div is a very tall portrait or a very flat landscape I’m just getting the top or just the left hand side of the image.
I’d like the centre of the original image to stay in the centre of the resized div.
I’ve tried a few things but have drawn a blank. I’m sure the script could feed a minus top: or left: into the style but it seems if I get too many div’s in div’s IE doesn’t like it, or what am I doing wrong?
Thing is I don’t really know how to wright this stuff, I only steal bit and bobs and splat them together…
And finally the demo
And the script:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
Thanks Very Much For This.
I'm not quiet sure if that's what you're looking for, but let's try this:
*upd: the wysiwyg is not working on comments at this moment, so sorry for messy code snippets.
1.Position the div#imgarea relatively. You can then float it to the right, to replicate your right:0px declaration. Don't forget to hide the overflow, to ensure that 'letter-boxed' parts of the image stay hidden.
#imgarea {
position: relative;
width: 70%;
height: 75%;
float: right;
overflow: hidden;
top: 25%;
};
Some user agents will add paddings and margins to the body element, thus preventing the image container to slide all the way to the right. Reset those, to get rid of the gaps between the container and the edge of the browser window.
body {
margin: 0;
padding: 0;
}
As for the image itself, position it absolutely.
img {
position: absolute;
}
And finally javascript. To center the image, you need to calculate what this width/height=auto sums up to, and then reset left/top attributes respectively. Your if function needs to be adjusted just a bit; leave your variables as is:
if (height_ratio > width_ratio) {
var newWidth, newHeight, newTop;
newWidth = area_width;
newHeight = image_height/width_ratio;
newTop = -(newHeight-area_height)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = newTop;
document.images[0].style.left = 0;
}else{
var newWidth, newHeight, newLeft;
newHeight = area_height;
newWidth = image_width/height_ratio;
newLeft = -(width-area_width)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = 0;
document.images[0].style.left = newLeft;
}
I hope that if this doesn't solve the issue completely, it at least sends you in the right direction. Good luck.
I'm not sure if this will work exactly, but may get your started. I had a client request a radial gradient be fixed to the left and right of a website's main ontent section. The page was set up with dynamic widths and I had a heck of a time getting one solid image to work, so I came up with a quick css solution.
#bgHold #gradLeft{
width:248px;
height:975px;
position:fixed;
right:50%;
margin-right:399px;
background:url("../images/gradLeft.png") top center no-repeat;
}
margin-right is half of the content block's width. So basically, the gradient is fixed on the page at 50% from the right, then shoved left 50% of the content box making it line up with the edge of the content. The same idea applies to the other side.
Now, with your situation, perhaps you can set right:50%; and margin-right:imgWidth/2?
I need to render profile images in a grid of exactly 101x155 each.
Some images are too small, some too big, most are not the right aspect ratio.
How do I show the img with a minimum width and height, no distortion, and show the exact size I want?
Without actually modifying the images, you have a few options available to you.
img { max-width: 101px max-height: 155px }
this will make sure that the images don't go above the 101x155px wide. Because they aren't the perfect aspect ratio there still will be whitespace on the sides of the image if the aspect ratio isn't perfect.
Another way would be to encase them in a container
<div><img .../></div>
div {width: 101px; height: 155px; overflow: hidden}
img {width: 101px;} /*or do height: 155px)*/
This isn't perfect but it gives you a different result. This will require the images to be either taller or wider for all images.
The best way would be to resize, but I know we can't always have our way :)
How about some jQuery? If you just include the <img> with class="grid-img":
$(".grid-img").each(function(i){
var width = $(this).width();
var height = $(this).height();
var ar = height/width;
if(width > 101) {
var newWidth = 101;
var newHeight = 101 * ar;
} else {
var newHeight = 155;
var newWidth = ar / newHeight;
}
$(this).height(newHeight);
$(this).width(newWidth);
});
what this should do is: if the image's width is too big, resize it based on the width (maintaining aspect ratio). if not, resize it based on height (again maintaining AR).