I’ve got couple of lines of JavaScript using jQuery to resize images to thumbnails.
var thumb = $(this);
thumb.load(function() {
var ratio = thumb.height() / config.maxHeight;
var newWidth = Math.ceil(thumb.width() / ratio);
thumb.height(config.maxHeight);
// this line matters
thumb.width(newWidth);
});
Fotunately this works fine. But if I replace the last line with:
thumb.width(Math.ceil(thumb.width() / ratio));
It changes width of images that hasn’t got explicitly defined dimensions badly (too narrow). To me, it seems like totally equivalent ways – via a variable or directly – but obviously they’re not.
I tried casting the ceil() result to a Number or Integer and it behaved opposite way – images with undefined dimension were OK but the rest was too wide (width of original image).
Although I the first solution works I guess there’s something fundamental I’m missing. So I want to avoid it in the future.
Thank you!
I would guess that the
<img>element you are manipulating does not have declaredheightorwidthattributes. If that is the case, then the issue is how browsers intelligently resize images given only one constraint.If you have an image that is 1000px wide, and 1000px tall, and you write an IMG tag like this:
Modern browsers will render the huge image resized down to 10 by 10px.
So, on the line where you alter the height:
the browser goes ahead an also alters the width. If you subsequently read the width (i.e.
thumb.width(Math.ceil(thumb.width() / ratio))), you are going to be reading the new width, not the width it had before being given a new height.