如何从onload保存图像宽度和高度? [英] How to save image width and height from onload?

查看:97
本文介绍了如何从onload保存图像宽度和高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< li> 元素的数组,我想把它变成一个旋转木马,只是我希望图片大小超过640x480时调整大小以及框架中心。

I have an array of <li> elements that I am trying to make into a carousel, just that I want the images to be resized if bigger than 640x480 as well as centered into the frame.

我有以下代码:
HTML:

I have the following code: HTML:

<ul id="carousel">      
    <li><img src="pic1.jpg" /><p><b>2012</b> something</p></li>
    <li><img src="pic2.jpg" /><p><b>2016</b> something else.</p></li>
</ul>

JQuery:

var imW=[];
var imH=[];
//...
$('li',obj).each(function(index){ 
    itemSources.push( $(this).find('img').attr('src') );                
    var img = $(this).find('img'); 
    imW.push(img.width());
    imH.push(img.height());
});

然后我使用 itemSources [i] imW [i] imH [i] 调整图片大小并添加任何必要的填充以将其置于框架中心。

I then use itemSources[i], imW[i] and imH[i] to resize my image and add any necessary padding to center it in the frame.

如果我的互联网足够快并且图像在计算大小之前加载,那么它可以正常工作。 (哈!)

Which works fine provided that my internet is fast enough and the images load before the size is computed. (ha!)

我知道我想要的东西:

var img = new Image();
img.onload = function() {
    console.log(this.width + 'x' + this.height);
};
img.src = $(this).find('img').attr('src');

但我无法保存宽度和高度,因为只是推送到数组超出了范围,为此创建外部回调也是如此。如何将那些容易打印到控制台的尺寸保存到我的imW和imH数组中?

But I cannot save the width and height, since just pushing to the arrays gets out of scope, and so does creating an external callback for that. How can I save those sizes that are so easily printed to the console into my imW and imH arrays?

推荐答案

你基本上可以设置图像的属性,如 data-loaded =true加载图像后加载最后一个图像然后可以迭代图像并加载数组

You can basically set an attribute of an image, something like data-loaded="true" once the image is loaded and when the last image is loaded you can then iterate the images and load the array

onload 方法中,进行以下更改

In your onload method, do the following changes

var img = new Image();
img.onload = function() {
    console.log(this.width + 'x' + this.height);

    //set this attribute to indicate that this image has been loaded already
    $(this).attr( "data-loaded", "true" );

    //check if all images have this attribute
    if ( $( "img[data-loaded='true']" ).size() == $( "img" ).size() ) 
    {
      //now iterate the images to load your array
    }
};
img.src = $(this).find('img').attr('src');

这篇关于如何从onload保存图像宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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