我对Chart.js上的饼图有疑问。
单击切片时删除切片的最佳方法是什么?我知道方法getSegmentsAtEvent()可用于读取切片属性。可以找出我单击的切片,然后遍历slices对象直至找到匹配项。有没有更简单的方法可以实现?
tks
这可以通过以下功能实现:getSegmentsAtEvent(event)
和removeData( index )
Chart.js API
使用getSegmentsAtEvent
,您可以恢复已单击的段。
下一步是在图表中找到切片的索引。要进行搜索,您可以遍历图表的所有当前段,并在找到时调用removeData
。 (我认为没有办法直接知道索引)
var segments = myChart.segments;
for (var index = 0; index < segments.length; index++) {
if (activeLabel == segments[index].label) {
myChart.removeData(index);
}
}
完整演示:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).Pie(data);
$("#myChart").click(
function(evt){
var activePoints = myChart.getSegmentsAtEvent(evt);
var activeLabel = activePoints[0].label;
var segments = myChart.segments;
for (var index = 0; index < segments.length; index++) {
if (activeLabel == segments[index].label) {
myChart.removeData(index);
}
}
}
);
}
);
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>
onclick
属性。myChart.getElementsAtEvent(event);
进行过滤].update()
方法更新图表以下是必选的工作片段
var chart_click_event = function(event) { debugger; let activePoints = myChart.getElementsAtEvent(event); //If you click on empty area this if check will not pass. if (activePoints[0]) { let chartData = activePoints[0]['_chart'].config.data; let idx = activePoints[0]['_index']; let label = chartData.labels[idx]; let value = chartData.datasets[0].data[idx]; if (label == 'China' || value < 50) { chartData.labels.splice(idx, 1); chartData.datasets[0].data.splice(idx, 1); myChart.update(); } } } var data = [{ data: [50, 55, 60, 33], backgroundColor: [ "#4b77a9", "#5f255f", "#d21243", "#B27200" ], borderColor: "#fff" }]; var options = { tooltips: { enabled: true }, plugins: { datalabels: { color: '#fff', } }, onClick: chart_click_event }; var ctx = document.getElementById("pie-chart").getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { labels: ['Pakistan', 'China', 'US', 'Canada'], datasets: data }, options: options });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <canvas id="pie-chart"></canvas>