本篇文章主要介绍了"Canvas html5中canvas图表实现柱状图的示例",主要涉及到Canvas方面的内容,对于HTMLjrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
前几天用到了图表库,其中百度的ECharts,感觉做得最好,看它默认用的是canvas,canvas图表在处理大数据方面比svg要好。那我也用canvas来实现...
showData(xl,xs,max){
//画数据
var that=this,
ctx=this.ctx,
ydis=this.H-this.padding*2-this.paddingTop,
sl=this.series.filter(s=>!s.hide).length,
sp=Math.max(Math.pow(10-sl,2)/3-4,5),
w=(xs-sp*(sl+1))/sl,
h,x,index=0;
that.animateArr.length=0;
// 展开数据项,填入动画队列
for(var i=0,item,len=this.series.length;i{
h=d/max*ydis;
x=xs*j+w*index+sp*(index+1);
that.animateArr.push({
index:i,
name:item.name,
num:d,
x:Math.round(x),
y:1,
w:Math.round(w),
h:Math.floor(h+2),
vy:Math.max(300,Math.floor(h*2))/100,
color:item.color
});
});
index++;
}
this.animate();
}
执行动画
执行动画也没啥好说的,里面就是个自执行闭包函数。动画原理就是给y轴依次累加速度值vy。但记得当队列执行完动画后,要停止它,所以有个isStop的标志,每次执行完队列的时候就判断。
animate(){
var that=this,
ctx=this.ctx,
isStop=true;
(function run(){
isStop=true;
for(var i=0,item;i=0.1){
item.y=item.h;
} else {
item.y+=item.vy;
}
if(item.y
绑定事件
事件一:mousemove的时候,看看鼠标位置是不是处于分组标签还是数据项上,绘制路径后调用isPointInPath(x,y),true则canvas.style.cursor='pointer';如果是数据项的话,还要给把该柱形重新绘制,设置透明度,区分出来。还需要把内容显示出来,这里是一个相对父容器container为绝对定位的div,初始化的时候已经建立为tip属性了。我们把显示部分封装成showInfo方法。