应用背景
这是拿到的美工图,首先在饼状图中间就有label ,显示的是“档案数”的一个占比,然后旁边显示每块扇形的“名称”、“数量”、“金额”等等属性,光使用echars的label是无法满足的,就需要使用到自定义的一个文本块。
翻来找去,终于在echarts的文档中找到一个关键组件【graphic】
graphic
是原生图形元素组件。可以支持的图形元素包括:
image, text, circle, sector, ring, polygon, polyline, rect, line, bezierCurve, arc, group,
使用中用到了两种 group、text
生成 graphic
- group 像一个容器组件,可以包含N个其他类型的组件,通过上面的图,我们可以分析得出,一共包含5段文字,也就是说,要使用一个group类型的组件,里面包含5个text文字组件,看下面代码。
先介绍下,下面用到的几个属性
1.left/top
描述怎么根据父元素进行定位。
『父元素』是指:如果是顶层元素,父元素是 echarts 图表容器。如果是 group 的子元素,父元素就是 group 元素。
2.children
只有 type=group 的组件才会有的属性,里面是一个数组类型子组件对象,在我这个例子中,就是5个text类型的组件
/**
生成 graphic 组件的方法
*/
function genterateGraphic(je=0,count=0,label,left){
const data = {
elements:[
{
type: 'group', //父组件
left:left, //参考echarts容器的定位
top:'30',
children:[
{
type: 'text', //扇形的名称
style:{
text:'{a|'+label+'}',
rich:{
a:{
fontSize: 14, //文字大小,很可惜不支持 color 属性,不然就可以分成3个子组件就搞定
}
}
},
top:0,
},
{
type: 'text',
style:{
text:'{a|档案数:}',
rich:{
a:{
fontSize: 12,
}
},
fill:'#ccc'
},
top:30,
},
{
type: 'text',
style:{
text:'{a|'+count+'}',
rich:{
a:{
fontSize: 14,
}
}
},
top:45,
},
{
type: 'text',
style:{
text:'金额:',
fill:'#ccc',
rich:{
a:{
fontSize: 14,
}
}
},
top:75
},
{
type: 'text',
style:{
text:'{a|'+je+'}',
rich:{
a:{
fontSize: 14,
}
}
},
top:90
}
]
}
]
}
return data;
}
使用echarts 实例绑定事件
this.pieChart = echarts.init(document.querySelector('.chartPie'),'light');//初始化echarts实例
const option = this.generatePieOption();
const graphic = this.genterateGraphic(111,2222,'xxx大队',textLeft);//生成graphic组件
option.graphic =graphic //将生成graphic组件赋值到 option 中
this.pieChart.setOption(option)//生成图表
const $this = this //解决 this 作用域的问题
const chartDom2 = document.querySelector(".chartPie") //获取echars 的父容器
/*
下面两句代码用于计算“graphic”组件生成的位置
*/
const chartWidth = chartDom2.offsetHeight
const textLeft = chartWidth *0.8+60;
//绑定图表的click事件
this.pieChart.on('click',function (params) {
const name = params.name; //获取到部门名称
//利用部门名称筛选出和对应的实体
const datas = $this.pieDatas.filter((data) => name == data.dept_name)
//根据筛选出来的对象,再次生成 Graphic 组件
const graphic = $this.genterateGraphic(datas[0].je,datas[0].c,params.name,textLeft);
$this.pieChart.setOption({graphic:graphic}) //更新图表
/*高亮指定的扇形区域*/
$this.pieChart.dispatchAction(
{
type:'pieToggleSelect',
dataIndex:params.dataIndex
}
)
})
以上就是echarts添加自定义文本块的核心代码……
最后实现的样子
PS:总算踏出了第一次,用键盘敲出了第一个字符,一方面为了自己学习加强影响,另一方面也希望能帮到在某个地方,正为这个问题苦恼的你!ლ(⌒▽⌒ლ)