Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - 无法从img.onload返回值[重复](Unable to return value from img.onload [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

trying to get dimenstions (eg 600x300) from an image using javascript.

(尝试使用javascript从图像中获取尺寸(例如600x300)。)

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>
  ask by Mike Q translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getMeta is finished before onload function.

(getMetaonload函数之前完成。)

You need to use a Promise or a callback.

(您需要使用Promise或回调。)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...