Yig*_*ong 4 javascript chart.js
我使用 ChartJS 创建了一个饼图。
现在我想创建一个单击处理程序,在其中我可以获取已创建的图表部分的标签和值。我该如何实现这一目标?
let my_chart = new Chart('tot_pop_chart', {
type: 'pie',
data: {
labels: ['NSW', 'VIC', 'QSD', 'SA', 'WA', 'TAS', 'NT', 'ACT'],
datasets: [{
data: [1, 2, 3, 4, 5, 6, 7, 8],
backgroundColor: ['rgba(63, 75, 59, 1)', 'rgba(242, 246, 208, 1)', 'rgba(197, 123, 87, 1)', 'rgba(118, 159, 182, 1)', 'rgba(58, 110, 165, 1)', 'rgba(88, 12, 31, 1)', 'rgba(157, 172, 255, 1)', 'rgba(122, 48, 108, 1)']
}
]
},
options: {
animation: {},
plugins: {
legend: {
display: true,
position: 'bottom'
}
},
onClick: ... //see below
}
}
);
Run Code Online (Sandbox Code Playgroud)
我当前的尝试如下:
onClick:
e => {
console.log("In click", e.chart);
// find the index of the clicked item
let canvasPosition = Chart.helpers.getRelativePosition(e, e.chart);
let index = e.chart.scales.x.getValueForPixel(canvasPosition.x);
// now I want to retrieve the label/data using the index, how to?
}
Run Code Online (Sandbox Code Playgroud)
但是,错误发生为TypeError: Cannot read property 'getValueForPixel' of undefined。另外,如何使用 onClick 函数中的索引检索标签/数据?
非常感谢你的帮助!
Lee*_*lee 15
饼图/圆环图不使用刻度,因此您不能使用getValueForPixel. 相反,您可以只听第二个参数,它包含一个包含所有活动元素的数组,默认交互模式仅包含 1 个项目:
var 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: (e, activeEls) => {
let datasetIndex = activeEls[0].datasetIndex;
let dataIndex = activeEls[0].index;
let datasetLabel = e.chart.data.datasets[datasetIndex].label;
let value = e.chart.data.datasets[datasetIndex].data[dataIndex];
let label = e.chart.data.labels[dataIndex];
console.log("In click", datasetLabel, label, value);
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);Run Code Online (Sandbox Code Playgroud)
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>Run Code Online (Sandbox Code Playgroud)