这里通过组合 color回调函数 和 graphic组件 实现需求,以下是完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>智能速度仪表盘</title>
<script src="https://cdn.staticfile.org/echarts/5.4.0/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:500px;"></div>
<script>
var myChart = echarts.init(document.getElementById('main'));
// 动态配置生成器
function getOption(speed) {
return {
graphic: [{
id: 'warning',
type: 'image',
right: 'center',
top: '35%',
style: {
image: 'https://img.icons8.com/fluency/48/high-priority.png', // 警告图标URL
width: 40,
height: 40,
opacity: speed > 120 ? 1 : 0 // 动态透明度
},
z: 100
}],
series: [{
type: 'gauge',
min: 0,
max: 200,
center: ['50%', '55%'],
axisLine: {
lineStyle: {
color: [
[0.3, '#4dabf7'], // 0-60
[0.6, '#69db7c'], // 60-120
[1, '#ff6b6b'] // 120-200
],
width: 20
}
},
pointer: {
itemStyle: {
color: (function() { // 动态指针颜色
if (speed < 60) return '#4dabf7';
if (speed < 120) return '#69db7c';
return '#ff6b6b';
})()
},
length: '60%',
width: 6
},
detail: {
fontSize: 30,
formatter: '{value} km/h',
color: (function() { // 动态数值颜色
if (speed < 60) return '#4dabf7';
if (speed < 120) return '#69db7c';
return '#ff6b6b';
})(),
offsetCenter: [0, '30%']
},
data: [{ value: speed, name: '当前速度' }]
}]
};
}
// 初始显示
myChart.setOption(getOption(75));
// 模拟实时更新(实际使用时替换为真实数据)
setInterval(() => {
let speed = Math.random() * 200;
myChart.setOption(getOption(speed.toFixed(2)));
}, 2000);
</script>
</body>
</html>
核心实现原理:
- 动态指针颜色控制
pointer: {
itemStyle: {
color: (function() {
if (speed < 60) return '#4dabf7';
if (speed < 120) return '#69db7c';
return '#ff6b6b';
})()
}
}
通过立即执行函数根据当前速度值返回对应颜色
- 智能警示图标
graphic: [{
style: {
opacity: speed > 120 ? 1 : 0 // 动态控制透明度
}
}]
当速度超过120时显示图标(opacity=1),否则隐藏(opacity=0)
- 数值颜色同步
detail: {
color: (function() {
// 颜色逻辑与指针同步
})()
}
确保数值显示颜色与指针颜色保持同步变化
进阶优化方向:
- 添加警示动画
// 在graphic配置中增加动画
animation: speed > 120,
animationDuration: 1000,
animationEasing: 'elasticOut'
- 多级警告系统
// 修改graphic配置为多个图标
graphic: [
{ // 普通警告
visible: speed > 120 && speed <= 160,
style: { image: 'warning1.png' }
},
{ // 严重警告
visible: speed > 160,
style: { image: 'warning2.png' }
}
]
- 声音警示集成
// 速度超限时播放提示音
if (speed > 120 && !isAlerted) {
new Audio('alert.mp3').play();
isAlerted = true;
} else if (speed <= 120) {
isAlerted = false;
}
- 自适应尺寸
// 添加响应式配置
window.addEventListener('resize', () => {
myChart.resize();
myChart.setOption(getOption(currentSpeed));
});
该方案通过动态配置生成函数实现:
- 指针颜色根据速度区间自动切换
- 超速警示图标智能显示/隐藏
- 所有视觉元素颜色同步变化
- 支持实时数据更新
可以通过修改以下参数自定义:
axisLine.color:调整速度区间颜色分段
graphic.style.image:更换警告图标
- 阀值判断逻辑中的120:修改速度警戒值
- 颜色映射逻辑:自定义各速度段的颜色方案