把legend图例设置背景色或者背景图
把legend设置成Arr,在每个legend对象里面背景颜色设置图片或者颜色值,backgroudColor:{image:(background.png)}。
设置完成后,legend会重叠在一起,使用top设置距离顶部的高度,把重叠的legend分开显示。
关于文字的显示,使用自定义富文本样式textStyle.rich,通过padding设置文本左右显示,经测试文本字数不能超过7个字,超过就视觉上宽度是不一样的。
demo图:
核心代
码:
top: `${90 - (i + 1) * 10}%`,
data: [
https://img-mid.csdnimg.cn/release/static/image/mid/ask/439372854686186.png "#left")
{
name: item.name,
icon: 'rect',
borderWidth: 0
}
],
backgroundColor:{
image: './legend_bg.png'
} ,
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 300px;
height: 150px;
background-color: #0e1842;
clip-path: polygon(12px 0, calc(100% - 12px) 0, 100% 12px, 100% calc(100% - 12px), calc(100% - 12px) 100%, 12px 100%, 0 calc(100% - 12px), 0 12px);
}
#echarts01 {
background-size: cover;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.2/echarts.common.js"></script>
</head>
<body>
<div id="echarts01" style="width: 800px;height: 400px;background-color: #0e1842;"></div>
<script>
var myChart = echarts.init(document.getElementById('echarts01'));
const data = [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
const colorArr = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
const legendArr = []
data.forEach((item, i) => {
legendArr.push({
selectedMode: false,
type: 'plain',
orient: 'vertical',
right: 10,
itemGap: 12,
itemWidth: 10,
itemHeight: 10,
top: `${90 - (i + 1) * 10}%`,
data: [
{
name: item.name,
icon: 'rect',
borderWidth: 0
}
],
padding: [2, 2, 0, 2],
backgroundColor:{
image: './legend_bg.png'
} ,
formatter: (name) => {
console.log(data[i].value);
name = name.length>6? name.substring(0,6)+'...':name
return `{name|${name}} {bfb|${data[i].value}%}`
},
textStyle: {
color: '#545659',
fontSize: 14,
fontFamily: '微软雅黑',
rich: {
name: {
padding: [4, 4],
color: '#fff',
align: 'left',
backgroundColor: 'transparent'
},
bfb: {
fontSize: 12,
padding: [4, -100, 0, 0],
align: 'right',
color: '#fff',
backgroundColor: 'transparent'
}
}
},
})
})
option = {
title: {
text: 'Referer of a Website',
subtext: 'Fake Data',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: legendArr,
series: [
{
type: 'pie',
radius: '50%',
data: data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
myChart.setOption(option);
</script>
</body>
</html>