2014-01-11 80 views
0

我想寫一個小的流媒體客戶端與畫布對象。畫布drawimage循環與超時

這是必要的代碼:

this.drawPictures = function() { 
    var i = 0; 

    while (i <= 3000) { 
     this.addPicture("Pictures/Wildlife/" + i + '.bmp', 1, 1); 
     i = i + 4; 
    } 
} 

這工作得很好!圖像會顯示出來。但這不是我想要的。

我想設置一個FPS限制。所以我需要在這個循環中有一個1000ms /幀的「睡眠」。

我試過用SetInterval或SetTimeOut的一些方法。但他們都沒有爲我工作。

於是,我就寫我自己的睡眠:

var i = 0; 
    timeStart = new Date().getTime(); 

    while (i <= 3000) { 
     timeNow = new Date().getTime(); 
     timeDifference = timeNow - timeStart; 
     if (timeDifference > 1000*i) { 
      this.addPicture("Pictures/Wildlife/" + i + '.bmp', 1, 1); 
      i = i + 1; 
     } 
    } 

我省實際的日期時間循環之前,準確地當爲TimeDifference達到1000毫秒我試圖加載圖片並加我。

我的問題: 當我用alert(i)而不是this.addPicture時,它工作的很好!我每1000毫秒(每秒)得到一個警報

當我這樣做像上面的例子(與this.addPicture)瀏覽器只是加載自己,直到我得到一個錯誤,該頁面無法加載。但我沒有看到任何圖片!

這是我給AddPicture功能:

this.addPicture = function (cPicPath, nSizeX, nSizeY) { 

    var imageObj = new Image(); 
    imageObj.onload = function() { 

     ctx.drawImage(imageObj, nSizeX, nSizeY); 
    } 
    imageObj.src = cPicPath; 
} 

有誰知道爲什麼它的工作原理與警報,但不給AddPicture?因爲當我不使用時間戳(第一個代碼示例)時,它工作正常!

回答

0

在您的ctx.drawImage中,imageObj之後的2個參數是X/Y而不是圖像大小。

您需要給圖像加載足夠的時間(1秒不夠時間)。

您的addPicture 開始(但沒有完成)加載圖像,但圖像沒有完全加載的時間addPicture再次被調用。

有許多像裝載機在那裏......這裏有一個:

var imageURLs=[]; // put the paths to your images here 
var imagesOK=0; 
var imgs=[]; 
imageURLs.push("myPicture1.png"); 
imageURLs.push("myPicture2.png"); 
imageURLs.push("myPicture3.png"); 
imageURLs.push("myPicture4.png"); 
loadAllImages(start); 

function loadAllImages(callback){ 
    for (var i=0; i<imageURLs.length; i++) { 
     var img = new Image(); 
     imgs.push(img); 
     img.onload = function(){ 
      imagesOK++; 
      if (imagesOK>=imageURLs.length) { 
       callback(); 
      } 
     }; 
     img.onerror=function(){alert("image load failed");} 
     img.crossOrigin="anonymous"; 
     img.src = imageURLs[i]; 
    }  
} 

function start(){ 

    // the imgs[] array holds fully loaded images 
    // the imgs[] are in the same order as imageURLs[] 
    // Start your timer and display your pictures with addPicture 

}