echarts 动态冒泡排序柱状图 ,正在更换的两根柱子有不同的颜色,更换完以后变回默认颜色,从<!DOCTYPE html>开始>
时间: 2024-06-04 12:14:06 浏览: 150
echarts柱状图堆叠图动态排序
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts动态冒泡排序柱状图</title>
<!-- 引入 ECharts 文件 -->
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
</head>
<body>
<!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
<div id="chart" style="width: 600px;height:400px;"></div>
<script>
// 初始化 echarts 实例
var myChart = echarts.init(document.getElementById('chart'));
// 指定图表的配置项和数据
var option = {
title: {
text: '冒泡排序柱状图',
subtext: '数据来自数组',
left: 'center'
},
tooltip: {
trigger: 'axis',
formatter: '{b} : {c}',
},
xAxis: {
type: 'category',
data: []
},
yAxis: {
type: 'value'
},
series: [{
name: '数值',
type: 'bar',
data: [],
itemStyle: {
normal: {
color: function(params) {
// 根据数值不同设置柱子颜色
var colorList = ['#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
'#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
'#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'];
return colorList[params.dataIndex % colorList.length];
}
}
}
}]
};
// 设置数据
var data = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
option.xAxis.data = data;
option.series[0].data = data;
// 渲染图表
myChart.setOption(option);
// 冒泡排序
var i = 0, j = 0, len = data.length;
var interval = setInterval(function() {
if (i < len) {
if (j < len - i - 1) {
// 比较相邻元素,交换位置
if (data[j] > data[j+1]) {
// 更换的两根柱子有不同的颜色
var colorList = ['#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
'#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
'#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'];
option.series[0].itemStyle.normal.color = [colorList[j], colorList[j+1]];
myChart.setOption(option);
// 交换位置
var temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
// 更换完以后变回默认颜色
option.series[0].itemStyle.normal.color = function(params) {
var colorList = ['#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
'#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
'#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'];
return colorList[params.dataIndex % colorList.length];
};
myChart.setOption(option);
}
j++;
} else {
i++;
j = 0;
}
} else {
clearInterval(interval);
}
}, 500);
</script>
</body>
</html>
阅读全文