最近加了一个前端群 发现前端很精彩 学着花了个图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘图</title>
</head>
<body>
<canvas id="canvas" width="600px" height="500px" style="border: 1px slategray solid;">
你的浏览器不支持canvas 请升级到最新版本
</canvas>
<a id="downCanvas" href="#">下载</a>
</body>
<script type="application/javascript">
var canvas = document.querySelector("#canvas");
var context = canvas.getContext("2d");
function Pie(){
this.width =canvas.width;
this.height = canvas.height;
this.x = this.width/2;
this.y = this.height/2;
this.r = Math.min(this.x,this.y)-120;
/**
* 绘制图形
*/
this.draw = function (centext,param) {
//移动到指定点
centext.moveTo(this.x,this.y);
//总人数
var sum = 0;
param.forEach(function (item,i) {
sum+=item.count;
});
param.forEach(function (item,i) {
item.rate = item.count/sum*2*Math.PI;
});
console.log(param);
//绘制饼图
var start = 0;
for (var k = 0; k<param.length;k++){
//开始绘制
context.beginPath();
context.moveTo(this.x,this.y);
//获取颜色
var colorStr = this.color();
context.fillStyle = colorStr;
//x轴坐标 y轴坐标 半径 其实位置 结束位置 是否逆时针旋转
context.arc(this.x,this.y,this.r,start,start+param[k].rate,false);
start+=param[k].rate;
param[k].color=colorStr;
//填充
context.fill();
}
//绘制颜色标记
param.forEach(function (it,i) {
context.moveTo(20,20*i);
context.beginPath();
context.fillStyle =it.color;
context.fillRect(20,20*i,40,20);
});
//绘制注释
param.forEach(function (it,i) {
context.moveTo(70,20*i);
context.beginPath();
context.fillStyle =it.color;
context.fillText(it.sex,70,20*i+10,20);
});
};
this.color = function(){
return "rgb("+Math.floor(256*Math.random())+","+Math.floor(256*Math.random())+","+Math.floor(256*Math.random())+")";
}
}
//初始化
var pie = new Pie();
//绘制饼图
pie.draw(context,[{"sex":"男","count":2},{"sex":"女","count":4},{"sex":"未知","count":3}]);
//下载饼图功能
var element = document.querySelector("#downCanvas");
var imageData = canvas.toDataURL("png");
var s = imageData.replace("image/png","image/octet-stream");
element.href = s;
element.download = "成员性别统计图.png";
</script>
</html>
效果