设置legend的宽度和高度不生效,宽度和高度还是自适应的
可以设置legend的宽度和高度且生效
let categories = [{
name: _('在线'),
icon: 'image://' + LEGEND_ICON_URL[STATUS.online]
}, {
name: _('告警'),
icon: 'image://' + LEGEND_ICON_URL[STATUS.alarm]
}, {
name: _('离线'),
icon: 'image://' + LEGEND_ICON_URL[STATUS.offline]
}];
option = {
legend: {
show: true,
borderColor: '#E8E8E8',
borderWidth: 1,
borderRadius: 4,
shadowColor: 'rgba(0, 0, 0, 0.08)',
shadowBlur: 4,
padding: 20,
left: 40,
bottom: 50,
itemWidth: 6,
itemHeight: 6,
itemGap: 10,
width: 120,
height: 100,
orient: 'vertical',
data: categories
}
}
不生效指的是什么?
@pissang 就是设置的宽度、高度不起作用,比如设置200的宽度,实际还是自适应的宽度
我也遇到这个问题,在MacOS上,设置legen的宽、高和间隔之后,在Safari和Firefox上是生效的,但是在Chrome上,无论itemWidth、itemHeight和itemGap设置为多少,两个项之间的间隔还是非常大,而且图例项中的文字越多,彼此间隔越大:
Chrome效果:

Firefox效果:

@pissang 期望至少在chrome上各项之间的间隔能保持一致
我也遇到了这个问题
我也遇到这个问题了,如果设置了itemGap和itemWidth,也是图例文字越多间距越大,请问这是什么原因?大家是怎么解决的?我去掉itemWidth和itemGap这两个配置项,间距就是正常的,不会随文字多少变化。
我的没没有效果, 各位找到解决方法了吗/(ㄒoㄒ)/~~
我的没没有效果, 各位找到解决方法了吗/(ㄒoㄒ)/~~
木有。。
希望legend每一个item能设置宽度,并且超出宽度后能有省略号。文档里说用rich属性,试过了照样不行
在另一个 issue https://github.com/apache/incubator-echarts/issues/4200#issuecomment-252568649 里有人从源码里找到原因了:
- - 仔细看源码发现问题了, 是
orient="horizontal"的时候,只有width会起作用,height为auto;orient="vertical"的时候只有height会起作用,width为auto。
参考 SegmentFault 上的 一个回答,可以使用 rich + textStyle 强行实现固定宽度,不过目前还没试出来百分比宽度 = =
{
legend: [{
type: 'scroll',
orient: 'vertical',
left: '60%',
right: 0,
// width: '40%',
top: 0,
bottom: 0,
pageIconSize: 10,
pageButtonGap: 0,
icon: 'circle',
formatter: '{a|{name}}', // 按照文档的说法 `rich` 参数只有指定了 `formatter` 后才有效
textStyle: {
rich: {
a: {
width: 100
}
}
},
tooltip: {
show: true,
textStyle: {
fontSize: 12
}
},
}],
}
如果需要强行设置百分比宽度的话,一种很绕的方法就是手动计算,得到像素宽度 = =
下面是自己的实现代码片段,支持图表的 resize 更新。虽然代码是 React Hooks 的实现,不过思路应该是能看得出来的,监听 window 的 resize 事件,然后通过获取 ECharts 容器 DOM 的 offsetWidth 乘以比例,得到实际的像素宽度,最后调用 ECharts 实例的 setOptions() 方法更新。
const option = useRef();
const ref = useRef();
const getTextWidth = (size, defaultSize = 100) => {
let textWidth = defaultSize;
if (ref.current && ref.current.echartsElement) {
textWidth = size * ref.current.echartsElement.offsetWidth;
}
return textWidth;
};
const formatOptions = () => {
option.current = {
legend: [{
formatter: '{a|{name}}',
textStyle: {
rich: {
a: {
width: getTextWidth(0.4)
}
}
},
// 省略多余参数
}],
};
};
useEffect(() => {
const chart = ref.current;
if (!chart) {
return undefined;
}
const instance = chart.getEchartsInstance();
const resizeChartLegend = () => {
instance.setOption({
legend: [{
textStyle: {
rich: {
a: {
width: getTextWidth(0.4)
}
}
}
}]
});
};
window.addEventListener('resize', resizeChartLegend);
return () => {
window.removeEventListener('resize', resizeChartLegend);
};
}, [ref.current]);
useEffect(() => formatOptions(), [data]);
return (
<ReactEcharts option={option.current} ref={ref} style={{ height: '220px' }} />
);
Most helpful comment
希望legend每一个item能设置宽度,并且超出宽度后能有省略号。文档里说用rich属性,试过了照样不行