2

我的代码中的事件侦听器和图像加载器有问题。当我尝试根据事件侦听器加载和检查加载图像的状态时,一些图像被跳过。我认为浏览器只能处理一个事件,当活动的一个没有停止时,下一个可以工作并跳过它的工作。很少有图像返回错误状态并且可以使用。请给我一些建议。这是我的代码:

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

};
4

2 回答 2

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 是单线程的,所以它只会简单地将一个事件放入队列中,并在上一个事件完成后运行下一个事件。它不会跳过任何事件。

于 2012-11-13T11:46:55.913 回答
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!');
于 2012-11-13T11:40:19.477 回答