效果图
HTML代码
<!DOCTYPE html>
<html style="height: 100%">
<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>echarts</title>
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5.2.2/dist/echarts.min.js"></script>
<script src="resources/data.js"></script>
<script src="answer/answer.js"></script>
<script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
var option;
answer.initEcharts(examData);
if (option && typeof option === 'object') {
myChart.setOption(option);
}
</script>
</body>
</html>
相关配置代码
resources/data.js
let answer = {
formatRich: function(data) {
let result = {};
data.forEach(item => {
result[item.i18n] = {
color: 'transparent',
backgroundColor: {
image: `nationalFlag/${item.i18n}.jpg` //标签图片路径
},
width: 53,
height: 35,
align: 'center',
}
})
return result;
},
initEcharts: function(initData) {
let data = initData.sort((a, b) => {
return a.value - b.value
});
let rich = this.formatRich(data); //富文本
option = {
backgroundColor: '#000',
grid: { // 调整柱状图在容器中的位置
left: '4%',
right: '10%',
bottom: '10%',
top: '10%',
containLabel: true
},
tooltip: {// 数据提示
trigger: 'axis',
axisPointer: {
type: 'none'
},
formatter: function(params) {
return params[0].name + ' : ' + params[0].value
}
},
xAxis: { //X轴配置
show: false,
type: 'value'
},
yAxis: [{ //Y轴
type: 'category',
interval: 0,
axisLabel: {
show: true,
textStyle: {
color: '#fff',
},
rich: rich,
formatter: (res) => { // 自定义文本格式
let result = data.find(item => {
if (item.name == res) {
return item
}
})
return [
`{${result.i18n}|${result.i18n}}` + ' ' + res
].join('\n')
}
},
splitLine: {
show: false
},
axisTick: {
show: false
},
axisLine: {
show: false
},
data: data.map(item => {
return item.name
})
}],
series: [{
type: 'bar',
zlevel: 1,
itemStyle: {
normal: {
barBorderRadius: 30, //圆角柱体
color: (res) => {
if (data.length - res.dataIndex > 3) {
return new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
offset: 1,
color: 'rgb(46,200,207,1)'
}, {
offset: 0,
color: 'rgb(46,0,207,1)'
}])
} else {
return new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
offset: 1,
color: 'rgb(255,0,0,1)'
}, {
offset: 0,
color: 'rgb(255,100,0,1)'
}])
}
}
},
},
barWidth: 20,
data: data.map(item => {
return item.value
})
}],
dataZoom: [{ //右侧缩放控件
type: 'slider',
orient: 'vertical',
showDataShadow: false,
right: 50,
}]
};
}
}
数据
answer/answer.js
let examData = [
{
name : '中国',
i18n: 'China',
value : 100
},{
name : '英国',
i18n: 'Britain',
value : 40
},{
name : '日本',
i18n: 'Japan',
value : 20
},{
name : '印度',
i18n: 'India',
value : 20
},{
name : '法国',
i18n: 'France',
value : 60
},{
name : '韩国',
i18n: 'Korea',
value : 20
},{
name : '美国',
i18n: 'America',
value : 80
}
]
图片资源自行更改替换