你可能想考慮spriting這是把所有的圖像放在一個大的圖像。有了這個,你只需要加載一個大的圖像,然後重新定位每個場景。
或者,在實際使用它們之前,您可能還需要預先加載這150個圖像。你可以使用JS數組來存儲Image對象,然後遍歷該數組來獲取圖像。
var images = [];
var expectLoaded = 150;
for(var i = 0; i<expectLoaded;i++){
(function(i){
//new image object
var img = new Image();
//onload hander
img.onload = function(){
//after load, push it into the array
images.push[img];
//and check if the all has loaded
if(images.length === expectLoaded){
//preload done
}
}
//start loading this image
img.src = //path to image[i];
},(i));
}
循環阻塞UI線程。 JS是單線程的,意味着代碼以線性方式依次執行。在循環語句之後的任何內容都會等到循環結束。如果這個循環需要很長時間......請喝點咖啡。此外,由於您正在操作DOM,因此UI線程被阻止後,您看不到更改。
但有一些方法可以繞過這一點,其中一個使用超時來延遲和排隊代碼,以便稍後執行,當JS不忙時。
function animate(frameNo){
//animate frame[frameNo];
if(frameNo < total_frames){ //make the UI breate in between frames
setTimeout(function(){ //so that changes reflect on the screen
animate(++frameNo); //then animate next frame
},200);
}
}
//start
animate(0);
嗯,如何在預先加載所有圖像之前開始在循環中顯示它們?或者出於某種原因,這不是一種選擇? – Raine 2012-04-01 07:11:22
在顯示它們之前,我確實將它們放在了陣列上。 – Sednus 2012-04-01 07:14:38
是的,看到我在下面發佈的鏈接,有一種方法可以在所有圖片已經成功加載到瀏覽器緩存中的情況下運行腳本,這將允許循環避免加載它們「即時」 – Raine 2012-04-01 07:18:52