Sam Skirrow
Sam Skirrow

Reputation: 3697

HTML5 Canvas pause and restart animation

I am building a simple HTML5 canvas animation where several lines zig-zag acros the canvas.

Once the lines have been drawn, the animation restarts. I'm trying to add a pause between each reset of 5 seconds. Is there a way this can be done?

My canvas code is as follows:

<canvas id="myCanvas" width="220" height="400" style="background:black"></canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var counter = 0;

    setInterval(function(){

        if (counter > 13) {
            counter = 0;
            context.clearRect(0, 0, 220, 400); // clears the animation
        }

        drawLine(counter,context);
        counter++;
    },200);

    function drawLine(whichOne, context) {
        context.beginPath();

        if (whichOne % 2 == 0)
        {
            context.moveTo(0,2 + (whichOne / 2) * 30);
            context.lineTo(220, 2 + ((whichOne + 1) / 2) * 30);
        }
        else
        {
            context.moveTo(220,2 + (whichOne / 2) * 30);
            context.lineTo(0, 2 + ((whichOne + 1) / 2) * 30);
        }

        // Stroke Style
        context.lineWidth = 2;
        context.strokeStyle = '#FFFFFF';
        context.stroke();
    }
</script>

And here is a fiddle to my code. I'm very new to HTML5 canvas, so any help is appreciated.

Upvotes: 0

Views: 1015

Answers (1)

Alnitak
Alnitak

Reputation: 339846

Your problem description is unclear, but if your intent is to simply have a fixed delay between the end of the initial drawing and the start of the next then you're better off using setTimeout instead of setInterval:

var counter = 0;

(function loop() {
    if (counter > 13) {
        counter = 0;
        setTimeout(function() {
            context.clearRect(0, 0, 220, 400); // clears the animation
            setTimeout(loop, 200);   // start it up again
        }, 1000);     // but wait a second
    } else {
        drawLine(counter,context);
        counter++;
        setTimeout(loop, 200);
    }
})();   // start the loop immediately

See http://jsfiddle.net/alnitak/stdbagrc/

Upvotes: 1

Related Questions