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
        }

藍色的箭頭函數就是設置顏色的函數。沒錯,這么寫就夠了。

 

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM