Reputation: 4276
please I need your help , my question is If I want to draw donut chart using canvas , how can I do this with canvas and java script,
I wrote the following code but I do not know how to complete
<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>
now what I have to put inside the for loop.
Please help me all.
Upvotes: 2
Views: 7905
Reputation: 6126
You will want to render the parts like this:
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);
}
See it in action here:
Upvotes: 9