无法从img.onload

时间:2019-11-28 23:00:09

标签: javascript

尝试使用javascript从图片中获取尺寸(例如600x300)。我不确定如何返回数据,因为它无法正常工作。我需要回调吗?如何?

<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>

1 个答案:

答案 0 :(得分:0)

getMetaonload函数之前完成。您需要使用Promise或回调。下面的回调示例:

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);
});