单击事件以在图表 JS 中显示饼图切片的名称

On click event to show name of pie chart slice in chartsJS

我正在使用 chartsjs。我想单击饼图切片并设置警报以显示被单击的切片的名称。

responsive: false,
onClick : (event, items) =>{
    alert("Clicked");
}

这将在任何切片上产生术语“点击”。但是我怎么才能得到切片。 当我将术语 “clicked” 更改为 items 时,结果是 [object Object]。 如何隔离切片的名称。您知道将鼠标悬停在 chartsjs 饼图切片上时出现的名称。

当我检查我点击的图表部分时(以第一个饼图部分为例)我看到:

 [i]
0: i
hidden: false
_chart: ni {id: 2, ctx: CanvasRenderingContext2D, canvas: canvas#myChart4, config: {…}, width: 650, …}
_datasetIndex: 0
_index: 0
_model:
backgroundColor: "rgb(0, 72, 165)"
borderAlign: "center"
borderColor: "#fff"
borderWidth: 2
circumference: 1.3057964574823102
endAngle: -0.26499986931258634
innerRadius: 78.4
label: false
outerRadius: 156.8
startAngle: -1.5707963267948966
x: 325
y: 192.2
[[Prototype]]: Object

正如您所说,您得到了一个对象,如果您记录这个对象,您会看到它是一个包含所有活动元素的数组。如果您记录元素本身,您会看到它包含 datasetIndex 和 dataIndex,使用这些您可以从图表中获取当前标签,如下所示:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      console.log(chart.data.labels[activeEls[0].index])
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

编辑

好像你用的是V2,流程基本一样,只是图表变量定义在不同的地方:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls) => {
      console.log(activeEls[0]._chart.data.labels[activeEls[0]._index])
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>