简单的函数:
/* * lists 数据数组 * r 半径 * line 线宽度 * */ function canvas(lists,r,line) { var canvass = document.getElementById('canvas'); var c = document.createElement('canvas'),h=canvass.clientHeight,w=canvass.clientWidth; c.width=w,c.height=h,s=0.2,es=0.2,point={x:w/2,y:h/2},c_point={}, canvass.appendChild(c) var ctx=c.getContext("2d"); if(lists.length<1) { ctx.fillText('暂时没有数据',point.x-35,point.y); return } var total=0,list2=[],total2=0,c_s for (var i =0;i<lists.length;i++){total+=parseInt(lists[i].value)} for (var i =0;i<lists.length;i++){ if(i!=lists.length-1){ c_s = parseInt(lists[i].value*100/total) total2+=c_s; list2.push(c_s) } } list2.push(100-total2); list2.forEach(function (v,i) { var p_x,p_y,l_x,t_x; ctx.beginPath();ctx.strokeStyle=lists[i].color;ctx.lineWidth=line;es=s+v*2/100 ctx.arc(point.x,point.y,r,s*Math.PI,es*Math.PI);ctx.stroke();ctx.beginPath(); c_point={x:point.x+Math.cos((s+es)*Math.PI/2)*90,y:Math.sin((s+es)*Math.PI/2)*90+point.y} ctx.moveTo(c_point.x,c_point.y) if(c_point.x<point.x){p_x=-5,l_x=-20,t_x=-85}else {p_x=5,l_x=30,t_x=35} if(c_point.y<point.y){p_y=-5}else {p_y=5} ctx.lineTo(c_point.x+p_x,c_point.y+p_y);ctx.lineTo(c_point.x+l_x,c_point.y+p_y);ctx.lineWidth=1;ctx.stroke(); ctx.beginPath();ctx.fillStyle=lists[i].color;ctx.arc(c_point.x+l_x,c_point.y+p_y,3,0,2*Math.PI);ctx.fill();ctx.fillStyle=lists[i].color; ctx.fillText(lists[i].name,c_point.x+t_x,c_point.y+p_y+4);s=es }) }
调用方法:
<div id="canvas" style="height: 400px;width: 400px;"></div>
var lists = [ {name:'县代贡献',value:50,color:'#6ED668'}, {name:'商户贡献',value:150,color:'#FCB747'}, {name:'业务员贡献',value:80,color:'#7680F5'}, {name:'用户贡献',value:100,color:'#4291F0'}, ] canvas(lists,75,30)
饼状图 :
直接把 线的宽度设置为 半径的两倍 既可以实现饼状图
代码仅供参考,具体功能可以自己扩展。
个人博客 :精华所在 https://gilea.cn/
http://www.cnblogs.com/jiebba 我的博客,来看吧!