在图像完全加载之前使用 Javascript 获取图像尺寸 [英] Get image dimensions with Javascript before image has fully loaded

查看:32
本文介绍了在图像完全加载之前使用 Javascript 获取图像尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解了在图像完全加载后获取图像尺寸的各种方法,但是是否有可能在任何图像刚开始加载时获取其尺寸?

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 started to load?

我没有通过搜索找到太多相关信息(这让我相信这是不可能的),但事实上浏览器(在我的例子中是 Firefox)显示了我在新标签页中打开的任何图像的尺寸它刚刚开始加载图像后的标题让我希望实际上有一种方法,我只是错过了正确的关键字来找到它.

I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.

推荐答案

您是对的,可以在完全加载之前获取图像尺寸.

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

这篇关于在图像完全加载之前使用 Javascript 获取图像尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