How to loop canvas animation?

Member

by samara , in category: Javascript , 3 months ago

How to loop canvas animation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 3 months ago

@samara 

To loop a canvas animation in HTML5, you can use the requestAnimationFrame() function along with a recursive function. Here is an example code snippet that demonstrates how to create a looping animation on a canvas element:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
    <title>Canvas Animation Loop</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>

    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        
        function draw() {
            // Clear the canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // Draw your animation here
            ctx.fillStyle = 'blue';
            ctx.fillRect(50, 50, 50, 50);
            
            // Request next frame
            requestAnimationFrame(draw);
        }
        
        // Call the draw function to start the animation
        draw();
    </script>
</body>
</html>


In this code snippet, the draw() function is called recursively using requestAnimationFrame(), which creates a loop that continuously updates the canvas animation. You can customize the animation by adding more drawing operations inside the draw() function.