如何使用画布绘制圆环图?

时间:2014-05-14 10:26:06

标签: javascript html5 canvas

请我需要你的帮助,我的问题是如果我想用画布绘制圆环图,我怎么能用canvas和java脚本来做这个呢,

我写了以下代码,但我不知道如何完成

<body>

    <canvas id="chart" width="500" height="500" style="background-color:black">  </canvas>

    <script type="text/javascript">

        var canvas  = document.getElementById("chart");
        var chart = canvas.getContext("2d");

        function drawdountChart(canvas)
        {

            this.x , this.y , this.radius , this.lineWidth , this.strockStyle , this.from , this.to = null;
            this.set = function( x, y, radius, from, to, lineWidth, strockStyle)
            {
                this.x = x;
                this.y = y;
                this.radius = radius;
                this.from=from;
                this.to= to;
                this.lineWidth = lineWidth;
                this.strockStyle = strockStyle; 
            }

            this.draw = function(data)
            {
                canvas.beginPath();
                canvas.lineWidth = this.lineWidth;
                canvas.strokeStyle = this.strockStyle;
                canvas.arc(this.x , this.y , this.radius , this.from , this.to);
                canvas.stroke();
                var numberOfParts = data.numberOfParts;
                var parts = data.parts.pt;
                var colors = data.colors.cs;
               for(var i = 0; i<numberOfParts; i++)
               {

               }
            }
        }
        var data = 
            {
                numberOfParts: 4,
                parts:{"pt": [20 , 30 , 25 , 25]},//percentage of each part
                colors:{"cs": ["red", "green", "blue", "yellow" ]}//color of each part
            };

        var drawDount = new drawdountChart(chart);
        drawDount.set(150, 150, 100, 0, Math.PI*2, 30, "#FFF");
        drawDount.draw(data);



    </script>


</body>

现在我必须把它放在for循环中。

请帮助我。

1 个答案:

答案 0 :(得分:5)

您需要渲染这样的部分:

var df = 0; //keep track of how far round the donut we are.

for(var i = 0; i<numberOfParts; i++) {
  canvas.beginPath();
  canvas.strokeStyle = colors[i]; // get the color
  // Calculate the % of a circle (2PI) to arc
  canvas.arc(this.x, this.y, this.radius, df, df + (Math.PI * 2) * (parts[i] / 100)); 
  canvas.stroke();
  // Update our progress around the donut so we know where to draw the next part
  df += (Math.PI * 2) * (parts[i] / 100);
}

请在此处查看:

http://jsfiddle.net/RgLAU/1/