echarts 实战 : 想让图例颜色和元素颜色对应,怎么办?

时间:2019-11-17
本文章向大家介绍echarts 实战 : 想让图例颜色和元素颜色对应,怎么办?,主要包括echarts 实战 : 想让图例颜色和元素颜色对应,怎么办?使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先,在 series 里设置颜色。

(我是用js生成 echarts 需要的option对象,所以可能很难看懂)

        normalData.sData.forEach((item, index) => {
          const object = {...baseSeriesObject}
          object.data = item.data
  
          this.setLegend(object, option, item.name, showLegendFlag)
          this.setStock(object, showStackFlag)
          this.setLegendColor(object, settingData.color[index])
  
          // 单位
          if (typeof settingData.unitFlag === "object" && settingData.unitFlag.length > 0 && settingData.xyType === "x" && settingData.unitFlag[settingData.unitFlag.length-1] !== "") {
            option.yAxis[index].axisLabel.formatter = this.getAxisLabel(settingData.unitFlag[index])
          }

          if (settingData.barWidth) {
            object.barWidth = settingData.barWidth
          }

          option.series.push(object)
        });

标红色的就是设置颜色的方法。

  setLegendColor = (object, color) => {
    if (!color || !object) {
      return object
    }
    object.normal = {
      color: color
    }
    return object
  }

最后是 legend.textStyle.color 。关键是 color 要写成函数。

    const baseLegend = {
      data:[],
      top:10,
      right:23,
      itemWidth:8,
      itemHeight:8,
      icon:'circle',
      textStyle:{
        padding:[3,5,0,3],
        fontSize:16,
        color: (params) => (params)
      },
    }
        if (typeof settingData.legendFlag === "object") {
          option.legend = Object.assign(baseLegend, settingData.legendFlag)
        } else {
          option.legend = baseLegend
        }

蓝色的箭头函数就是设置颜色的函数。没错,这么写就够了。

以上。

原文地址:https://www.cnblogs.com/foxcharon/p/11875364.html