如何将setInterval转换为requestAnimationFrame

时间:2013-10-11 07:06:04

标签: javascript html5-canvas setinterval requestanimationframe

一个名叫Gustavo Carvalho的家伙发布了一个stackoverflow帖子,展示了相机/视口在HTML5游戏中的运作方式。

除了使用setInterval而不是requestAnimationFrame之外,一切都很好。

我尝试转换为requestAnimationFrame但没有成功: - (

有人可以帮忙吗?这是帖子:

Simple HTML5 game camera/viewport

非常感谢!

编辑:在回顾下面的答案之后,我想出了这个解决方案:

更换以下代码......

 // Game Loop
    var gameLoop = function(){                      

        update();
        draw();
    }   

    // <-- configure play/pause capabilities:



    var runningId = -1;

    Game.play = function(){

        if(runningId == -1){


                //Use setInterval instead of requestAnimationFrame for compatibility reason
            runningId = setInterval(function(){
                gameLoop();
            }, INTERVAL);



            console.log("play");

        }

    }

    Game.togglePause = function(){      
        if(runningId == -1){
            Game.play();
        }
        else
        {
            clearInterval(runningId);
            runningId = -1;
            console.log("paused");
        }
    }   

    // -->

替换这一个......

// Game Loop
    var gameLoop = function(){                      

        if(gameStatus == 'play'){

            update();
                draw();

        }

        window.requestAnimationFrame(gameLoop);

    }   


    var gameStatus = 'play';

    Game.play = function() {

        gameLoop();

    }




    Game.togglePause = function() {

        if(gameStatus == 'play'){

            gameStatus = 'pause';

            console.log(gameStatus);
        }
        else if(gameStatus == 'pause'){

            gameStatus = 'play';

            console.log(gameStatus);

        }



    }

2 个答案:

答案 0 :(得分:1)

您可以将代码的以下部分修改为:

/// add a flag as condition for loop
var isPlaying = true;

// Game Loop
function gameLoop(){                      
    update();
    draw();

    /// incorporate loop here
    if (isPlaying)
        requstAnimationFrame(gameLoop);
}   

然后:

Game.play = function(){ 
    if (!isPlaying){
        isPlaying = true;    /// enable looping
        gameLoop();          /// start loop
        console.log("play");
    }
}

Game.togglePause = function(){      
    if(!isPlaying){
        Game.play();
    }
    else
    {
        isPlaying = false;   /// this will terminate loop
        console.log("paused");
    }
}

请注意,对于最新版本的Firefox和Chrome,requestAnimationFrame现在没有前缀。对于旧版和其他浏览器,您可能需要使用polyfill

答案 1 :(得分:1)

对requestAnimationFrame函数的调用必须在其第一个参数中实际提供循环,这恰好是一个函数。 粗略地说,做这样的事情:

    function draw() {
      // some drawing on a canvas happens here
    }

    function game_loop() {
      var callback = function(t) {
        draw();
        // loop the whole thing:)
        game_loop();
      };
      window.requestAnimationFrame(callback);
    }