How to resize of a image base on screen size - javascript

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.

Related

I need to position image at the bottom of the background image and have them stay in place when window is resized

I have a background image and I have other images that need to stay at the bottom of the background image, even if the window resizes or there is a different screen size.
This is a ReactJS web app so any javascript or CSS will work.
CSS:
html {
background: url(imageInMemory.png) no-repeat center center fixed;
background-size: contain;
}
Javascript:
// I calculate the ratio for 'background-size: contain'
let A = window.innerWidth;
let B = window.innerHeight;
let W = naturalWidth; // Width of image, I have this hardcoded
let H = naturalHeight; // Height of image, I have this hardcoded
const ratio = Math.min((A/W), (B/H));// this is the ratio to which the image was scaled given the current window size.
// I position images on top of background images where they should be using this new ratio
<div style={{marginTop: ratio * H * .7}}>
<img src='otherImage'/>
</div>
This works on some window sizes, but sometimes the images will not be on top of the right area of the background Image.
I did a responsive layout for one image behind and a floating form resizing and repositioning all fields and texts.
I will not put all my code here, then i said to you create your own code inside a function named like "update_field_positions" running in events window resize and load.
For screens with more than 608px the height of my image is 882px
Then i define the reason of proportion: img_cadastro.clientHeight / 882
And use this value for resize and reposition all the items
I used css too:
#media screen and (max-width:608px) {
.img_cadastro {
width:100%;
height:auto;
}
and
#media screen and (min-width:608px) {
.img_cadastro {
width:608px;
height:882px;
}
A little piece of my working js code:
function update_field_positions() {
.... (some code) ....
var razao = img_cadastro.clientHeight / 882;
bloco_campos_ext.style.top = ((258 * razao) + compensador) + "px";
div_voucher.style.marginTop = ((57 * razao) + compensador_voucher) + "px";
div_voucher.style.marginLeft = ((120 * razao) + compensador) + "px";
nome_voucher.style.fontSize = (24 * razao) + "px";
cod_voucher.style.fontSize = (28 * razao) + "px";
resize_object(bloco_campos_ext, 357, 148, razao, false);
resize_object(bloco_campos_int, 357, 148, razao, false);
}
Use this css to your div:
position:fixed;
bottom:0;
For a responsive screen working when the windows is resized
Your codes of getting ratio and repositioning should be inside a function, you could create a function named update_field_positions for example: update_field_positions()
then your function must be called in 2 events, onload and window.resize
example:
function start() {
update_field_positions();
window.onresize = update_field_positions;
}
<body onLoad="start()">
Tou should use onload, for wait objects become ready before working with them to avoid errors and window.onresize to update values with a new window.innerWidth
The other problem is that the window can be resized to a smaller size than your image
And then you have to create some code to handle these situations:
if (window.innerWidth < naturalWidth) {...}

Retrieve size of background image after scaling with jQuery?

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.

How do I get dynamically fluid images depending on browser window aspect ratio?

This might not be a simple question, but I try my best.
I have this example site: http://lotvonen.tumblr.com/
I have a little piece of javascript that automatically calculates the height of the inner browser window and sets that number as image wrapper div's height. Height of the image inside the wrapper is 100% of the wrapper, so that I get nice, full screen images on all normal screen sizes.
This works wonderfully on screens that are more wide than tall (desktops, laptops, etc).
But!
With screens that are more tall than wide (smartphones, iPads etc), the images get clipped from sides. I don't want that, so I have a temporary solution to have media query assigning height to auto and width to 100%, when browser screen max-width is 1024, so that no clipping occurs. But it's not a very good solution, and breaks at certain resolutions. It also destroys my JS with lower resolutions (eg. 800x600).
Here's the JS:
<script type="text/javascript">
var elems = document.getElementsByClassName('img'),
size = elems.length;
for (var i = 0; i < size; i++) {
var img = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
img.style.height=(height)+'px';
}
</script>
and here's my CSS:
.img {
max-width:100%
}
.img img {
width:auto;
}
.img img {
height:100%;
}
#media only screen and (max-width: 1024px) {
.img {
height:auto !important;
}
.img img {
height:auto !important;
max-width:100%;
}
and here's the div:
<li><div class="img"><img src="{PhotoURL-HighRes}" alt="{PhotoAlt}"/></div>
How do I get it so, that when the browser window is more tall than wide (eg. 720x1024), the images adjust by width, and when the browser window is more wide than tall (eg. 1024x720) the images adjust like they do now (by height, with the JS).
Is this possible at all? Is there a simple CSS fix to this or do I need to mess more with JS?
Thanks in advance!
You could also get the aspect in javascript on a regular basis and then add a class to the body object that would specify if it was 4:3, widescreen, or portrait. Then make it run on an interval in case the window changes size.
Example
CSS
.43 img { width: auto; }
.widescreen img { width: 100%; }
.portrait img { height: 100%; }
JavaScript
var getAspect = function(){
var h = window.innerHeight;
var w = window.innerWidth;
var aspect = w / h;
var 43 = 4 / 3;
var cssClass = "";
if (aspect > 43) {
cssClass = "widescreen";
}
else if (aspect === 43) {
cssClass = "43";
}
else {
cssClass = "portrait";
}
$("body").addClass(cssClass); // Using jQuery here, but it can be done without it
};
var checkAspect = setInterval(getAspect, 2000);
I would suggest getting the aspect ratio first in javascript. Use window.innerHeight and windows.innerWidth, and make the necessary division. Then, make this a condition. When the screen in wider than its height, set the image in css to width: 100%. Otherwise, set height: 100%.

Render images at a standard size without stretching, with a minimum size

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

Why are these Images bigger then original size?

I have multiple images that I pull from facebook. They are placed in a scroller. When you click on the image a dialog appears with the actual image (The images in the scroller are thumbnail size, what you get from a facebook query with src_small)
I cannot determine the size of the images before I get them. Some are huge and others very small. To account for this (so all images fit in the dialog and are a reasonable size) I tried this:
/*
* Image in the dialog div
*/
.DialogImagesBig
{
position: relative;
width: 95%;
top: 0px;
left: 10px;
}
/*
* Firefox only
*/
#-moz-document url-prefix()
{
/*
* Edits images for FF
*/
.DialogImagesBig
{
height: 95% !important;
width: 95% !important;
position: relative;
top: 0px;
left: 10px;
}
}
But it actually makes some images bigger then they are (Big images are smaller, but small images are bigger and pixelated). Why is that? How would I fix this so that all images fit in the dialog and are not pixelated?
Edit I have been told that I need to use Javascript (or Jquery?) to get this done. How would I go about doing that?
A width/height of 95% means 95% of the parent element's width/height, not 95% of the image's original size.
You can get the image width/height by doing this:
var img = new Image();
img.src = _image_src_
img.width // returns width
img.height // returns height
img // returns <img src="_image_src_" />
You can compare those values with the width/height of your dialog and do all the resizing you need, i hope this can help.
Example:
if (img.width > 100)
img.width = 100
$("#image_container").html(img)
You could try this sort of thing:
h = $('#theimage').height();
w = $('#theimage').width();
if(h > 400 && w < 500) {
$('#theimage').height(400);
$('#theimage').width = w / (h / 400);
}
...
...
same for other comparisons, to shrink it down appropriately. I think the math is right there...

Categories

Resources