开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第23天,点击查看活动详情
写在前面
上篇文章介绍了在vite+vue的后台项目中折线图线条的线性渐变,本篇文章介绍如何在vite+vue项目中实现面积图的颜色渐变
完整源码:项目gitee地址
在线演示:演示地址
账号:admin
密码:admin
面积图的颜色渐变
实现过程记录:
我们知道,基础面积图的实现是在series里添加areaStyle: {}即可。
现在我们要实现面积图的颜色渐变,我们找到官方文档areaStyle配置项:
发现和折线图线条的线性渐变的配置项指向同一个位置。
看过我上篇文章的同学此时应该已经会实现面积图的颜色渐变了。没看过的可以继续往下看。
首先,我们需要在series下增加areaStyle,配置里面的color的值就可实现面积图的颜色渐变,下面是我写的一个例子。
我们可以看到例子中,设置了type为linear,即线性渐变。
color中还有其他字段,例子中设置了x:0,y:0,x2:0,y2:1,这会使我们的图表纵向线性渐变,即从上往右下颜色渐变,我们可以通过改变 x ,y ,x2 ,y2 的值来改变渐变的方向。
colorStops字段是一个数组,通过设置offset的值来进行颜色的配置,offset取值范围为[0,1],是一个百分数,分别表示0% ~ 100%的颜色,例子中设置了0%和100%处的颜色
series: [
{
type: 'line',
showSymbol: false,
data: [820, 932, 901, 934, 1290, 1330, 1320],
smooth: true,
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: 'rgba(255, 160, 0, 0.3)' // 0% 处的颜色
}, {
offset: 1, color: 'rgba(254, 196, 0, 0)' // 100% 处的颜色
}],
global: false // 缺省为 false
}
},
}
]
最终实现的全部代码如下:
<template>
<div ref="main" class="main"></div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
const main = ref()
onMounted(() => {
initChart()
})
const initChart = () => {
let myChart = echarts.init(main.value);
let option = {
tooltip: {
trigger: 'axis'
},
xAxis: {
data: ["2016", "2017", "2018", "2019", "2020", "2021", "2022"],
boundaryGap: false, // x轴两边是否留白
// 坐标轴轴线
axisLine: {
lineStyle: {
color: '#fff',
opacity: 0.6
}
},
// 坐标轴刻度
axisTick: {
show: false
},
// 坐标轴文本
axisLabel: {
show: true,
color: "rgba(255, 255, 255, 0.6)"
}
},
yAxis: {
// 坐标轴分割线
splitLine: {
lineStyle: {
color: ['#fff'],
opacity: 0.1
}
},
// 坐标轴文本
axisLabel: {
show: true,
color: "rgba(255, 255, 255, 0.6)"
}
},
grid: {
},
series: [
{
type: 'line',
showSymbol: false,
data: [820, 932, 901, 934, 1290, 1330, 1320],
smooth: true,
itemStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 1,
y2: 0,
colorStops: [{
offset: 0, color: 'rgba(255, 179, 0, 0.3)' // 0% 处的颜色
}, {
offset: 0.33, color: 'rgba(255, 160, 0, 1)' // 33% 处的颜色
}, {
offset: 0.66, color: 'rgba(254, 219, 0, 1)' // 66% 处的颜色
}, {
offset: 1, color: 'rgba(254, 196, 0, 0.3)' // 100% 处的颜色
}],
global: false // 缺省为 false
}
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: 'rgba(255, 160, 0, 0.3)' // 0% 处的颜色
}, {
offset: 1, color: 'rgba(254, 196, 0, 0)' // 100% 处的颜色
}],
global: false // 缺省为 false
}
},
}
]
};
myChart.setOption(option);
}
</script>
<style lang="less" scoped>
.main {
width: 500px;
height: 300px;
background-color: #000612;
}
</style>
最终效果:
写在最后
以上就是在vite+vue项目中实现折线图线条的渐变的所有代码和说明