2012-11-13 145 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是單線程的,所以它只是簡單地將一個事件放入一個隊列中,並在之前完成後運行下一個事件。它不會跳過任何事件。