使用echarts实现金字塔效果,颜色渐变,左右显示其对应的值
效果:
如果要实现一个正三角的形状,需要在data数组中,将value赋值成有序递增,bl代表他的分值,显示在左侧。
var data = [
{
name: "小学",
value: 10,
bl: 50,
},
{
name: "初中",
value: 20,
bl: 56,
},
{
name: "高中",
value: 30,
bl: 21,
},
{
name: "大学",
value: 40,
bl: 86,
},
{
name: "研究生",
value: 50,
bl: 12,
},
];
//gradient 方法用来实现获取每一层的颜色值
var colorList = this.gradient("#e3e4e9", "#8b8cba", data.length);
var myChart = echarts.init(this.$refs.main);
// 指定图表的配置项和数据
var option = {
color: colorList,
tooltip: {
trigger: "item",
triggerOn: "mousemove",
formatter: function (params) {
var result = params.data.name;
return result;
},
},
series: [
{
name: "Funnel",
type: "funnel",
sort: "ascending",
top: "5%",
left: "5%",
bottom: "0",
width: "60%", // 宽度可以自定义
height: "90%", // 高度可以自定义
min: 0,
max: data.length * 10,
label: {
show: true,
position: "left",
formatter: "{c}",
formatter: function (params) {
return params.data.bl;
},
color: "#FFFFFF",
fontSize: 12,
},
labelLine: {
show: false,
length: 2,
},
itemStyle: {
normal: {
borderWidth: 0,
opacity: 0.6,
},
},
emphasis: {
label: {
fontSize: 10,
},
},
data: data,
zlevel: 2,
},
{
name: "Funnel",
type: "funnel",
sort: "ascending",
top: "5%",
left: "5%",
bottom: "0",
width: "60%", // 宽度可以自定义
height: "90%", // 高度可以自定义
min: 0,
max: data.length * 10,
label: {
show: true,
position: "right",
color: "#FFFFFF",
fontSize: 12,
formatter: function (params) {
return params.data.state.length > 8
? params.data.state.substring(0, 8) + "..."
: params.data.state;
},
},
labelLine: {
show: false,
length: 2,
},
itemStyle: {
normal: {
borderWidth: 0,
// borderColor: "transparent",
opacity: 0.6,
},
},
emphasis: {
label: {
fontSize: 12,
},
},
data: data,
zlevel: 1,
},
],
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
window.addEventListener("resize", () => {
myChart.resize();
});
获取每一层渐变的颜色值
function rgbToHex(r, g, b) {
var hex = ((r << 16) | (g << 8) | b).toString(16);
return "#" + new Array(Math.abs(hex.length - 7)).join("0") + hex;
}
function hexToRgb(hex) {
var rgb = [];
for (var i = 1; i < 7; i += 2) {
rgb.push(parseInt("0x" + hex.slice(i, i + 2)));
}
return rgb;
}
export function gradient(startColor, endColor, step) {
//将hex转换为rgb
var sColor = hexToRgb(startColor),
eColor = hexToRgb(endColor);
//计算R\G\B每一步的差值
var rStep = (eColor[0] - sColor[0]) / step;
var gStep = (eColor[1] - sColor[1]) / step;
var bStep = (eColor[2] - sColor[2]) / step;
var gradientColorArr = [];
for (var i = 0; i < step; i++) {
//计算每一步的hex值
gradientColorArr.push(
rgbToHex(
parseInt(rStep * i + sColor[0]),
parseInt(gStep * i + sColor[1]),
parseInt(bStep * i + sColor[2])
)
);
}
return gradientColorArr;
}