1

trying to get dimenstions (e.g. 600x300) from an image using javascript. I am not sure how to return the data because it's not working. Do I need a callback, and how ?

<script>
function getMeta(url){   
    var img = new Image();
    var res = img.onload = function(){
        var ret = this.width+'x'+ this.height;
        alert(ret);
        return ret;
    };
    img.src = url;
    return res;
}
var meta = getMeta('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg');
alert(meta);
</script>
Mike Q
  • 6,716
  • 5
  • 55
  • 62
  • 1
    `getMeta` returns before the `onload` function fires. You'll need to use a promise or other async workflow. – Mark Nov 28 '19 at 23:02
  • @certainPerformance , it is but it also isn't, IMO the response below was perfect perhaps with your link included. I don't think this needed to be tagged as a duplicate. – Mike Q Nov 29 '19 at 15:47

1 Answers1

2

getMeta is finished before onload function. You need to use a Promise or a callback. Example with callback below:

function getMeta(url, cb){
    var img = new Image();
    img.onload = function(){
        var ret = this.width+'x'+ this.height;
        console.log(ret);
        cb(ret);
    };
    img.src = url;
}
getMeta('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg', function(meta){
  console.log('got meta', meta);
});
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • Thank you, I think your answer plus the link to the other thread was perfect.. I got it working thanks to your help. – Mike Q Nov 29 '19 at 15:46