<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> body{ background-color: #000; } canvas{ border: 1px solid #000; background-color: #fff; } </style> </head> <body> <canvas></canvas> </body> <script> var canvas=document.getElementById('canvas') ctx=canvas.getContext('2d'); /*获取画布的宽高*/ var w=canvas.width h=canvas.height; /*统计及时通讯工具的使用情况*/ var data={ title:'统计及时通讯工具的使用情况', list:[ { name: 'QQ', value: 500 }, { name: 'wechat', value: 600 }, { name: 'feiQ', value: 50 }, { name: 'momo', value: 200 }, { name: 'tantan', value: 300 }, { name: 'YY', value: 150 }, { name: 'DingDing', value: 100 } ] }; /*颜色*/ var colors = 'darkolivegreen,darkorange,darkorchid,darkred,darksalmon,darkseagreen,darkslateblue,darkslategray'.split( ',' ); function draw(){ /*原点*/ var x0=w/ 2, y0=h/ 2, r=160; /*起点是-90° 终点暂定*/ var start= -Math.PI/ 2, end; var list=data.list; /*统计数据的总和*/ var sum=0; list.forEach(function(ele){ sum+=ele.value; }) /*求出每个通讯工具占圆的多少弧度*/ list.forEach(function(ele){ ele.angle=ele.value/sum*2*Math.PI; }) /*数据线的长度 比半径多出16*/ var lineLength=r+16; /*开始画饼图*/ list.forEach(function(ele,i){ /*终止弧度是开始弧度加每个部分占圆的弧度*/ end=start+ele.angle; console.log(end); ctx.beginPath(); ctx.moveTo(x0,y0); ctx.arc(x0,y0,r,start,end); ctx.fillStyle=ctx.strokeStyle=colors[i]; ctx.fill(); /*绘制数据的线*/ /*线的弧度*/ var lineAngle=start+ele.angle/2; /*数据的线的末端和文字是向左还是向右的判断 西边向左,东边向右*/ var linedirction=-16; if(lineAngle>-Math.PI/2 && lineAngle<Math.PI/2){ linedirction=-linedirction;; } /*求出线的终止位置*/ var lineX=x0+lineLength*Math.cos(lineAngle), lineY=y0+lineLength*Math.sin(lineAngle); ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(lineX,lineY); ctx.lineTo(lineX+linedirction,lineY); ctx.stroke(); /*绘制文字*/ ctx.font='12px simsum'; ctx.textAlign=align; ctx.textBaseline='bottom'; ctx.fillText(' '+ele.name+': '+ele.value+' ',lineX+linedirction,lineY); ctx.textBaseline='top'; ctx.fillText(' percent: '+(ele.value/sum*100).toFixed(2)+'% ',lineX+linedirction,lineY); /*把上一次的终止弧度作为下一次的开始弧度*/ start=end; }) /*绘制标题*/ ctx.font='30px simsum'; ctx.fillStyle='#000'; ctx.textAlign='center'; ctx.fillText(data.title,x0,0+16); } draw(); </script> </html>