2015-09-07 88 views
0

我一直在想這個。我花了3個小時嘗試不同的方法並在網上尋找解決方案,但我仍然沒有修復它。 我有兩個單獨的圖像(不是一個spritesheet),他們需要一個接一個地顯示爲動畫,無限。這是我最新的代碼:HTML5逐幀動畫(多個圖像)

var canvas, context, imageOne, imageTwo, animation;  

function init(){ 
    canvas = document.getElementById("canvas"); 
    context = canvas.getContext("2d"); 

    canvas.width = window.innerWidth; 
    canvas.height = window.innerHeight; 

    imageOne = new Image(); 
    imageTwo = new Image(); 

    imageOne.src = "catone.png"; 
    imageTwo.src = "cattwo.png"; 

    // Just to make sure both images are loaded 
    setTimeout(function() { requestAnimationFrame(main);}, 3000); 
} 

function main(){ 

    animation = { 

    clearCanvas: function(){ 
     context.clearRect(0, 0, canvas.width, canvas.height); 
    }, 

    renderImageOne: function(){ 
     context.drawImage(imageOne, 100, 100); 
    }, 

    renderImageTwo: function(){ 
     context.drawImage(imageTwo, 100, 100); 
    } 

    }; 

    animation.renderImageOne(); 

    // I also tried calling animation.clearCanvas(); 
    context.clearRect(0, 0, canvas.width, canvas.height); 

    animation.renderImageTwo(); 

    // I put this here to confirm that the browser has entered the function, and that it hasn't stopped after animation.renderImageTwo(); 
    console.log("cats"); 
    requestAnimationFrame(main); 
} 

init(); 

但問題是,只有一個圖像顯示,它不動。我在控制檯中看不到任何錯誤或警告。我也確信HTML和JavaScript已正確連接並且圖像處於正確的路徑。所以無論如何,只顯示第一個功能中的圖像。例如:animation.renderImageOne();顯示catone,但如果我用animation.renderImageTwo()替換它;它顯示cattwo。

回答

2

的問題是在這裏:

animation.renderImageOne(); 

    // I also tried calling animation.clearCanvas(); 
    context.clearRect(0, 0, canvas.width, canvas.height); 

    animation.renderImageTwo(); 

是它的繪製第一個圖像,清空畫布,然後繪製第二圖像,那麼畢竟它繪製到屏幕上。離開你只看到第二個圖像。你將來需要這種交替值的變量,並用它來確定哪張是你應該借鑑:

var canvas, context, imageOne, imageTwo, animation; 
var imageToDraw = "one"; 

然後:

function main() { 

    ... 

    if(imageToDraw == "one") { 
     animation.renderImageOne(); 
     imageToDraw = "two"; 
    } 
    else if(imageToDraw == "two") { 
     animation.renderImageTwo(); 
     imageToDraw = "one"; 
    } 

    ... 
} 

注:你並不需要定義animationmain(),您可以將其移至全局範圍。那樣你每次打電話main()時都不要重新定義它。

+1

另外我想知道是否使用字符串是設置「交流發電機」,但無論如何upvote最有效的方式:-) – Kaiido

+0

@Kaiido我想這可能會更容易閱讀,我看到你的觀點,使用布爾值可能是一個更好的主意。雖然它確實開放了使用兩個以上圖像的機會。 –

+0

是的,如果你有很多圖像要交替使用,最好使用一個數組和一個增加的變量,註釋中的布爾值只針對這個特定的2狀態切換。但我看到你的可讀性,我認爲這是適合OP的最佳選擇。 – Kaiido