我想添加指向甜甜圈图表的链接,以便能够向用户发送包含由点击选项过滤的记录的页面。
例如here,如果用户点击"绿色",我想将用户发送到一个页面,该页面将显示所有"绿色"记录。
我没有找到一个简单的方法来做到这一点,并尝试过这样的工作尚未完成:
(我添加了一个属性"过滤"使用" id"我需要对其进行过滤)
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red",
filter: 1
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green",
filter: 2
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow",
filter: 3
}
]
$(document).ready(
function () {
$("#chart").click(
function(evt){
var activePoints = chart.getSegmentsAtEvent(evt);
var url = "http://example.com/?grid[f][collor][]=" + activePoints[0].filter
alert(url);
}
);
}
);
我无法获得属性" filter"使用" activePoints [0] .filter"
谢谢。
答案 0 :(得分:3)
在JSON中添加自定义属性是v2(https://github.com/nnnick/Chart.js/issues/1185)路线图中的一项功能。就目前而言,您可以在javascript中添加属性,如下所示:
var segments = chart.segments;
for (var i = 0; i < segments.length; i++) {
segments[i].filter = i+1;
}
这是一个在url(http://jsfiddle.net/tcy74pcc/1/)中加载了filter / id属性的jsfiddle:
如果你想用一个基于点而不是段的图表来做这个,这里有一个类似线条解决方案的帖子: Displaying custom dataset properties in tooltip in chart.js
希望有所帮助。祝你好运!
答案 1 :(得分:2)
现在不推荐使用getSegmentsAtEvent。改为使用getElementsAtEvent。
这里有完整的功能,并为每个片段添加动态颜色。
var piChart = function (ctx, labelName, labels, values, filters) {
var colors = dynamicColors(values.length)
var data = {
labels: labels,
datasets: [
{
label: labelName,
backgroundColor: colors.backColors,
hoverBackgroundColor: colors.highColors,
borderColor: colors.borders,
hoverBorderColor: colors.borders,
borderWidth: 1,
data: values
}
]
};
var pieChart = new Chart(ctx, {
type: "pie",
data: data
});
if (filters != null) {
ctx.click(
function (evt) {
var activePoints = pieChart.getElementAtEvent(evt);
if (activePoints.length > 0) {
var index = activePoints[0]["_index"];
location.href = filters[index];
}
});
}
}
var dynamicColors = function (count) {
var backColors = [];
var highColors = [];
var borders = [];
for (var i = 0; i < count; i++) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var backColor = "rgba(" + r + "," + g + "," + b + ", 0.4)";
var highColor = "rgba(" + r + "," + g + "," + b + ", 0.8)";
var border = "rgba(" + r + "," + g + "," + b + ", 1)";
backColors.push(backColor);
highColors.push(highColor);
borders.push(border);
}