html5中canvas图表实现柱状图的示例

2020-04-25 08:07:42易采站长站整理

if(ctx.isPointInPath(pos.x*2,pos.y*2)){
//清空后再重新绘制透明度为0.5的图形
ctx.clearRect(that.padding+item.x,that.H-that.padding-item.h,item.w,item.h);
ctx.globalAlpha=0.5;
ctx.fill();
canvas.style.cursor='pointer';
that.showInfo(pos,item);
ctx.restore();
break;
}
canvas.style.cursor='default';
that.tip.style.display='none';
ctx.globalAlpha=1;
ctx.fill();
ctx.restore();
}

},false);

this.canvas.addEventListener('mousedown',function(e){
e.preventDefault();
var box=canvas.getBoundingClientRect();
var pos = {
x:e.clientX-box.left,
y:e.clientY-box.top
};
for(var i=0,item,len=that.legend.length;i<len;i++){
item=that.legend[i];
roundRect(ctx,item.x,item.y,item.w,item.h,item.r);
// 因为缩小了一倍,所以坐标要*2
if(ctx.isPointInPath(pos.x*2,pos.y*2)){
that.series[i].hide=!that.series[i].hide;
that.animateArr.length=0;
that.draw();
break;
}
}

},false);
}
//显示数据
showInfo(pos,obj){
var txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',obj.num):obj.num;
var box=this.canvas.getBoundingClientRect();
var con=this.container.getBoundingClientRect();
this.tip.innerHTML = '<p>'+obj.name+':'+txt+'</p>';
this.tip.style.left=(pos.x+(box.left-con.left)+10)+'px';
this.tip.style.top=(pos.y+(box.top-con.top)+10)+'px';
this.tip.style.display='block';
}

总结

这里完成的只是个基本的效果,其实还有很多地方要进一步优化,比如响应式的支持,移动端的支持,动画的效果,多y轴的支持,显示内容的效果,同时支持折线功能等。