echarts 饼状图 设置同色系
程序员文章站
2022-07-14 10:02:43
...
echarts 饼状图 设置同色系
今天了解echats的时候发现饼状图给的颜色是随机的,虽然可以设置color来自定义,但是当我数据不确定的时候要怎么渲染出同色系的呢。我自己写了个小demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./echarts.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
</body>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
var colorlist = ['rgb(220,20,60)',
'rgb(0,0,255)',
'rgb(0,128,0)',
]
var datalist = []
var data1 = [{
value: 335,
name: '直达',
selected: true
}, {
value: 679,
name: '营销广告'
}, {
value: 1548,
name: '搜索引擎'
}]
var data2 = [{
value: 335,
name: '直达1'
}]
var data3 = [{
value: 310,
name: '邮件营销'
}, {
value: 234,
name: '联盟广告'
}, {
value: 135,
name: '视频广告'
}]
var data4 = [{
value: 1048,
name: '百度'
}, {
value: 251,
name: '谷歌'
}, {
value: 147,
name: '必应'
}, {
value: 102,
name: '其他'
}]
var data5 = []
maplist(data2)
maplist(data3)
maplist(data4)
var num1 = data1.length
var num2 = data2.length
var num3 = data3.length
var num4 = data4.length
var color1 = colorlist[0]
var color2 = colorlist[1]
var color3 = colorlist[2]
mapcolor(num2, color1)
mapcolor(num3, color2)
mapcolor(num4, color3)
getdata(data1)
getdata(data2)
getdata(data3)
getdata(data4)
//下面这个是将rgb变成rgba并且设置透明度
function mapcolor(num, mycolor) {
for (var i = 1; i <= num; i++) {
var opc = (1 / num) * i;
var color = mycolor.split("(")[0] + "a(" + mycolor.split("(")[1]
color = color.split(")")[0] + "," + opc + ")"
colorlist.push(color)
}
}
function getdata(list) {
list.map(item => {
datalist.push(item.name)
})
}
function maplist(list) {
list.map(item => {
data5.push(item)
})
}
// 指定图表的配置项和数据
var option = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: datalist
},
color: colorlist,
series: [{
name: '访问来源',
type: 'pie',
selectedMode: 'single',
radius: [0, '30%'],
label: {
position: 'inner'
},
labelLine: {
show: false
},
data: data1
}, {
name: '访问来源',
type: 'pie',
radius: ['40%', '55%'],
label: {
formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ',
backgroundColor: '#eee',
borderColor: '#aaa',
borderWidth: 1,
borderRadius: 4,
// shadowBlur:3,
// shadowOffsetX: 2,
// shadowOffsetY: 2,
// shadowColor: '#999',
// padding: [0, 7],
rich: {
a: {
color: '#999',
lineHeight: 22,
align: 'center'
},
// abg: {
// backgroundColor: '#333',
// width: '100%',
// align: 'right',
// height: 22,
// borderRadius: [4, 4, 0, 0]
// },
hr: {
borderColor: '#aaa',
width: '100%',
borderWidth: 0.5,
height: 0
},
b: {
fontSize: 16,
lineHeight: 33
},
per: {
color: '#eee',
backgroundColor: '#334455',
padding: [2, 4],
borderRadius: 2
}
}
},
data: data5
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</html>
效果图如下: