Real image width with JavaScript - javascript

I have the next function:
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
}
}
I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.
images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?

Here is, hopefully, enough sample code to give you what you want:
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)
EDIT: Here, I couldn't help myself - is this what you are after?
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width + "px");
}
}
}

#Sergio del Amo: Indeed, if you check out my link you'll see that you want clientWidth instead.
#Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the clientWidth change:
// width in pixels
function setImagesWidth(id, width)
{
var images = document.getElementById(id).getElementsByTagName("img");
var newWidth = width + "px";
for (var i = 0; i < images.length; ++i)
{
if (images[i].clientWidth > width)
{
images[i].style.width = newWidth;
}
}
}

Careful, it looks like you might rather want clientWidth:
http://developer.mozilla.org/en/Determining_the_dimensions_of_elements

EDIT: Can i accept somehow this answer as the final one?
Since offsetWidth does not return any unit, the .px ending must be concatenated for the css attribute.
// width in pixels
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width+".px");
}
}
}

Just in case you, the reader, came here from google looking for a way to tell what is actual image file pixel width and height, this is how:
var img = new Image("path...");
var width = image.naturalWidth;
var height = image.naturalHeight;
This becomes quite usefull when dealing with all kinds of drawing on scaled images.
var img = document.getElementById("img");
var width = img.naturalWidth;
var height = img.naturalHeight;
document.getElementById("info").innerHTML = "HTML Dimensions: "+img.width+" x "+img.height +
"\nReal pixel dimensions:"+
width+" x "+height;
<img id="img" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Circle-withsegments.svg" width="100">
<pre id="info">
</pre>

Related

CSS max() function alternative

I would like to set the min-height of a HTML element to the maximum of two values, but unfortunately css doesn't support max().
Here's my css code:
#content{ min-height:calc( 100% - 100px); }
The other value is constant number (400px). I think I have to use JS, but I cant figure out how to do that.
Here is my JS code:
function layout(){
var y = document.getElementById("content");
y.style.minHeight = Math.max(parseInt(y.style.minHeight), 400).toString + "px";
}
window.onload = layout;
window.onresize = layout;
alert(parseInt(y.style.minHeight)) gives me naN.
What am I doing wrong?
Regards
I can't determine a direct way to get the calculated result of the min-height style.
But the following function assigns it to the height of the element, from which we can get it as the element's new offsetHeight.
The function then restores the original height of the element:
function layout() {
var y = document.getElementById('content'),
h = y.offsetHeight;
y.style.height = getComputedStyle(y).getPropertyValue('min-height');
y.style.minHeight = Math.max(y.offsetHeight, 400) + 'px';
y.style.height = h + 'px';
} //layout
Working Fiddle

Resize image before loading - jquery

I'm using this plugin to create image zoom and gallery, yet I want to scale all images to fit with the container (using ratio algorithm).
Here is ratio function :
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
And this is how the gallery load images :
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
What I've tried :
var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
But scaleSize is not working properly since the current width and height is not yet defined (image not yet exist in dom).
Thanks for any pointers.
I took a look into plugin code and think you call your scaleSize() too early. An image with class simpleLens-big-image exists first after var img is set up and addClass() is done.
Try following:
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Try something like this and call the onload method. This will make sure that the image is loaded to the DOM before you resize
var img = $('<img>');
img.src = src ;
img.onload = function() {
// Run onload code.
} ;

IE 6,7,8 don't support onload event in image object or DOM

