开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第22天,点击查看活动详情
写在前面
上篇文章介绍了在vite+vue的后台项目中引入echarts,本篇文章介绍如何在vite+vue项目中实现折线图线条的渐变
完整源码:项目gitee地址
在线演示:演示地址
账号:admin
密码:admin
折线图的渐变
实现过程:
查看官网文档,找到相关的配置项:
从上面的描述我们就知道了应该配置哪项信息来实现折线图的渐变。
首先,我们需要在series下增加itemStyle,配置里面的color的值就可实现折线图线条的渐变,根据文档的说明,我们可以知道type表示渐变的类型,分为线性渐变linear和径向渐变radial,以及纹理填充(type字段缺省),该篇文章主要介绍线性渐变的实现,因为项目中要求用到的就是线性渐变,另两种在项目中用到后再介绍,下面是我写的一个例子。
我们可以看到例子中,设置了type为linear,即线性渐变。
color中还有其他字段,例子中设置了x:0,y:0,x2:1,y2:0,这会使我们的图表横向线性渐变,即从左往右颜色渐变,如果我们将这些值改为x:0,y:0,x2:0,y2:1,这会使我们的图表纵向线性渐变,即从上往下颜色渐变,以此类推,我们可以通过改变这四个值来改变渐变的方向。
colorStops字段是一个数组,通过设置offset的值来进行颜色的配置,offset取值范围为[0,1],是一个百分数,分别表示0% ~ 100%的颜色
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
}
}
}
]
我们在项目的src\views\ChartLine.vue文件中编写实现折线图线条的渐变的全部代码如下:
<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
}
}
}
]
};
myChart.setOption(option);
}
</script>
<style lang="less" scoped>
.main {
width: 500px;
height: 300px;
background-color: #000612;
color: rgb(254, 196, 0);
}
</style>
最终效果:
写在最后
以上就是在vite+vue项目中实现折线图线条的渐变的所有代码和说明