Amay
Amay

Reputation: 1521

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?

Upvotes: 13

Views: 14552

Answers (1)

Ivan Chub
Ivan Chub

Reputation: 442

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();

Upvotes: 13

Related Questions