Canvas How to - Draw animated loading spinner








Question

We would like to know how to draw animated loading spinner.

Answer


<!--  ww w .ja va  2 s .  c o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    (function() {
        setInterval(draw, 30);
        var degrees = 0.0;
        var offset = 8;
        function draw() {
            var canvas = document.getElementById('tutorial');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
                ctx.clearRect(0, 0, 16, 16);
                degrees += 0.10;
                ctx.save();
                ctx.translate(offset, offset);
                ctx.rotate(degrees);
                // Draw half open circle
                ctx.beginPath();
                ctx.lineWidth = 2;
                ctx.arc(8-offset , 8-offset, 6, 0, 1.75 * Math.PI);
                ctx.stroke();
                // Draw arrowhead
                ctx.lineWidth = 2;
                ctx.moveTo(13-offset , 1-offset);
                ctx.lineTo(9-offset , 5-offset);
                ctx.lineTo(13-offset , 5-offset);
                ctx.lineTo(13-offset , 1-offset);
                ctx.stroke();
                ctx.restore();
            }
        }
    })();
});//]]>  
</script>
</head>
<body>
  <CANVAS id="tutorial" width="16" height="16">
</body>
</html>

The code above is rendered as follows: