到目前爲止,我有一個函數接下來應該得到一個時間(只是幾個小時),然後比較if語句中的小時數以將正確的時鐘加載到imageURLs []數組中。據我可以告訴這工作正常。然後運行loadAllimages()函數,它應該將圖像加載到數組imgs []中。然後它應該在方法start()中繪製圖像。我這樣做是因爲藥丸圖像在時鐘的頂端,我需要它來正確加載。問題是loadAllimages()函數無效,我找不出原因。到目前爲止,所有我可以告訴是因爲在start()函數imgs.length開始就沒有把它在陣列IMGS []爲0在HTML畫布上加載圖像
function next(){
var currentdate = new Date();
var datetime = currentdate.getHours();
var imageURLs=[];
var imagesOK=0;
var imgs=[];
if(datetime==1||datetime==13){
imageURLs.push("clock/clock1.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==2||datetime==14){
imageURLs.push("clock/clock2.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==3||datetime==15){
imageURLs.push("clock/clock3.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==4||datetime==16){
imageURLs.push("clock/clock4.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==5||datetime==17){
imageURLs.push("clock/clock5.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==6||datetime==18){
imageURLs.push("clock/clock6.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==7||datetime==19){
imageURLs.push("clock/clock7.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==8||datetime==20){
imageURLs.push("clock/clock8.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==9||datetime==21){
imageURLs.push("clock/clock9.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==10||datetime==22){
imageURLs.push("clock/clock10.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==11||datetime==23){
imageURLs.push("clock/clock11.png");
imageURLs.push("clock/pill.png");
}
else if(datetime==0||datetime==12){
imageURLs.push("clock/clock12.png");
imageURLs.push("clock/pill.png");
}
loadAllImages();
function loadAllImages(){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
img.src = imageURLs[i];
img.onload = function(){
imgs.push(img);
};
}
if(i==imageURLs.length){
start();
}
}
function start(){
// the imgs[] array holds your fully loaded images
for (var i=0; i<imgs.length; i++) {
if(i==0){
canvas.ctx.drawImage(this, 600,100);
}
else{
canvas.ctx.drawImage(this, 740, 240);
}
}
// the imgs[] are in the same order as imageURLs[]
}
}
您可能會發現我的[YAIL圖像加載器](http://abdiassoftware.com/blog/2013/11/yail-yet-another-image-loader-for-javascript/)可用作替代方案。此外這已被回答[這裏](http://stackoverflow.com/questions/17524444/how-to-load-images-from-json-object-on-canvas-image/17527381#17527381)。 – K3N