вторник, 15 июля 2008 г.

Defining and Changing Image Size in JavaScript

How can one define the size of the image in JavaScript?

I've come up with the approach of handling onload event for image element like this:

imageElement.onload = function() {
var width = imageElement.width;
var height = imageElement.height;
...
}

Once image is loaded browser knows for sure the width and height of this image and developer can reference actual values from width and height properties of image DOM element.

By changing image height or width it will be proportionally resized. BUT it is important to remember that corresponding image element properties are changed only when image is displayed!

Let's say there is an image 10 pixels long and 20 pixels high. JavaScript code sets width to be 50 pixels, thus demanding height to be increased 5 times, resulting in 100 pixels. If image was visible at the moment width value was overriden, height property will be updated as well, with 100 pixels. And if image was invisible, height property is not updated and left as it is before image si actually displayed!

4 комментария:

Анонимный комментирует...

So it's kind of callback when you dynamically load an image? because generally you could just get width and height without onload function.

Tsukur Vladimir aka _flush_dia_ комментирует...

Yes, it is a callback. The thing is if you try to obtain width and height immediately after setting image source, browser may not know at that point of time exact sizes of the image. It takes some time for him to download the image itself. If you define onload callback function the extraction of height and width from corresponding image properties inside such a function will return appropriate size, because image is already loaded.

Antoine комментирует...
Этот комментарий был удален автором.
Анонимный комментирует...

nice trick ;)