问题描述
我对 Chart.js 上的饼图有疑问.
I have a question regarding piecharts on Chart.js.
单击切片时删除切片的最佳方法是什么?我知道方法 getSegmentsAtEvent() 可用于读取切片属性.可以找出我正在单击的切片循环遍历切片对象,直到找到匹配项.有没有更简单的方法来实现它?
What would be the best way to remove a slice when clicking on it? I'm aware the method getSegmentsAtEvent() can be used to read the slice properties. It's possible to find out which slicing I'm clicking looping through the slices object until a match is found. Is there a simpler way to achieve it?
tks
推荐答案
这可以通过以下函数实现:getSegmentsAtEvent(event)
和 removeData( index )
Chart.js API
This can be achieved using the functions: getSegmentsAtEvent(event)
and removeData( index )
Chart.js API
使用 getSegmentsAtEvent
可以恢复被点击的段.
With getSegmentsAtEvent
you can recover the segment that has been clicked.
下一步,是在图表中找到切片的索引.要进行搜索,您可以遍历图表的所有当前段并在找到时调用 removeData
.(我觉得没有办法直接知道索引)
The next step, is to find the index of the slice in the chart. To do the search, you can iterate through all the current segments of the chart and call removeData
when it's found. (I think there is no way to directly know the index)
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>
这篇关于删除 Chart.js 中饼图上的切片 onClick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!