<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas width="800" height="600" style="border: 1px solid gray;margin: 20px auto;display: block;"></canvas>
</body>
</html>
<script>
var PieChart= function () {
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.r=150;
this.outXian=20;
this.rectW=15;
this.rectY=10;
this.space = 20;
}
PieChart.prototype.init= function () {
this.bingTu(data);
}
PieChart.prototype.bingTu=function(data){
var angleList = this.angle(data);
var that=this;
var start=0;
angleList.forEach(function (item, i) {
var end=item.angle+start;
that.ctx.beginPath();
that.ctx.moveTo(that.x0,that.y0);
that.ctx.arc(that.x0,that.y0,that.r,start,end);
var color = that.ctx.fillStyle=that.random();
that.ctx.fill();
that.title(start,item.angle,color,item.title);
that.shuoMing(i,item.title,color);
start=end;
})
};
PieChart.prototype.title=function(start,angle,color,title){
var xie = this.r+this.outXian;
var Xbian=xie*Math.cos(start+angle/2);
var Ybian=xie*Math.sin(start+angle/2);
var outX=this.x0+Xbian;
var outY=this.y0+Ybian;
this.ctx.beginPath();
this.ctx.moveTo(this.x0,this.y0);
this.ctx.lineTo(outX,outY);
this.ctx.strokeStyle=color;
this.ctx.stroke();
this.ctx.font="14px 宋体";
var txtWidth=this.ctx.measureText(title).width;
if(outX>this.x0){
this.ctx.lineTo(outX+txtWidth,outY);
this.ctx.textAlign="left";
this.ctx.textBaseline="bottom";
this.ctx.fillText(title,outX,outY);
}else{
this.ctx.lineTo(outX-txtWidth,outY);
this.ctx.textAlign="right";
this.ctx.textBaseline="bottom";
this.ctx.fillText(title,outX,outY);
}
this.ctx.stroke();
};
PieChart.prototype.shuoMing=function(index,title,color){
this.ctx.fillStyle=color;
this.ctx.fillRect(this.space,this.space+index*(this.rectY+10),this.rectW,this.rectY);
this.ctx.textBaseline="top";
this.ctx.font="12px 黑体";
this.ctx.textAlign="left";
this.ctx.fillText(title,this.space+this.rectW+10,this.space+index*(this.rectY+10));
};
PieChart.prototype.angle=function(data){
var total=0;
data.forEach(function (item, i) {
total+=item.num;
});
data.forEach(function(item,i){
var angle=item.num/total*2*Math.PI;
item.angle=angle;
})
return data;
};
PieChart.prototype.random=function(){
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
return 'rgb('+r+','+g+','+b+')';
}
var data=[{title:"20以下",num:6},{title:"20-25",num:26},{title:"25-30",num:20},{title:"30-35",num:8}];
var pc=new PieChart();
pc.init();
</script>