要求:根据数据绘制饼状图
效果图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="600" height="600" style="border:1px solid green"></canvas>
<script>
var data=[
{title:"20岁以下",num:6},
{title:"20-25岁以下",num:20},
{title:"25-30岁以下",num:28},
{title:"30-40岁以下",num:16}
]
function pieChart(){
this.ctx=document.querySelector("canvas").getContext("2d");
this.w=this.ctx.canvas.width;
this.h=this.ctx.canvas.height;
// 圆心
this.x0=this.w/2+60;
this.y0=this.h/2;
this.radius=150;
this.outline=20;
}
pieChart.prototype.init=function(){
this.drawPie();
}
// 画图
pieChart.prototype.drawPie=function(){
this.drawAngle();
var angle1=0;
data.forEach(function(item,index){
var color="#";
for(var j=0;j<6;j++){
color+=Math.floor(Math.random()*10);
}
this.drawTitle(angle1,item.angle,color,item.title);
this.drawDesc(index,color,item.title);
this.ctx.beginPath();
this.ctx.moveTo(this.x0,this.y0);
this.ctx.arc(this.x0,this.y0,this.radius,angle1,angle1+item.angle);
this.ctx.fillStyle=color;
this.ctx.fill();
angle1+=item.angle;
}.bind(this))
}
//写标题
pieChart.prototype.drawTitle=function(start,angle,color,title){
//确定由圆心伸出去的点
//确定伸出去的长度 长度即斜边=半径健身出去的长度
//对边=斜边*sin(角度) y轴方向
//邻边=斜边*cos(角度) x轴方向
//计算伸出去点的横坐标
//1.斜边的长度
var edge=this.radius+this.outline;
//2.x轴方向的直角边
var edgeX=edge*Math.cos(start+angle/2);
var edgeY=edge*Math.sin(start+angle/2);
//3.横纵坐标
var outX=this.x0+edgeX;
var outY=this.y0+edgeY;
//4.画线
this.ctx.beginPath();
this.ctx.moveTo(this.x0,this.y0);
this.ctx.lineTo(outX,outY);
this.ctx.strokeStyle=color;
this.ctx.stroke();
//文字和下划线
//需要判断线的方向,根据x0来判断
this.ctx.font="14px 微软雅黑";
//先获取文字的宽度
var textWidth=this.ctx.measureText(title).width;
if(outX>this.x0){
this.ctx.textAlign="left";
this.ctx.lineTo(outX+textWidth,outY);
}else{
this.ctx.textAlign="right";
this.ctx.lineTo(outX-textWidth,outY);
}
this.ctx.stroke();
this.ctx.baseLine="bottom";
this.ctx.fillStyle=color;
this.ctx.fillText(title,outX,outY);
}
//标题说明
pieChart.prototype.drawDesc=function(index,color,title){
var w=40;
var h=25;
var space=15;
this.ctx.beginPath();
this.ctx.fillStyle=color;
this.ctx.fillRect(h,(space+h)*(index+0.5),w,h);
this.ctx.font="14px 微软雅黑";
this.ctx.textAlign="left";
this.ctx.baseLine="bottom";
this.ctx.fillText(title,h+w+space,(space+h)*(index+0.5)+h);
}
pieChart.prototype.drawAngle=function(){
var total=0;
data.forEach(function(item,i){
total+=item.num;
})
data.forEach(function(item,i){
var angle=Math.PI*2*(item.num/total);
item.angle=angle;
})
return data;
}
var pieChart=new pieChart();
pieChart.init();
</script>
</body>
</html>