从 chartJS 中的数据定义 backgroundColor

Define backgroundColor from data in chartJS

如何使用数据变量中的属性设置元素的背景颜色?

"backgroundColor": ["Farbe"], won't work ...

我。 e.如何访问变量中提供的信息?

非常感谢!

https://jsfiddle.net/zre6t1jn/

var mydata = [
{ "Thema": "Thema 1", "Anzahl": 50, "Farbe": "#006aaa" }, 
{ "Thema": "Thema 2", "Anzahl": 10, "Farbe": "#0071ae" }, 
{ "Thema": "Thema 3", "Anzahl": 10, "Farbe": "#0077b1" }, 
{ "Thema": "Thema 4", "Anzahl": 5, "Farbe": "#007cb3" }
];

var lineCtx = document.getElementById("myChartTree");
var myLineChart = new Chart(lineCtx, 
{
    "type": "treemap",
    "options": {
      "responsive": true,
      "plugins": {
        "title": {
        "display": false,
      },
      "legend": {
          "display": false
        }
      }
    },
    "data": {
      "datasets": [{
        "tree": mydata,
        "key": "Anzahl",
        "groups": ["Thema"],
        "borderWidth": 2,
        "borderColor": "white",
        ---> **"backgroundColor": "#cccccc",** <---
        "spacing": 0,
        "labels": {
          "display": true,
          "font": { "size": 11 }
        }
      }]
    }
  }
);

您可以为此使用脚本化选项作为背景色:

var mydata = [{
    "Thema": "Thema 1",
    "Anzahl": 50,
    "Farbe": "#006aaa"
  },
  {
    "Thema": "Thema 2",
    "Anzahl": 10,
    "Farbe": "#0071ae"
  },
  {
    "Thema": "Thema 3",
    "Anzahl": 10,
    "Farbe": "#0077b1"
  },
  {
    "Thema": "Thema 4",
    "Anzahl": 5,
    "Farbe": "#007cb3"
  }
];

var lineCtx = document.getElementById("myChartTree");
var myLineChart = new Chart(lineCtx, {
    "type": "treemap",
    "options": {
      "responsive": true,
      "plugins": {
        "title": {
          "display": false,
        },
        "legend": {
          "display": false
        }
      }
    },
    "data": {
      "datasets": [{
        "tree": mydata,
        "key": "Anzahl",
        "groups": ["Thema"],
        "borderWidth": 2,
        "borderColor": "white",
        "backgroundColor": (ctx) => (ctx.dataIndex ? mydata[ctx.dataIndex].Farbe : 'gray'),
        "spacing": 0,
        "labels": {
          "display": true,
          "font": {
            "size": 11
          }
        }
      }]
    }
  }

);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>=
<script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@2.0.2/dist/chartjs-chart-treemap.js"></script>
<div style="width:auto;max-width: 100%;height:200px;">
  <canvas id="myChartTree" width="507px" height="200px"></canvas>
</div>