1.在HTML中引入Canvas标签
<canvas class="pie-chart" width="850" height="500" ></canvas>
2.引入单独的js文件
let PieChart = function(selector, options){
let canvas = "string" === typeof selector ? document.querySelector(selector) : null;
if(canvas === null) return false;
let defaultOptions = {
radius: 200,
legendParams:{ //图例参数
font: '24px Arial', //图例字体属性
x: 30, //图例x轴坐标
y: 30, //图例y轴坐标
margin: 50, //图例间距
width: 40, //图例宽度
height: 24 //图例高度
}
}
this.context = canvas.getContext('2d'); //获取context环境
this.width = canvas.getAttribute("width") || 300;
this.height = canvas.getAttribute("height") || 300;
this.options = Object.assign(defaultOptions,options); //合并参数
}
PieChart.prototype.load = function(data){
data.forEach(item => this.count? this.count += item.value : this.count = item.value);
this.data = data;
return this;
}
PieChart.prototype.render = function(){
let _generateLegend = (item,index) =>{
this.context.fillRect( //绘制图例图标
this.options.legendParams.x,
this.options.legendParams.y + index*this.options.legendParams.margin,
this.options.legendParams.width,
this.options.legendParams.height
)
this.context.font = this.options.legendParams.font
this.context.fillText(//绘制图例文字
item.title,
this.options.legendParams.y + this.options.legendParams.margin,
(index + 1) * this.options.legendParams.margin
)
}
let temparc = 0;
this.data.forEach((item,index)=>{//遍历绘制饼图扇形区域
item.color = `#${('00000' + (Math.random()*0x1000000<<0).toString(16)).substr(-6)}`;
this.context.beginPath();
this.context.moveTo(this.width / 2,this.height / 2);
let startarc = temparc,endarc = startarc + (item.value / this.count) * Math.PI * 2;
this.context.arc( //饼图弧形区域
this.width / 2, //圆中心x坐标
this.height / 2,//圆中心y坐标
this.options.radius,//饼图半径
startarc, //开始角度
endarc,//结束角度
false
);
this.context.closePath();
this.context.fillStyle = item.color;
this.context.fill();
temparc = endarc;
if(this.options.legend){ //是否需要绘制图例
_generateLegend(item,index)
}
})
return this;
}
3.在script标签中声明数据后使用
const data = [
{title: "大米",value: 1024},
{title: "肉类",value: 512},
{title: "零食",value: 256},
{title: "蔬菜",value: 920},
]
let pie = new PieChart('.pie-chart',{legend: true});
pie.load(data).render();
效果
