Obtaining half the width of an image using Javascript - javascript

I am trying to calculate half of the width of an object using Javascript.
var img = document.getElementById('picture1');
var width = img.clientWidth;
var halfwidth = width/2;
I then need to plug that variable into a jquery css modifier for margin-left. This will be used to position the image in the exact center of the page.
$('#div').css('margin-left','-400px');
but instead of -400px, I need to have the variable in there somehow. Can this be accomplished?

I think this will work for you:
$('#div').css('margin-left','-' + ($('#picture1').width()/2) + 'px');

Keeping it simple
$('#div').css('margin-left','-'+(parseInt($('#picture1').width())/2)+'px');

Here is how you can position the image in the center of the page http://jsfiddle.net/JkZdH/
var img = $('#myImg'),
docWidth = $(document.body).width(),
imgWidth = img.outerWidth(true),
marginLeft = (docWidth - imgWidth) / 2;
img.css('margin-left', marginLeft);
For html:
<img src="sample_image.png" alt="dog" id="myImg" />

$('#div').css({marginLeft : $('#picture1').width()/2});

Related

How to use javascript/css to force a website page zoom level to fixed value?

I need html/css/javascript to fix everyone's zoom level on a website page.
Does anyone have an idea on the javascript?
The only way I found that works natively is in designing my HTML/CSS with the units "vw" and "vh" (% relative to the viewport) instead of "px". You can use it everywhere you used to put "px" (font-size, width, height, padding, margin, etc...). Very useful for a page designed to be display full screen only (no scroll) or "Kiosk-style". "vw" and "vh" are not affected by browser zoom. See: https://www.w3schools.com/cssref/css_units.asp
You can use the document.onLoad to change the scale in CSS through Javascript:
var minimum_width = 840; // Put you own value here
var desired_width = 1440; // and here
var actual_width = document.all ? document.body.clientWidth : window.innerWidth;
var actual_height = document.all ? document.body.clientHeight : window.innerHeight;
if (desired_width > actual_width) {
desired_width = actual_width;
}
if (desired_width < minimum_width) {
desired_width = minimum_width;
}
var scale = Math.round(actual_width/desired_width*100)/100;
var desired_height = Math.round(actual_height/scale);
var body = document.body;
body.style.transform = "scale(" + scale + ")";
body.style.width = desired_width + "px";
body.style.minHeight = (desired_height) + "px";
Will work on most popular browsers.

javascript, get size of a background scaled with contain property

