Get image dimensions with Javascript before image has fully loaded

后端 未结 3 1052
孤街浪徒
孤街浪徒 2020-11-28 05:48

I\'ve read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just star

3条回答
  •  忘掉有多难
    2020-11-28 06:38

    You are right that one can get image dimensions before it's fully loaded.

    Here's a solution (demo):

    var img = document.createElement('img');
    
    img.src = 'some-image.jpg';
    
    var poll = setInterval(function () {
        if (img.naturalWidth) {
            clearInterval(poll);
            console.log(img.naturalWidth, img.naturalHeight);
        }
    }, 10);
    
    img.onload = function () { console.log('Fully loaded'); }
    

提交回复
热议问题