Use canvas to draw a pie chart and canvas pie chart
<! DOCTYPE html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> draw a pie chart. </Title>
<Style>
Canvas {
Border: 1px solid green;
}
</Style>
</Head>
<Body>
<! -- Draw a pie chart -->
<Canvas width = "500" height = "500" id = "canvas"> </canvas>
</Body>
<Script>
Var canvas = document. getElementById ('canvas ');
Var ctx = canvas. getContext ('2d ');
Function toAngle (radian ){
Return radian * 180/Math. PI;
}
Function toRadian (angle ){
Return angle * Math. PI/180;
}
/* Draw a pie chart */
Var colors = 'green, yellow, pink, blue, red, lightgreen, lightblu'. split (',');
Var text = 'html5, Canvas, Javascript, Css3, Ajax, framework encapsulation, jQuery and mobile web'. split (',');
Var x0 = canvas. width/2,
Y0 = canvas. height/2,
Radius = 100,
Start =-5,
Distance = 20,
Padding = 5,
Step = 360/colors. length;
For (var I = 0; I <colors. length; I ++ ){
Ctx. beginPath ();
Ctx. fillStyle = colors [I];
Ctx. moveTo (x0, y0 );
Ctx. arc (x0, y0, radius, toRadian (start), toRadian (start + = step ));
Ctx. fill ();
/* Draw a diagonal line */
Ctx. beginPath ();
Ctx. strokeStyle = colors [I];
Var x1 = x0 + (radius + distance) * Math. cos (toRadian (start-step/2 ))),
Y1 = y0 + (radius + distance) * Math. sin (toRadian (start-step/2 )));
Ctx. moveTo (x0, y0 );
Ctx. lineTo (x1, y1 );
Ctx. stroke ();
/* Write text */
Ctx. beginPath ();
Ctx. fillStyle = colors [I];
Var textX = x1,
TextY = y1;
If (start-step/2> 90 & start-step/2 <270 ){
Ctx. textAlign = 'right ';
TextX = textX-padding;
} Else {
Ctx. textAlign = 'left ';
TextX = textX + padding;
}
Ctx. fillText (text [I], textX, textY-padding/2 );
/* Draw a straight line */
Ctx. beginPath ();
Ctx. moveTo (x1, y1 );
// Calculate the text width
Var length = ctx. measureText (text [I]). width
If (start-step/2> 90 & start-step/2 <270 ){
X1 + =-2 * padding-length;
} Else {
X1 + = 2 * padding + length;
}
Ctx. lineTo (x1, y1 );
Ctx. stroke ();
/* Pie chart */
/* Ctx. beginPath ();
Ctx. fillStyle = colors [I];
Ctx. moveTo (x0, y0 );
Ctx. arc (x0, y0, radius, toRadian (start), toRadian (start + = step ));
Ctx. fill ();*/
}
</Script>
</Html>