I've seen a few posts here trying to answer this question and I tried using the codes given as answers but haven't been able to get it to work, so I must be doing something wrong. Basically I have a div with a background-image with the CSS property "background-size: contain". I want to get the dimensions of the scaled background. Here is my code, mostly copied from another post here, with some things changed to match my div's names:
var elem = document.querySelector("#enlarged-inner .image-bg");
function getBackgroundSize(elem) {
elem = document.querySelector("#enlarged-inner .image-bg");
//get original background size
var computedStyle = getComputedStyle(elem);
var img = new Image;
img.src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2');
var imgW = parseInt(img.width, 10);
var imgH = parseInt(img.height, 10);
//get scaled size
var newW = parseInt(computedStyle.width, 10);
var newH = parseInt(computedStyle.height, 10);
var scaledW = 0;
var scaledH = 0;
scaledW = imgW / imgH * newH;
scaledH = imgH / imgW * newW;
}
window.onresize = function(){ getBackgroundSize(elem); }
Its able to get the original (unscaled) size of the background image just fine, so I atleast know that the first half of the code is working. But the second part, the important part, doesn't seem to do anything. I've been testing it by changing a test divs innerHTML to the new variables:
document.getElementById("test").innerHTML = newW + " , " + newH;
I'm new to javascript and not great at math so I'm sure theres probably something I'm just not understanding correctly here.
EDIT: the code above has been updated a little and heres some more explanation.
So in this picture the blue box is a scalable div that contains the div with the background. Its height and width are set with vh and vw.
The gray box represents the background image itself, with its size set to contain. In the updated code above, newW and newH give me the dimensions of the blue box, no matter how its scaled. imgW and imgH give me the original unscaled dimensions of the background. I want scaledW and scaledH to return the scaled size of the gray box, but my math doesnt seem to work out.
I can't test it right now but I think that the variables you're modifying (newW and newH) are passed by value. So, you actually don't update your image's size. You'll probably need to use these variables to update your image's size, maybe with:
img.width = newW etc
I figured out a simpler way to achieve what I wanted. Basically what I was trying to do was have a div with an image in it, that I could scale to any size, and the entire image would always fit inside the div (similar to the background-size contain property), and the images would always maintain their original aspect ratio. In my particular case instead of a div, its the size of the full window, and I found it to be easier to work with images in img tags instead of backgrounds. Heres the code:
function getBackgroundSize(elem) {
elem = document.querySelector("#enlarged-inner img");
var imgW = elem.naturalWidth;
var imgH = elem.naturalHeight;
var newW = window.innerWidth;
var newH = window.innerHeight;
var imgRatio = imgW / imgH;
var newRatio = newW / newH;
var scaledW = 0;
var scaledH = 0;
if (imgRatio > newRatio) {
scaledW = newW;
scaledH = imgH * newW / imgW; }
else {
scaledW = imgW * newH / imgH;
scaledH = newH; }
document.querySelector("#enlarged-inner img").style.width = scaledW;
document.querySelector("#enlarged-inner img").style.height = scaledH;
}
I basically just found the unscaled height and width of the image, and the dimensions of the containing div (the window in my case), and then found their ratios of width over height. I'm not so good at math but atleast in the examples I tried to work out, if the W/H of the image was larger than W/H of the window, it would mean the image's width would be defined by the width of the window. And then the correct height of the image could be found with some simple math.

offsetHeight and offsetWidth calculating incorrectly on first onclick event, not second

