Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas requestAnimationFrame pause

How to pause canvas animation made with requestAnimationFrame ? I start animation like this:

Code:

window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
})();

function Start() {
    Update();
    requestAnimFrame(Start);
}

Start();

Now I want to add pause option after keydown. Is there any simple way to do it?

like image 806
Amay Avatar asked May 14 '13 22:05

Amay


1 Answers

What you could do is create a variable that stores the state of your animation: paused or unpaused. Change that state every time you click a button. Something like this should work:

var isPaused = false;

window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
})();

function Start() {
    if (isPaused) {
        Update();
    }

    requestAnimFrame(Start);
}

window.onkeydown = function() {
    isPaused = !isPaused; // flips the pause state
};

Start();
like image 60
Ivan Chub Avatar answered Oct 29 '22 08:10

Ivan Chub