This code when run should resize the height and width that a image to fit the container.
This is the output from the code(from alerts):
2488: Images natural height
3264: Images natural width
450: The containers height
1063: The containers width
612: New height
844: New width
4: The number of times it was divided to get to output
**It should divide it 6 times to provide the outcome of:
New width: 544
New height: 414
**
I am almost certain that the problem is in the Java Script:
function resize(iid, eid) {
//Get the ID of the elements (ele being the container that the image is in and img being the image its self)
var img = document.getElementById('img');
var ele = document.getElementById('contaner');
//makes the var needed
var currentwidth = ele.clientWidth;
var currentheight = ele.clientHeight;
var naturalheight = img.naturalHeight;
var naturalwidth = img.naturalWidth;
var newheight = naturalheight;
var newwidth = naturalwidth;
var x = 0;
//runs a loop that should size the image
while (newheight > currentheight && newwidth > currentwidth){
x = x + 1;
newheight = naturalheight / x;
newwidth = naturalwidth / x;
}
newheight = Math.ceil(newheight);
newwidth = Math.ceil(newwidth);
//alerts out the answers
alert(naturalheight);
alert(naturalwidth);
alert(currentheight);
alert(currentwidth);
alert(newheight);
alert(newwidth);
alert(x);
}
#contaner {
height: 450px;
width: 90%;
margin: 5% auto;
position: relative;
}
#img {
height: 450px;
width: 90%;
}
<div id="contaner">
<img src = "..\..\Resorces\Images\SlideShow\img1.jpg" style="width:652px;height:489px;" id="img"/>
<div id="left_holder"><img onClick="slide(-1)" src="..\..\Resorces\Images\arrow_left.png" class="left"/></div>
<div id="right_holder"><img onClick="slide(+1)" src="..\..\Resorces\Images\arrow_right.png" class="right"/></div>
</div>
The problem is this line:
while (newheight > currentheight && newwidth > currentwidth)
It's stopping as soon as either width or height fits within the container, where as it seems like you want both to fit within the bounds of the container. Change to || and you'll get six iterations:
while (newheight > currentheight || newwidth > currentwidth)
Related
is there an easy way to get the final height and width of a background image with Javascript or jQuery even if a background-size property was applied?
I mean, I know I can get the background image url and load it to an Image object and then get the width and height. But it is the size of the source image. If someone scaled it with CSS then the size changed
How can I find its final size?
#edit
it is different from the question marked as similar because it doesnt say how to get the size in pixels if someone changed the background-size
Using getComputedStyle, I've created this script that returns the width and height of a given element's background, in pixels. It works with:
Dimensions (width or height) set to auto, either explicitly or because no specific value was given (width and height default to auto)
Dimensions set to percentage %
Dimensions set to pixels px
Dimensions set to a combination of any of the previous. (i.e width: 100px; height: auto or width: auto; height: 32.4% or height: 100px; width: 2% or width: 21.2%)
background-size set to cover or contain
It works if background-size is set with an external CSS file, inline CSS, inline header CSS or if it is not set at all (meaning width and height are auto).
Here's a JsFiddle (with cover example)
http://jsfiddle.net/gp4e9d3z/3/
And here's StackOverflow's code snippet (with percentage auto units)
function getBackgroundSize(elem) {
// This:
// * Gets elem computed styles:
// - CSS background-size
// - element's width and height
// * Extracts background URL
var computedStyle = getComputedStyle(elem),
image = new Image(),
src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2'),
cssSize = computedStyle.backgroundSize,
elemW = parseInt(computedStyle.width.replace('px', ''), 10),
elemH = parseInt(computedStyle.height.replace('px', ''), 10),
elemDim = [elemW, elemH],
computedDim = [],
ratio;
// Load the image with the extracted URL.
// Should be in cache already.
image.src = src;
// Determine the 'ratio'
ratio = image.width > image.height ? image.width / image.height : image.height / image.width;
// Split background-size properties into array
cssSize = cssSize.split(' ');
// First property is width. It is always set to something.
computedDim[0] = cssSize[0];
// If height not set, set it to auto
computedDim[1] = cssSize.length > 1 ? cssSize[1] : 'auto';
if(cssSize[0] === 'cover') {
// Width is greater than height
if(elemDim[0] > elemDim[1]) {
// Elem's ratio greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else if(cssSize[0] === 'contain') {
// Width is less than height
if(elemDim[0] < elemDim[1]) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
// elem's ratio is greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
} else {
computedDim[1] = 'auto';
computedDim[0] = elemDim[0];
}
}
} else {
// If not 'cover' or 'contain', loop through the values
for(var i = cssSize.length; i--;) {
// Check if values are in pixels or in percentage
if (cssSize[i].indexOf('px') > -1) {
// If in pixels, just remove the 'px' to get the value
computedDim[i] = cssSize[i].replace('px', '');
} else if (cssSize[i].indexOf('%') > -1) {
// If percentage, get percentage of elem's dimension
// and assign it to the computed dimension
computedDim[i] = elemDim[i] * (cssSize[i].replace('%', '') / 100);
}
}
}
// If both values are set to auto, return image's
// original width and height
if(computedDim[0] === 'auto' && computedDim[1] === 'auto') {
computedDim[0] = image.width;
computedDim[1] = image.height;
} else {
// Depending on whether width or height is auto,
// calculate the value in pixels of auto.
// ratio in here is just getting proportions.
ratio = computedDim[0] === 'auto' ? image.height / computedDim[1] : image.width / computedDim[0];
computedDim[0] = computedDim[0] === 'auto' ? image.width / ratio : computedDim[0];
computedDim[1] = computedDim[1] === 'auto' ? image.height / ratio : computedDim[1];
}
// Finally, return an object with the width and height of the
// background image.
return {
width: computedDim[0],
height: computedDim[1]
};
}
// Stuff for debugging
function updateData() {
var background = getBackgroundSize(document.body);
document.getElementById('width').innerHTML = background.width + 'px';
document.getElementById('height').innerHTML = background.height + 'px';
document.getElementById('winWidth').innerHTML = getComputedStyle(document.body).width;
document.getElementById('winHeight').innerHTML = getComputedStyle(document.body).height;
}
// Execute onload, so that the background image is already loaded.
window.onload = window.onresize = updateData;
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
background: url('http://hdwallpapersfit.com/wp-content/uploads/2015/03/images-7.jpg');
background-size: 80% auto;
}
div {
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
<div id="data">
Background width: <span id="width"></span>
<br>
Background height: <span id="height"></span>
<hr>
Body width: <span id="winWidth"></span>
<br>
Body height: <span id="winHeight"></span>
</div>
Using the JSFiddle Here, I found that changing the height or width of the container forces the image to be scaled to the largest height or width. Meaning that the measurement of one edge of the background will be equal to one of the dimension of the container. Using this and some proportions we can calculate the dimensions of the image.
// let .container represent element containing the image
var image; // the image object to the background image
var dim_h, dim_w; // the height and width of the actual image
height = $(".container").height();
width = $(".container").width();
if (height >= width)
{
dim_h = height;
dim_w = (height / image.height) * image.width;
}
else
{
dim_w = width;
dim_h = (width / image.width) * image.height;
}
// dim_w and dim_h contain the width and height of the actual
// background image after scaling
The above code uses the proportion below to calculate it.
(element_height / image_height) == (element_width / image_width)
I think it should give you the answer you want.
What is the css height of the image if the width is for example: 3px?
original image height is 400px;
original image width is 800px;
what I've tried is:
convert the 3px to a percentage of the original image width:
function perwVal(v){
return 100 * v / iow; //img orig width
}
function perhVal(v){
return v / 100 * ioh; // img original height
}
var imgwidthPerc = perwVal(3);
var imgheightPerc = perhVal(imgwidthPerc);
// not correct the height is off
any help will be appreciated.
You get the ratio of the width vs. height:
const ratio = originalWidth / originalHeight;
and then to find the width for a different height:
const newWidth = newHeight * ratio;
In your example:
const originalHeight = 800;
const originalWidth = 400;
const ratio = originalWidth / originalHeight;
const newHeight = 3;
const newWidth = newHeight * ratio;
console.log(newWidth);
But note Sebastian's point that you may not need it, you may be able to use CSS's aspect-ratio.
I am looking for simple solution to always keep aspect ratio of a video but also to always fit the video inside the browser window for both the width and the height.
So far all the solutions I have found have been fitting only by width, but I need also to fit height. :}
Bootstrap does this. The trick is that CSS padding bottom is computed based on the width of the element.
.video-container {
position: relative;
overflow: hidden;
height: 0;
padding-bottom: 56.25%; /* calculate by aspect ratio (h / w * 100%) */
}
.video-container .video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="video-container">
<video class="video"></video>
</div>
See this example. It works with <embed>, <object>, <iframe>, and <video> tags. My example is just a colored <div> that keeps its' aspect ratio constant.
I wrote this for images originally for another question on SO, but it should work for just about any element. Just change the first variable to match your video element. You can also drop the for loop if you are only resizing a single element.
JS:
function resize() {
var img = document.getElementsByTagName('img');
var w = window.innerWidth;
var h = window.innerHeight;
//console.log(w);
//console.log(h);
for (i = 0; i < img.length; i++) {
var ratio = (img[i].clientHeight / img[i].clientWidth);
if (img[i].clientHeight > h && img[i].clientWidth < w) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientHeight <= h && img[i].clientWidth < w && ratio > 1) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientWidth >= w) {
img[i].style.width = w + "px";
}
if (img[i].clientHeight < h && img[i].clientWidth <= w && ratio < 1) {
img[i].style.width = w + "px";
}
}
}
resize();
window.onresize = resize;
JSFiddle: https://jsfiddle.net/hopkins_matt/k7t26sw5/
You could try the CSS only route. YouTube had the solution I was looking for which was keeping width, and height in a 16:9 ratio.
video {
width: 100%;
min-height: 480px;
height: calc((9 / 16) * 100vw);
max-height: calc(100vh - 169px);
}
With HTML5, the aspect of the video will mold to the parent no matter the video's ratio.
Try with Javascript...
function updateHeight()
{
var videoHeight = 9 * videoDom.offsetWidth / 16;
videoDom.style.height = vidoeHeight + "px";
}
window.onload = function()
{
updateHeight();
}
window.onresize = function()
{
updateHeight();
}
Assuming your video has 16:9 aspect ratio.
I am getting NaN back from one of my functions. After doing the research I found out the answer was not a number but I figured that it must be imposable. I am only working with numbers and I am rounding the answer.
function resize(iid, eid) {
//Get the ID of the elements (ele being the container that the image is in and img being the image its self)
var img = document.getElementById('img');
var ele = document.getElementById('contaner');
//makes the var needed
var currentwidth = ele.clientWidth;
var currentheight = ele.clientHeight;
var naturalwidth = img.naturalHeight;
var naturalheight = img.naturalWidth;
var newheight = naturalheight;
var newwidth = naturalwidth;
var x;
//runs a loop that should size the image
while (newheight > currentheight && newwidth > currentwidth){
x = x + 1;
newheight = naturalheight / x;
newwidth = naturalwidth / x;
}
newheight = Math.round(newheight);
newwidth = Math.round(newwidth);
//alerts out the answers
alert(newheight);
alert(newwidth)
}
#contaner {
height: 450px;
width: 90%;
margin: 5% auto;
position: relative;
}
#img {
height: 450px;
width: 90%;
}
<div id="contaner">
<img src = "..\..\Resorces\Images\SlideShow\img1.jpg" style="width:652px;height:489px;" id="img"/>
<div id="left_holder"><img onClick="slide(-1)" src="..\..\Resorces\Images\arrow_left.png" class="left"/></div>
<div id="right_holder"><img onClick="slide(+1)" src="..\..\Resorces\Images\arrow_right.png" class="right"/></div>
</div>
You have:
var x;
And then when you do:
x = x + 1;
x is undefined it get cast to string and then concatenated with the 1. So:
x = 'undefined1';
When x is used on a division it returns NaN.
Solution: Change x declaration:
var x = 0;
NaN is due by this line of code:
var x;
while (newheight > currentheight && newwidth > currentwidth) {
x = x + 1; //<- Here x is undefined
}
I am looking at this site here:
platetheslate
I found it from another users question on here but I have one of my own.
How do they make the header image FULL HEIGHT? I know you can get a full width/height with even CSS "cover" element but thats not what I am getting at.
How did they set it, so no matter what size your display/window it takes up the full screen (height wise), no matter what you always just see the photo UNTIL you scroll down.
Thanks in advance!
This should scale the width in proportion with the height.
#id {
position: relative;
height: 100%;
width: auto;
}
in the header's css class, do height: 100%
Note their Javascript is unminified here: http://www.platetheslate.com/wp-content/themes/twentyeleven/js/jquery.main.js
Here is the method that sets the height and width of the image:
//initHImage
function initHImage() {
var minWidth = 1100;
var holder = jQuery('#h-image');
var image = holder.find('img');
var win = jQuery(window);
var ratio = image.width() / image.height()
image.removeAttr('height width');
holder.css({
overflow: 'hidden',
position: 'relative'
});
function setSize() {
var winW = win.width();
var winH = win.height();
var W = Math.max(winW, minWidth);
var winRatio = W / winH;
holder.css({
width: W,
height: winH
});
if(winRatio > ratio) {
image.css({
width: W,
height: W / ratio,
marginTop: Math.min((W - W / ratio) / 2, 0),
marginLeft: 0
});
}
else {
image.css({
width: winH * ratio,
height: winH,
marginTop:0,
marginLeft: Math.min((W - winH * ratio) / 2, 0)
});
}
}
setSize();
win.bind('resize orientationchange', setSize);
}