简体   繁体   中英

Getting Value of Image Width from JavaScript Image Onload Function

I have the following which gets the width of a given image:

<!DOCTYPE html>
<html>
<head>
    <title>Image Width</title>
    <script>
        var img = new Image();
        img.onload = function() { 
            alert("Width: " + img.width);
        };
        img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"

        // Do something with 'img.width' here, outside the image onload event handler.

    </script>
</head>
<body>
</body>
</html> 

I understand that I need the image to load before getting its width, and how to get its width from within the image onload event handler, but I'm having real difficulty accessing its width from outside the handler.

Am I just being an idiot and missing something really simple or is it more complex than I think?

Any help would be most appreciated.

Regards, Steve.

The problem you face is asynchronous programming. The onload function will be called by the engine at a later time, and the program will hold its execution.

There are two options:

  1. If you need the value as soon as possible, you'll have to run the code inside onload , eg:

     var img = new Image(); img.onload = function() { alert("Width: " + img.width); // Do something with 'img.width' here, outside the image onload event handler. }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
  2. If the code that will access img.width will happen later, eg after user clicks something, you can store the value and use it elsewhere:

     var width; var img = new Image(); img.onload = function() { width = img.width; }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg" function anotherFunction() { alert(width); }

I'm not sure I understand what you're trying to do, but if you want to access the image's width then I suggest you read some more about asynchronous code.

What the img.onload = function() {} code does is to schedule the function to be called after the image has been loaded.
However the code that follows it is just being executed immediately ( synchronously ) after the scheduling takes place, which most surely will precede the image's being loaded.

Hence, you need to delay its execution until the image is loaded, which is exactly what img.onload is meant for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM