效果:
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>饼状图</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script> (function () {
var data = [{
"value":"0.4",
"color":"red",
"name":"JAVA"
},{
"value":"0.3",
"color":"green",
"name":"PYTHON"
},{
"value":"0.2",
"color":"blue",
"name":"C++"
},{
"value":"0.1",
"color":"grey",
"name":"PHP"
}];
var canvas = document.getElementById("canvas");
//设置宽高不从css中设置
canvas.width = 600;//设置canvas宽
canvas.height = 600;//设置canvas高
canvas.style.border = "1px solid red";
//获取上下文
var ctx = canvas.getContext("2d");
//画图
var x0 = 300,y0 = 300;//圆心
var x,y;//文字放置位置
var radius = 100;
var tempAngle = -90;//画圆的起始角度
for(var i = 0;i<data.length;i++){
var startAngle = tempAngle*Math.PI/180;//起始弧度
var angle = data[i].value*360;
var endAngle = (tempAngle+angle)*Math.PI/180;//结束弧度
var textAngle = tempAngle + 0.5*angle;//文字放的角度
x = x0 + Math.cos(textAngle*Math.PI/180)*(radius+20);//文字放的X轴
y = y0 + Math.sin(textAngle*Math.PI/180)*(radius+20);//文字放的Y轴
//如果文字在圆形的左侧,那么让文字 对齐方式为 文字结尾对齐当前坐标。
if( textAngle > 90 && textAngle < 270 ) {
ctx.textAlign = 'end';
}
var text = data[i].name + " "+ data[i].value*100+"%";
ctx.fillText(text,x,y);
ctx.beginPath();
ctx.moveTo(x0,y0);
ctx.fillStyle = data[i].color;
ctx.arc(x0,y0,radius,startAngle,endAngle);
ctx.fill();
tempAngle += angle;
}
}());
</script>
</body>
</html>