背景
要求雷达图标签可点击并高亮显示被点击的标签,然后在雷达图右侧显示被点击标签项的详细数据。
分解后的任务如下:
- [ ] 1、标签可点击
- [ ] 2、标签点击后标签高亮显示
- [ ] 3、在雷达图右侧展示被点击标签对应的详细数据
功能实现
实现任务1
作为非专业前端人士在使用echarts图表库实现雷达图时,该库对于点击数据来说还是很容易实现的,代码如下(使用了echarts for react):
<ReactECharts option={calChartOption(systemIndicator)} onEvents={onEvents}/>
关键就是这个onEvents事件方法,代码示例如下:
const onEvents = {
click: (param: any) => {
if (systemIndicator && param.targetType === "axisName") {
let it = systemIndicator.category.find(c => c.name === IndicatorMap.get(param.name));
it && setIndicatorItems(it.indicatorItems);
setCategoryName(param.name.replace('评估', '维度'));
setIndicatorStyle(getIndicatorStyle(param.name))
}
},
}
实现任务2
对于雷达图的标签的样式是通过radar下的axisName统一指定,没有为每个标签提供单独的设置方法。统一设置方式如下代码所示:
radar: {
// shape: 'circle',
indicator: [
{ name: 'Sales', max: 6500 },
{ name: 'Administration', max: 16000 },
{ name: 'Information Technology', max: 30000 },
{ name: 'Customer Support', max: 38000 },
{ name: 'Development', max: 52000 },
{ name: 'Marketing', max: 25000 }
],
axisName :{
//formatter: '{value}',
color:'red',
fontSize:'14px',
fontWeight:'800'
}
},
这样的话就办法为某一个标签通过这种方式来实现显示高亮了,只好再去看看官方文档,发现了graphic这个标签,文档中是这样描述的
graphic
是原生图形元素组件。可以支持的图形元素包括:image, text, circle, sector, ring, polygon, polyline, rect, line, bezierCurve, arc, group,
既然官方没有提供为标签独立设置样式的方式,那么我们可以换一种思路,没错,我们自己“画”一个高亮样式,然后盖住下面原来的标签就可以实现这样的效果了。
So,现在开始一波骚操作~~~~
我们只需要往eCharts的option选项的graphic项添加需要绘制的内容即可。
{
graphic: [
{type: 'rect', ...}, {type: 'circle', ...}, ...
]
}
接下来,我们需要绘制两个内容:
1、一个白色的矩形,用于盖住下面的原标签(注意一下大小就好了)
2、绘制高亮(另外一种颜色)增大增粗的文字。(字体的样式而已)
下面给出绘制的完整代码,一个绘制的对象数组而已。
const getIndicatorStyle = (indicatorName: string): any => {
const graphics: any = [{
type: 'text',
left: 'center',
bottom: '10',
style: {
fill: '#999',
text: '注:点击各指标名称,查看详细数据',
font: '12px Microsoft YaHei'
}
}];
let x = "center";
let y = "0"
if (indicatorName === "label1") {
x = "315";
y = "96"
} else if (indicatorName === "label2") {
x = "10";
y = "96"
} else if (indicatorName === "label3") {
x = "50";
y = "240"
} else if (indicatorName === "label4") {
x = "270";
y = "240"
}
graphics.push({
type: 'group',
left: x,
top: y,
children: [
{
type: 'rect',
left: 'center',
top: 'middle',
shape: {
width: 80,
height: 30
},
style: {
fill: '#fff',
},
z: 5
},
{
type: 'text',
left: 'center',
top: 'middle',
style: {
fill: '#4486F8',
text: indicatorName,
fontSize: '16px',
fontWeight: '800'
},
z: 6
}
]
});
return graphics;
}
上面代码中的关键点有两处:
1、绘制的坐标位置
由于通过点击可以获得坐标点,但是绘制的位置计算起来也麻烦,干脆人工定位了。echarts提供了left、right、top、bottom 四个定位点,大家可以自行决定使用那一组来定位。
2、将下面的白色矩形和上面绘制的高亮文字成组
组合的好处,大家可以想想你做ppt时使用组合时带来的便利,这样组合内可以方便设置相对位置,组合外也能统一设置定位,是不是更方便? 最终实现效果如下:
实现任务3
这个就没啥好说的了,难不到众英雄....