图表JS-更改条形图中最后一个元素的颜色

时间:2019-12-16 17:03:35

标签: javascript reactjs charts chart.js

到目前为止,我可以通过对最后一个元素进行硬编码来使其工作,但是无论图表中传递了什么数据,我都希望自动对其进行着色。 我尝试了(index.length-1),但是它不起作用。

labels: ["Red", "Blue", "Yellow", "Red", "Blue"],
datasets: [{
    data: [22, 19, 23, 84, 22],
    backgroundColor: function(context) {
      var index = context.dataIndex;
      var value = context.dataset.data[index];
      console.log(value);
      return value === context.dataset.data[4] && index === 4 ?
        "red" :
        "blue";
    }
  }]
}

1 个答案:

答案 0 :(得分:2)

backgroundColor上使用回调:

backgroundColor: this.data.map((item, index) => {
  if (index === this.data.length - 1) {
    return 'red';
  } else return 'blue'
})

或使用三元运算符:

backgroundColor: this.data.map((item, index) => {
  return index === this.data.length - 1 ? 'red' : 'blue'
}),

this.data是用于创建图表的数据。

完整解决方案:

data = [22, 19, 23, 84, 22];
labels: ["Red", "Blue", "Yellow", "Red", "Blue"],
  datasets: [{
    data: this.data,
    backgroundColor: this.data.map((item, index) => {
      return index === this.data.length - 1 ? 'red' : 'blue'
    }),
  }]
}