build a double doughnut chart that spins when triggered - Javascript Canvas

Javascript examples for Canvas:Example

Description

build a double doughnut chart that spins when triggered

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/*from w  w  w.  java2s. c o  m*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.lineWidth=20;
    var PI=Math.PI;
    var rotation=0;
    var arcs=[];
    arcs.push({cx:150,cy:150,radius:100,startAngle:-45,endAngle:45,color:"blue"});
    arcs.push({cx:150,cy:150,radius:100,startAngle:45,endAngle:135,color:"red"});
    arcs.push({cx:150,cy:150,radius:100,startAngle:135,endAngle:225,color:"gold"});
    arcs.push({cx:150,cy:150,radius:100,startAngle:225,endAngle:315,color:"green"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:-43,endAngle:-2,color:"blue"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:0,endAngle:45,color:"blue"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:47,endAngle:88,color:"red"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:90,endAngle:135,color:"red"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:137,endAngle:180,color:"gold"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:182,endAngle:225,color:"gold"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:227,endAngle:272,color:"green"});
    arcs.push({cx:150,cy:150,radius:75,startAngle:275,endAngle:313,color:"green"});
    drawAll();
    function drawAll(){
        for(var i=0;i<arcs.length;i++){
            draw(arcs[i]);
        }
    }
    function draw(a){
        ctx.save();
        ctx.translate(a.cx,a.cy);
        ctx.rotate(rotation*PI/180);
        ctx.beginPath();
        ctx.arc(0,0,a.radius,a.startAngle*PI/180,a.endAngle*PI/180);
        ctx.strokeStyle=a.color;
        ctx.stroke();
        ctx.restore();
    }
    $("#rotate").click(function(){
        rotation+=90;
        drawAll();
    });
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <button id="rotate">Rotate</button> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials