We help IT Professionals succeed at work.

HTML5 - flickering animation

Tom Knowlton
Tom Knowlton asked
on
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

Comment
Watch Question

Software Engineer
Commented:
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

Tom KnowltonWeb developer

Author

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