Phil
Phil

Reputation: 627

Why is my HTML5 canvas not clearing during a short pause?

I have a game loop here that is rendering the following in draw(). The desired goal is to have the game clear the canvas, say "game over", then pause for 3 seconds before resetting and continuing a new game. However, it looks like it just pauses the existing game for 3 seconds, instead of clearing and drawing "game over". What could be wrong with it?

    // check for game over - failed
    if (ball_y + ball_dy + ball_radius> HEIGHT-20)
    {
        game_end_start_time = new Date().getTime();

         while (new Date().getTime() - game_end_start_time < 3000)
         {

            clear();  // calls  ctx.clearRect(0, 0, WIDTH, HEIGHT);

            fillColorValue(COLOR_GREEN);
            drawFont("G A M E   O V E R", WIDTH/2-80, HEIGHT/2);

         }

        resetGame();  
        return;
    }  

Upvotes: 0

Views: 159

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83368

How to write render loop (animation loop) in Javascript:

http://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/

Upvotes: 0

Maurice
Maurice

Reputation: 27632

Your JavaScript code runs on the UI thread. So basically the browser can't draw until your code is finished with execution. And as you are just looping for 3 seconds all you are doing is blocking the browser from doing anything at all.

Try drawing the game over screen and using setTimeout(function(){resetGame();}, 3000); to restart the new game after 3 seconds.

Upvotes: 2

Related Questions