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

查看:113
本文介绍了在图像完全加载之前使用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天全站免登陆