0

Here is simple code. Arc works for sure but when I try to put requestAnimationFrame in function whole function just doesn't work.

I did nothing because I am doing it from Chris Courses canvas course. Exactly same code as his.

            var canvas = document.querySelector('canvas');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            var ctx = canvas.getContext('2d');

            var x = 200;
            function animate(){
            requestAnimationFrame(animate);
            ctx.beginPath();
            ctx.arc(x, 200, 30, 0, Math.PI * 2, false);
            ctx.strokeStyle = 'blue';
            ctx.stroke();
            console.log('F');
            x =+ 1;
            }
<html>
    <head>
        <meta charset="utf-8"/>
        <style>
            *{
                padding:0;
                margin:0;
            }
            body{
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <canvas>

        </canvas>
        <script src="canvas.js"></script>
    </body>
</html>
KadEyy
  • 3
  • 1

1 Answers1

2

You need to call the animate function at least once outside of the function to initialize the start of it. This can be another requestAnimationFrame(animate), animate(), or a self invoking function.

function animate(){
  // The function body
  requestAnimationFrame(animate);
}

animate();
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • "You should also call requestAnimationFrame at the end of the function and not the start." Why? It's perfectly correct to call it at the beginning, may even actually be better in the very rare cases it would matter (long frame) – Kaiido May 30 '19 at 23:15
  • I guess it doesn't really matter https://stackoverflow.com/questions/38229386/requestanimationframe-at-beginning-or-end-of-function – Get Off My Lawn May 30 '19 at 23:57