2016-09-14 68 views
1

當點擊一個按鈕時,我在畫布上爲一些東西製作動畫。一旦動畫完成,我想調用一個函數作爲參數傳遞到初始化爲​​的函數中。帶回調函數的requestAnimationFrame?

這可能嗎?

我嘗試了各種方法,用匿名函數等

var anim = false; 
var game = new Game(); 

function Game(){ 
    this.turn = 1; 

    this.move = function(){ 
    this.animate(game.advanceTurn); 
    } 

    this.advanceTurn = function(){ 
    this.turn++; 
    } 

    this.animate = function(callback){ 
    var done = false; 
    anim = window.requestAnimationFrame(game.animate); 

    // animation code here 

    if (done){ 
     window.cancelAnimationFrame(anim); 
     anim = false; 
     callback(); 
    } 
    } 

即按一下按鈕,動畫的東西,動畫完成,調用game.advanceTurn。

當記錄提供的參數時,控制檯將首先記錄我的回調函數,然後將其替換爲我認爲是計時器測量的值(符合rAF描述的MDN描述)。

回答

3

您可以使用bind讓您的回調函數傳遞。同時,您還可以通過對this,讓您保持參照當前遊戲對象實例:

function Game(){ 
 
    var i = 0; 
 
    var anim = false; 
 
    
 
    this.turn = 1; 
 

 
    this.move = function(){ 
 
    this.animate(this.advanceTurn.bind(this)); 
 
    } 
 

 
    this.advanceTurn = function(){ 
 
    this.turn++; 
 
    } 
 

 
    this.animate = function(callback){ 
 
    var done = false; 
 
    anim = window.requestAnimationFrame(this.animate.bind(this, callback)); 
 

 
    // animation code here 
 
    console.log(i++); 
 

 
    if (i>5){ 
 
     window.cancelAnimationFrame(anim); 
 
     i = 0; 
 
     anim = false; 
 
     callback(); 
 
    } 
 
    } 
 
} 
 

 
new Game().animate(function() { 
 
    console.log('callback received'); 
 
});

0

你沒有正確編寫類。

在您的Game類中,您正在使用變量game,但應該使用this

例如,

window.requestAnimationFrame(game.animate); 

應該

window.requestAnimationFrame(this.animate); 

爲什麼你要爲animfalse?​​returns a non-zero number of type `long.

this.turn應該從0開始,而不是從1開始。

move致電animate沒有意義。

事實上,你試圖使用的結構是挖你一個墳墓。

我認爲最好讓你重新開始,並在第二次正確的時候做。

Try this tutorial :)