My application has a large size of images to present and which should be resized for uniformly presentation with fixed width and height, to do so I write a JavaScript method in image's onload image like this:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcHeight = targetHeight;
calcWidth = (targetHeight / height) * width;
} else {
calcWidth = targetWidth;
calcHeight = (targetWidth / width) * height;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
HTML image:
<img src='PATH' onload='autoResizeImage(100, 100, this)'>
This way works well on Chrome and Firefox except IE 6,7,8. I'm suffering on this, how can I complete this task on IE 6,7,8.
Thanks so much.
I would start by saying that if you're serving images to be displayed at a particular size, you should send them from the server at the correct size in the first place. Sending excessively large images and having the browser resize them is poor practice because it means that you're using up a lot more bandwidth than you need to. Your users may have restricted bandwidth, and may not appreciate the extra load time on your page caused by this.
However, I don't really know why you need to do this resizing exersise at all? HTML will by default scale an image to the size of the <img> tag that contains it anyway, so all you need to do is specify height and width styles for your <img> tag, and the scaling will be done automatically. There should be absolutely no need for all that messing around with Javascript.
<img src='PATH' style='width:100px; height:100px;'>
That should work in all browsers; no JS required. The image should be scaled for you.
But ideally, as I said, please try to avoid sending excessively large images to the page if you're not going to use them at full size.
Change the order of assignments. First assign onload function and then src attribute. It works for IE 8 at least.
var div = document.getElementById('div');
var img = new Image();
img.onload = function() {
var text = document.createTextNode('loaded ' + img.src);
div.appendChild(text);
};
window.setTimeout(function() {
var random = Math.random();
img.src ="http://stackoverflow.com/users/flair/450989.png?random=" + random;
}, 1000);
div.appendChild(img);
<div id="div"/>

Strange behavior when drawing on multiple canvases

Basically, I'm trying to create a grid spanning multiple canvases, but I get strange behaviour on the first and last one. The stroke color and spacing is changed. I don't see how it could happen. Here is the relevant code, follow the link to see it in action. (the site is work in progress)
http://www.gjar-po.sk/~hudak9c/test3/
var canvasCount = document.getElementsByTagName("canvas").length;
if (canvasCount > 0) {
for (var i = 0; i < canvasCount; i++) {
var canvas = document.getElementsByTagName("canvas")[i];
if (canvas.getContext("2d")) {
var can = canvas.getContext("2d");
can.beginPath();
for (var x = 5; x < 640; x += 20) {
can.moveTo(x, 0);
can.lineTo(x, canvas.height);
}
for (var y = 5; y < canvas.height; y += 20) {
can.moveTo(0, y);
can.lineTo(canvas.width, y);
}
can.lineWidth = 1;
can.strokeStyle = "#000";
can.stroke();
} else {
alert("getContext fail");
}
}
}
Edit: I managed to fix the problem. It was caused by me (obviously) setting the width and height of the canvas through style.width and style.height, not through canvas.width and canvas.height, which made them stretch/shrink from their default dimensions instead of resize.
Try to set width and height to the canvases by tag attributes width and height like this:
<canvas width="640" height="50">
Not by style attribute. It is very important. Because when you set style attribute and point there width and height properties, then your canvas with default real width and height just stretches to your new sizes.

Javascript Resize Image not working

I have JS which resize the width and height of Image which is working fine if I used Alert before assigning the actual image src to the image object and if I omit the alertbox, it is not working. Please suggest me how to fix it.
`
<html>
<head>
<script type="text/javascript" language="javascript">
function resize_image_height_weight(id, hgt, wdth)
{
//alert(id);
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
// alert("Height=>" + heights + " Width=> " + widths);
if(heights > hgt || widths > wdth)
{
if(heights > widths)
{
var temp = heights/hgt;
var new_width = widths / temp;
new_width = parseInt(new_width);
heights = hgt;
widths = new_width;
}
else
{
var temp = widths/wdth;
var new_height = heights / temp;
new_height = parseInt(new_height);
heights = new_height;
widths = wdth;
}
}
Obj.height = heights;
Obj.width = widths;
}
</script>
</head>
<body>
<div>
<center>
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" id="i" alt="Google logo" height="150" width="150">
<script type="text/javascript">
document.images[document.images.length-1].onload = resize_image_height_weight("i",150,150);
</script>
</center>
</div>
</body>
</html>`
When you set the .src on an image, you have to wait until the image is successfully loaded until you can read it's height and width. There is an onload event handler that will tell you when the image is loaded.
Here's a place in your code where this issue could occur:
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
In this case, since the image was already elsewhere in the document, you should just read the height and width off the existing element rather than the new element.
Be very careful when testing because if the image is in your browser cache, it may load immediately, but when it's not in your cache, it takes some time to load and won't be available immediately.
Putting an alert at the right place in your script can allow the image to load before the script proceeds which could explain why it works with the alert.
As RobG mentions, your onload handler is also faulty (needs to be a function, not the returned result of a function).
Here's a simpler function to scale an image to fit the bounds. This uses a trick that you only need to set one size (height or width on the image) and the other will be scaled by the browser to preserve the aspect ratio.
function resizeImage(id, maxHeight, maxWidth) {
// assumes the image is already loaded
// assume no height and width is being forced on it yet
var img = document.getElementById(id);
var height = img.height || 0;
var width = img.width || 0;
if (height > maxHeight || width > maxWidth) {
var aspect = height / width;
var maxAspect = maxHeight / maxWidth;
if (aspect > maxAspect) {
img.style.height = maxHeight + "px";
} else {
img.style.width = maxWidth + "px";
}
}
}
You can see it in action here: http://jsfiddle.net/jfriend00/BeJg4/.
In the function assigned to onload:
> document.images[document.images.length-1].onload =
> resize_image_height_weight("i",150,150);
you are assigning the result of calling resize_image_height_weight which throws an error in IE. Set it to a function instead:
document.images[document.images.length-1].onload = function() {
resize_image_height_weight("i",150,150);
};

Categories

Resources