折线图之后又来饼状图啦~\(≧▽≦)/~啦啦啦
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="cv"></canvas>
<script>
var cv=document.getElementById("cv");
cv.style.border = "1px solid red";
cv.width = 600;
cv.height = 400; var ctx = cv.getContext("2d");
// 弧度转化为角度
function toAngle(radian) {
return radian / Math.PI * 180;
} // 角度转化为弧度
function toRadian(angle) {
return angle / 180 * Math.PI;
} //根据数据画饼
var data=[{
"value": .1,
"color": "purple",
"title": "社会招生"
},{
"value": .1,
"color": "rebeccapurple",
"title": "公务员"
},{
"value": .1,
"color": "red",
"title": "公开课"
},{
"value": .1,
"color": "rosybrown",
"title": "前端"
},{
"value": .2,
"color": "royalblue",
"title": "应届生"
},{
"value": .3,
"color": "saddlebrown",
"title": "程序员"
},{
"value": .1,
"color": "salmon",
"title": "老司机"
}];
var startAngle=-90, //饼图起始角度
x0=300, //圆心x的坐标
y0=200, //圆心y的坐标
radius=100, //圆的半径
step= 0, //定义扇形增加角度的变量
line=20; //画线的时候超出半径的一段线长 //画饼
for (var i = 0; i < data.length; i++) {
ctx.beginPath(); //开启新路径
step=data[i].value*360; //根据数据计算增加的角度
var lineAngle=startAngle+step/2; //计算线的角度
ctx.moveTo(x0,y0);
ctx.arc(x0,y0,radius,toRadian(startAngle),toRadian(startAngle+=step));
ctx.fillStyle=data[i].color;
ctx.fill();
ctx.beginPath();
//画线
//圆弧上的点坐标 (x0+r*Math.cos(toRadian(lineAngle/2)),y0+r*Math.sin(toRadian(linAngle/2)))
var x1=x0+(radius+line)*Math.cos(toRadian(lineAngle)),//圆弧上线与圆相交点的x坐标
y1=y0+(radius+line)*Math.sin(toRadian(lineAngle)),//圆弧上线与圆相交点的y坐标
//获取文本长度
textW=ctx.measureText(data[i].title).width,
linePadding=60;
ctx.moveTo(x0,y0);
ctx.lineTo(x1,y1);
ctx.strokeStyle=data[i].color;
ctx.stroke(); ctx.beginPath();
var textPadding=10; //文字与线之间的间距
ctx.moveTo(x1,y1);
//当圆弧x轴坐标大于圆心的x轴坐标,线向右画,linepadding为正值
if(x1>=x0){
ctx.lineTo(x1+linePadding,y1);
//绘制文字 //textpadding同理
ctx.fillText(data[i].title,x1+textPadding,y1-textPadding);
}else{
ctx.lineTo(x1-linePadding,y1);
//使左边的文字右对齐
ctx.textAlign="right";
ctx.fillText(data[i].title,x1-textPadding,y1-textPadding);
}
ctx.strokeStyle=data[i].color;
ctx.stroke();
} </script>
</body>
</html>
显示效果图