HTML5 - flickering animation

I seem to be able to draw different sized shapes on the HTML5 "canvas" from an array.

But there is a lot of flickering.  How can this be smoothed-out?


<!DOCTYPE html>
<html>
  <head>
  <title></title>
    <style type="text/css">
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script type="text/javascript">

        var i = 0;
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d'); 
        var one = {
            x: 300,
            y: 300,
            radius: 50,
            startAngle: 0,
            endAngle: Math.PI * 2,
            counterClockwise: false,
            color: '#aff',
            useletter: 'G'
        };

        var two = {
            x: 120,
            y: 120,
            radius: 20,
            startAngle: 0,
            endAngle: Math.PI * 2,
            counterClockwise: false,
            color: '#eee',
            useletter: 'T'
        };   

        _myCircleArray = [one,two];

        window.requestAnimFrame = (function (callback) {
            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
        })();

        function drawCircle(myCircle, context) {
            //context.save();
            context.beginPath();
            context.arc(myCircle.x, myCircle.y, myCircle.radius, myCircle.startAngle, myCircle.endAngle, myCircle.counterClockwise);
            context.fillStyle = myCircle.color;            
            context.fill();
            context.strokeStyle = '#000';
       //     context.closePath();
            context.stroke();
            //context.retore();
        }

        function drawText(myCircle, context, text) {
          //  context.save();
            context.beginPath();          
            context.fillStyle = '#000';          
            context.fill();
            context.font = "40px Georgia";
            context.fillText(myCircle.useletter, myCircle.x - 10, myCircle.y + 10);
            context.strokeStyle = '#000';
    //        context.closePath();
            context.stroke();           
          //  context.restore();
        }

        function animate(myCircle, canvas, context, startTime) {           
            var time = (new Date()).getTime() - startTime;           
            var amplitude = 150;   
            var period = 2000;           
            var centerX = (canvas.width / 2) - ((myCircle.radius * 2) / 2);        
            var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;            
            myCircle.x = nextX;
            context.clearRect(0, 0, canvas.width, canvas.height);
            drawCircle(myCircle, context);
            drawText(myCircle, context, "T");
            requestAnimFrame(function () {
                
                if (i < 1) {
                    i++;
                }
                else {
                    i = 0;
                }

                var a = _myCircleArray[i];
                animate(a, canvas, context, startTime);

            });
        }

      

       

       
        // wait one second before starting animation
        setTimeout(function () {
            var startTime = (new Date()).getTime();
            var a = _myCircleArray[i];
            animate(a, canvas, context, startTime);
           
        }, 1000);

    </script>
  </body>
</html> 

Open in new window

LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Robert SchuttSoftware EngineerCommented:
Most of the time, you use an animation 'frame' to clear the canvas and draw all shapes. In your current code you clear and draw only 1 of the shapes so they start flickering because half of the time they're just not on the screen.

If the moving shapes will never overlap you can solve it for this case by only clearing the relevant portion of the canvas, by changing line 82 to:
context.clearRect((canvas.width / 2) - (myCircle.radius * 2 * amplitude), myCircle.y - myCircle.radius - 1, myCircle.radius * 4 * amplitude, myCircle.radius * 2 + 2);

Open in new window


But probably a better solution would be to do the loop inside the animate() function:
        function animate(canvas, context, startTime) {           
            var time = (new Date()).getTime() - startTime;           
            context.clearRect(0, 0, canvas.width, canvas.height); // only clear once
            for (var a = 0; a < _myCircleArray.length; a++) {
                var myCircle = _myCircleArray[a];
                var amplitude = 150;   
                var period = 2000;           
                var centerX = (canvas.width / 2) - ((myCircle.radius * 2) / 2);        
                var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;            
                myCircle.x = nextX;
                drawCircle(myCircle, context);
                drawText(myCircle, context, "T");
            }
            requestAnimFrame(function () {
                
                    animate(canvas, context, startTime);

            });
        }

        // wait one second before starting animation
        setTimeout(function () {
            var startTime = (new Date()).getTime();
            animate(canvas, context, startTime);
           
        }, 1000);

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Tom KnowltonWeb developerAuthor Commented:
I was able to, quite literally, plug in your modified function above and it worked great.

Thank you for the fast response, forgive me for not answering back as quickly!!  : /

Tom


my updated code:

<!DOCTYPE html>
<html>
  <head>
  <title></title>
    <style type="text/css">
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script type="text/javascript">

        var i = 0;
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d'); 
        var one = {
            x: 300,
            y: 300,
            radius: 50,
            startAngle: 0,
            endAngle: Math.PI * 2,
            counterClockwise: false,
            color: '#aff',
            useletter: 'G'
        };

        var two = {
            x: 120,
            y: 120,
            radius: 20,
            startAngle: 0,
            endAngle: Math.PI * 2,
            counterClockwise: false,
            color: '#eee',
            useletter: 'T'
        };   

        _myCircleArray = [one,two];

        window.requestAnimFrame = (function (callback) {
            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
        })();

        function drawCircle(myCircle, context) {
            //context.save();
            context.beginPath();
            context.arc(myCircle.x, myCircle.y, myCircle.radius, myCircle.startAngle, myCircle.endAngle, myCircle.counterClockwise);
            context.fillStyle = myCircle.color;            
            context.fill();
            context.strokeStyle = '#000';
       //     context.closePath();
            context.stroke();
            //context.retore();
        }

        function drawText(myCircle, context, text) {
          //  context.save();
            context.beginPath();          
            context.fillStyle = '#000';          
            context.fill();
            context.font = "40px Georgia";
            context.fillText(myCircle.useletter, myCircle.x - 10, myCircle.y + 10);
            context.strokeStyle = '#000';
    //        context.closePath();
            context.stroke();           
          //  context.restore();
        }

//        function animate(myCircle, canvas, context, startTime) {           
//            var time = (new Date()).getTime() - startTime;           
//            var amplitude = 150;   
//            var period = 2000;           
//            var centerX = (canvas.width / 2) - ((myCircle.radius * 2) / 2);        
//            var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;            
//            myCircle.x = nextX;
//            context.clearRect(0, 0, canvas.width, canvas.height);
//            drawCircle(myCircle, context);
//            drawText(myCircle, context, "T");
//            requestAnimFrame(function () {
//                
//                if (i < 1) {
//                    i++;
//                }
//                else {
//                    i = 0;
//                }

//                var a = _myCircleArray[i];
//                animate(a, canvas, context, startTime);

//            });
//        }


        function animate(canvas, context, startTime) {
            var time = (new Date()).getTime() - startTime;
            context.clearRect(0, 0, canvas.width, canvas.height); // only clear once
            for (var a = 0; a < _myCircleArray.length; a++) {
                var myCircle = _myCircleArray[a];
                var amplitude = 150;
                var period = 2000;
                var centerX = (canvas.width / 2) - ((myCircle.radius * 2) / 2);
                var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
                myCircle.x = nextX;
                drawCircle(myCircle, context);
                drawText(myCircle, context, "T");
            }
            requestAnimFrame(function () {

                animate(canvas, context, startTime);

            });
        }

        // wait one second before starting animation
        setTimeout(function () {
            var startTime = (new Date()).getTime();
            animate(canvas, context, startTime);

        }, 1000);


       

       
        // wait one second before starting animation
        setTimeout(function () {
            var startTime = (new Date()).getTime();
            var a = _myCircleArray[i];
            animate(a, canvas, context, startTime);
           
        }, 1000);

    </script>
  </body>
</html> 

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.