Canvas How to - Draw circle segments








Question

We would like to know how to draw circle segments.

Answer


<!--from   w  w w  .  j  a v a  2s. c o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    window.drawCircle = function(x, y){
        var can = document.getElementById('thecanvas'),
            ctx = can.getContext('2d'),
            segments = 10,
            currentSegment = 0,
            toRadians = function(deg){
                return ( Math.PI / 180 ) * deg;
            },
            getTick = function(num){
                var tick = toRadians(360) / segments;
                return tick * num;
            },
            segment = function(start, end){
                start = start || getTick(currentSegment);
                end = end || getTick(currentSegment + 1);
                ctx.beginPath();
                ctx.arc(x, y, 60, start, end);
                ctx.stroke();
                ctx.closePath();
            };
        can.width = window.innerWidth;
        can.height = window.innerHeight;
        ctx.lineWidth = 50;
        ctx.strokeStyle = 'rgba(0,0,0,0.5)';
        setTimeout(function render(){
            segment(getTick(currentSegment), getTick(currentSegment + 1));
            currentSegment += 1;
            if (currentSegment < segments){
                setTimeout(render, 250);
            } else {
                currentTick = 0;
            }
        }, 250);
    };
    drawCircle(150, 150);
}//]]>  
</script>
</head>
<body>
  <canvas id="thecanvas"></canvas>
</body>
</html>

The code above is rendered as follows: