2012-11-13 60 views
2

我在我的代码中遇到了事件监听器和图像加载器的问题。当我尝试加载并检查基于事件侦听器加载的图像的状态时,跳过了一些图像。我认为浏览器只能处理一个事件,而当活动的事件不会停止时,可以工作并跳过其工作。因此很少的图像会返回到前景状态并可以使用。给我一些关于这个的建议。这是我的代码:AddEventListener和图像加载器的问题

//Image loader 
var urlList = [ 
    'images/ground_02.png', // 0 - FG 
    'images/ground_layer0.png', // 1 - CITY 
     ... 
]; 
var urlListLength = urlList.length; //length of URL-array 
var iCount = new Number(0); // Create zero-counter 
var images = new Array(); // All images array. Each elem stores one image 
var imageInfo = function(imageName, imageCount, imageWidth, imageHeight) { // Constructor for image data container 
    this.imageName = imageName; // Url of image 
    this.imageCount = imageCount; // Frames 
    this.imageWidth = imageWidth; // Width of images 
    this.imageHeight = imageHeight; // Height of images 
}; 
var imageData = new Array(); // Images data array 
for (var i=0; i!=urlListLength; ++i) { // Loop for each image load 
    images[i] = new Image(); // Image array. 
    images[i].addEventListener('load', function(i) { 

     imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height)); 

     iCount++; 
     if (iCount == urlListLength) { 
      var loaded = true; 
      loop(); 
     }; 

    }, false); 

    images[i].src = urlList[i]; 
    images[i].onerror=function() { 
     alert("FAIL "+this.src); 
    }; 

}; 
+0

你可以编辑你的文章,使其更清晰你问什么问题?你有没有试图确认你对事业的想法? – Hbcdev

+0

如何测试一些图像是否加载? –

+1

你应该在设置src之前定义onerror *。 –

回答

0

这应该适用于所有浏览器,包括IE6。

var list = [ 
     'images/ground_02.png', 
     'images/ground_layer0.png' 
    ], 
    images = {}; 

function loadImage() { 
    images[this.src] = { 
    loaded: (this.width > 0 ? true : false), 
    src: this.src, 
    width: this.width, 
    height: this.height 
    }; 

    if (list.length < 1) return; 

    var url = list.pop(), 
     img = new Image(); 

    img.onload = loadImage; 
    img.onerror = loadImage; 
    img.src = url; 
} 

loadImage(); // Initialize loading 

如果你需要检查的图像已加载:

function isImageLoaded(src) { 
    return (images[src] && images[src].loaded); 
} 

if (isImageLoaded('images/ground_02.png')) alert('Yes!'); 
0

你有问题至少在这里:

imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height)); 

load事件被触发一次加载图像通过浏览器。但没有必要按照加载开始时的顺序触发它。基本上,images[2]可以在images[0]images[1]之前加载,在这种情况下,iCount将不起作用。

您可以使用this而不是images[iCount],因为在这种情况下,this会指向已经发射加载事件的图像。

imageData.push(new imageInfo(this, this.width/this.height, this.width, this.height)); 

我认为浏览器只能处理一个事件和活动的一个不是 未来能够停止工作,并跳过工作。

没有。那是错的。定期所有的事件将被解雇。但是JS是单线程的,所以它只是简单地将一个事件放入一个队列中,并在之前完成后运行下一个事件。它不会跳过任何事件。