I have written the following script to display a hidden element, then fix it's position to the center of the page.
function popUp(id,type) {
var popUpBox = document.getElementById(id);
popUpBox.style.position = "fixed";
popUpBox.style.display = "block";
popUpBox.style.zIndex = "6";
popUpBox.style.top = "50%";
popUpBox.style.left = "50%";
var height = popUpBox.offsetHeight;
var width = popUpBox.offsetWidth;
var marginTop = (height / 2) * -1;
var marginLeft = (width / 2) * -1;
popUpBox.style.marginTop = marginTop + "px";
popUpBox.style.marginLeft = marginLeft + "px";
}
When this function is called by an onclick event, the offsetHeight and offsetWidth are calculated incorrectly, thus not centering the element correctly. If I click the onclick element a second time, the offsetHeight and offsetWidth calculate correctly.
I have tried changing the order in every way I can imagine, and this is driving me crazy! Any help is very much appreciated!
I am guessing your height and width are not defined on the parent. See this fiddle where it works fine. Boy I'm smart. http://jsfiddle.net/mrtsherman/SdTEf/1/
Old Answer
I think this can be done a lot more simply. You are setting the top and left properties to 50%. This will place the fixed element slight off from the center. I think you are then trying to pull it back into the correct position using negative margins. Instead - just calculate the correct top/left values from the start and don't worry about margin. Here is a jQuery solution, but it can be easily adapted to plain js. I also think your current code won't work if the window has been scrolled at all.
//this code will center the following element on the screen
$('#elementid').click(function() {
$(this).css('position','fixed');
$(this).css('top', (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop() + 'px');
$(this).css('left', (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft() + 'px');
});

Is it possible to measure the resulting background image when using background-size: cover with Javascript?

I want to know if it's possible to determine the (new) dimensions of a background image after it has been resized with css3's 'background-size: cover' using Javascript.
(Not working) Example: http://jsfiddle.net/daco/GygLJ/3/
Cheers,
Daco
I don't know enough pure JS to post this without assuming jQuery but it can probably be ported easily.
What you could do is find the src of the background image, then use javascript's built in width / height functions to get its dimensions.
eg:
//jQuery
var imgSrc = $('#test').css('background-image');
//might need to do a bit of parsing on that, returns: url(http://blahblah)
alert(imgSrc);
imgSrc=imgSrc.replace('url("', '').replace('")', '');
alert(imgSrc);
var newImg = new Image();
newImg.onload=function()
{
var h = newImg.height;
var w = newImg.width;
alert('w:'+w+' h:'+h);
};
newImg.src=imgSrc;
Hope this helps
Example here: http://jsfiddle.net/vap8p/
EDIT: updated source and linked to working example
Assuming background-image css for element with ID 'mydiv'. All native JavaScript. Won't interact with other JavaScript on page.
(function (id) {
var img = new Image(), elm = document.getElementById(id);
img.dataset.w = elm.offsetWidth;
img.dataset.h = elm.offsetHeight;
img.addEventListener('load', function () {
var maxw = this.dataset.w,
maxh = this.dataset.h,
aspect = this.width / this.height;
if(maxw > maxh * aspect) alert(maxw + ' x ' + maxw / aspect);
else alert(maxh * aspect + ' x ' + maxh);
}, false);
img.src = window.getComputedStyle(elm).backgroundImage.slice(4, -1);
})('mydiv');​
You might want to round down.
For contain rather than cover, change the compare to the opposite.
if(maxw < maxh * aspect) alert(maxw + ' x ' + maxw / aspect);

Resize and Center image with jQuery

Looks like I haven’t explained myself well. I do apologize for that.
I have edited this question to make it more clear.
The scenario
We have a website that doesn’t host the images. What it does is a reference to an image in other server.
The plan
Resize images keeping proportions.
Center resized images.
Flexible so it can fit in several sizes.
The bug
My code works as intended, however there is a Bug that only happens sometimes.
If you go to the search page of the website, and swap between page 1, 2, 3 and 4 a couple of times, you will notice that sometimes the images are good… other times they appear aligned left, and do not take up the full container area.
The links
The full website (in beta)
The JavaScript File
The jQuery plugin that helped me (jThumb)
The plan (detailed version)
Let’s say that the image is 600x400 pixels (remember they are not hosted on this server), and with jQuery and CSS, I want to resize the image (keeping proportions) in to a container of 310x200 pixels.
The other challenge is to center the image.
All this has to be flexible because there are several different containers sizes in the website.
What I have done so far (you can find this in the link above)
To resize the image I'm doing:
var img = new Image();
img.src = $(this).attr("src");
var width = $(this).css('width');
var height = $(this).css('height');
var photoAspectRatio = img.width / img.height;
var canvasAspectRatio = width.replace("px", "") / height.replace("px", "");
if (photoAspectRatio < canvasAspectRatio) {
$(this).css('width', width);
$(this).css('height', 'auto');
var intHeight = height.replace("px", ""); //tirar o PX
$(this).css('marginTop', (-Math.floor(intHeight / 2)));
}
else {
$(this).css('width', 'auto');
$(this).css('height', height);
}
$(this).wrap('<div class="thumb-img" style="width:' + width + ' ;height:' + height + ';"><div class="thumb-inner">' + '</div></div>');
To center the image I’m doing:
jQuery(this).css('position','absolute');
jQuery(this).left( '-' + ( parseInt( $(this).width() ) / 2 ) + 'px' );
jQuery(this).top( '-' + ( parseInt( $(this).height() ) / 2 ) + 'px' );
jQuery(this).css('margin-left', '50%' );
jQuery(this).css('margin-top', '50%');
There's a far simpler solution to determine how to resize and position the image. It will work with all image and container sizes.
var canvasWidth = parseInt(width);
var canvasHeight = parseInt(height);
var minRatio = Math.min(canvasWidth / img.width, canvasHeight / img.height);
var newImgWidth = minRatio * img.width;
var newImgHeight = minRatio * img.height;
var newImgX = (canvasWidth - newImgWidth) / 2;
var newImgY = (canvasHeight - newImgHeight) / 2;
Now just position the image using newImgX, newImgY, and resize it to newImgWidth, newImageHeight.
This is probably a race condition. You are setting the img src and then immediately trying to get its width and height attributes. But there is no guarantee that the web browser has downloaded the image or pulled it from the browser cache yet, and if it hasn't, your code will lead to unexpected results.
You need to do something like this:
var img = new Image();
var $thumb = $(this);
img.load(function() {
/* .....[image calculation and resize logic]..... */
});
img.src = $thumb.attr("src");
Note that the order of the above statements is very important -- you must attach the img.load event handler first, then assign the img.src second. If you do it in the other order, you will end up with an opposite race condition (the image may already be loaded after the img.src assignment, in which case the event handler will not be called in all browsers -- by setting the event handler first you ensure that it will be called after the img.src assignment even if the image is already loaded).
Also, note the $thumb definition at the top. This is because "this", inside the img.load function, will be a reference to the new "img", not the thumbnail element. So your logic will have to reference "$thumb" for the DOM element and "this" (or "img") for the in-memory image.
Also, for the actual logic take a look at the answer "Scott S" provided above. His suggestion looks simpler than what you have.
It's not clear from your question, but I'm assuming one your issues is the left-align of the images in the table at the bottom half of your front page at http://www.algarvehouses.com.
The issue here is not your jQuery code, rather it is your CSS.
add a text-align: center to your thumb-inner class. Then make sure that rule is loaded AFTER the "table.dlRandom img, ..." rule - or remove the display:block from that rule. That should center those images.
Generally though - to scale the image, your logic looks correct up to the point of the div. Don't quite understand that logic. You don't need to set the auto size though, just restrain the dimension that is required.
One tangential tip - in the code above you reference $(this) no less than 16 times. Do this at the top of the function, and use it from there on:
var $this = $(this);
I really didn't get your question but this maybe be help you.
function resizer(imgCls, maxWidth, maxHeight) {
var img = $('img'), imgWidth, imgHeight;
img.each(function () {
imgWidth = this.width;
imgHeight = this.height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
var widthFact = maxWidth / imgWidth;
var heightFact = maxHeight / imgHeight;
var chooseFact = (widthFact > heightFact) ? heightFact : widthFact;
imgWidth = imgWidth * chooseFact;
imgHeight = imgHeight * chooseFact;
}
})
}
this code gets the images matches the provided className and looks your arguments. pass maxWidth to your maxWidth value such as 300 px, and pass maxHeight to your images maxHeight such as 300.
then the function will loop for every image and checks its width and height. If its width or height is larger than your max values then it will be resized by keeping the aspect ratio.
Please let you free to ask more question about the issue and please be more clear.
This script will shrinks, and align image depending of their orientation. Image is rounded with div ho has fixed width and hight, and also a style set to overflow:hidden. The script actual recognize the image orientation and ad to image a margin-left or margin-top in minus atribute to style depending of a image vertical or horizontal orientation.
CSS:
<style type="text/css">
.thumb {
width:160px;
height:160px;
overflow:hidden;
}
</style>
jquery with javascript:
window.onload = function() {
var images = $(".image_center");
for(i=0; i<images.length; i++)
images[i].onload = centerImage(images[i]);
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
img.style.height = y+"px";
img.style.marginLeft = -(marx) + "px";
}
if (img.width < img.height ) {
var x = 160;
var y = img.height/img.width*x;
var mary = (y-x)/2;
img.style.width = x+"px";
img.style.marginTop = -(mary) + "px";
}
}
}
HTML:
<div class="thumb"><img class="image_center" src="sa.jpg" alt="#" /></div>
<div class="thumb"><img class="image_center" src="sb.jpg" alt="#" /></div>
You can see demo here: Link
Another useful plugin which achieves this is jQuery Center Image which supports two modes. One to fill the entire space by cropping and resizing the image and another which emulates max-width/max-height to resize to fit within the space.

Categories