<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="600" height="400" style="border: 1px solid #ccc"></canvas>
<script>
var PieChart = function () {
this.ctx = document.querySelector('canvas').getContext('2d');
this.x0 = this.ctx.canvas.width / 2;
this.y0 = this.ctx.canvas.height / 2;
this.radius = 150;
this.outLine = 20;
this.spaceX = 10;
this.spaceY=20;
this.smallW=30;
this.smallH=15;
}
PieChart.prototype.init = function () {
this.drawPie();
}
PieChart.prototype.drawPie = function () {
var angleList = this.drawAngle();
var start = 0;
angleList.forEach((item,i) =>{
var end = item.angle + start;
this.ctx.beginPath();
this.ctx.moveTo(this.x0,this.y0);
this.ctx.arc(this.x0, this.y0, this.radius, start, end);
this.ctx.fillStyle = this.randomColor();
this.ctx.fill();
this.drawTitle(start, item, this.ctx.fillStyle);
this.drawInfo(i, item.title, this.ctx.fillStyle)
start = end;
});
}
PieChart.prototype.drawTitle = function (start, item, color) {
var edge = this.radius + this.outLine;
var edgeX = edge * Math.cos(start + item.angle / 2);
var edgeY = edge * Math.sin(start + item.angle / 2);
var outX = this.x0 + edgeX;
var outY = this.y0 + edgeY;
this.ctx.beginPath();
this.ctx.moveTo(this.x0, this.y0);
this.ctx.lineTo(outX, outY);
this.ctx.strokeStyle = color;
this.ctx.stroke();
var align = outX > this.x0 ? 'left' : 'right';
this.ctx.font = "15px 微软雅黑";
this.ctx.textAlign = align;
this.ctx.baseline = 'bottom';
this.ctx.fillStyle = color;
this.ctx.fillText(item.title,outX,outY);
var textW = this.ctx.measureText(item.title).width;
this.ctx.moveTo(outX, outY);
outX = outX > this.x0 ? outX + textW : outX - textW;
this.ctx.lineTo(outX, outY);
this.ctx.stroke();
}
PieChart.prototype.drawInfo = function (index, text, color){
this.ctx.beginPath();
this.ctx.fillRect(this.spaceX, this.spaceY * (index+1), this.smallW, this.smallH);
this.ctx.font = "12px 微软雅黑";
this.ctx.fillStyle = color;
this.ctx.textAlign="left";
this.ctx.fillText(text,this.spaceX*2+this.smallW,this.spaceY * (index+1)+this.smallH);
}
PieChart.prototype.drawAngle = function () {
var total = 0;
data.forEach(function (item, index) {
total += Number(item.num);
})
data.forEach(function (item, index) {
var angle = Number(item.num) / total * Math.PI * 2;
item.angle = angle;
})
return data;
}
PieChart.prototype.randomColor = 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: 100},
{title: "20-25岁", num: 200},
{title: "25-30岁", num: 200},
{title: "30岁以上", num: 100},
];
var pieChart = new PieChart();
pieChart.init();
</script>
</body>
</html>