2016-03-08 39 views
1

我试图在d3中将多个多边形转换为按钮。我需要每个多边形具有不同的滚动/滚出/点击操作。 我绘制多边形是这样的:在d3中使用不同滚动操作的多个多边形

poly = [coordinates]; 

poly2 = [coordinates]; 

//drawing polygons 
chart.selectAll("polygon") 
    .data([poly, poly2]) 
    .enter().append("polygon")  
    .attr(... //attributes go here 
//I add functionality below 
    .on("mouseover", function (d) { 
     chart.selectAll("polygon") 
     .attr("fill","orange"); 
    }) 
    .on("mouseout" , function (d) { 
     chart.selectAll("polygon") 
     .attr("fill","steelblue"); 
    }); 

这适用于所有的“鼠标...”影响到所有多边形。为每个多边形分配不同的“鼠标...”动作的最佳方法是什么?例如,我希望poly在鼠标悬停时将颜色切换为orange,但在鼠标悬停时poly2将变为red。 这是我的fiddle with the polygon "buttons",但我只能将相同的动作分配给两个多边形。你可以做这样的事情

回答

2

我的办法是设置里面的数据悬停颜色:

事情是这样的:

poly2 = { 
    color: "green",//mouse hover color 
    points: [{ 
    "x": 71, 
    "y": 1.5 
    }, { 
    "x": 75, 
    "y": 0 
    }, { 
    "x": 79, 
    "y": 1.5 
    }, { 
    "x": 75.5, 
    "y": 1.1 
    }, { 
    "x": 75.5, 
    "y": 1.7 
    }, { 
    "x": 74.5, 
    "y": 1.7 
    }, { 
    "x": 74.5, 
    "y": 1.1 
    }] 
}; 

下鼠标悬停,而不是选择这样所有的多边形:

chart.selectAll("polygon") 
     .attr("fill","orange"); 

选择触发它并从数据中设置填充颜色(查看悬停颜色是否在数据中传递)

d3.select(this) 
     .attr("fill", d.color);//fill color from the data defining the polygon. 

工作代码here

+0

谢谢,它的伟大工程!但是如果我想添加'。对( “鼠标悬停”,loadnewdata)''那里功能loadnewdata(){\t chart.select(”线 “) \t \t .datum(数据) \t \t .attr(”类“,”行“) \t \t .attr(”d“,newdata);}'将新数据加载到其中一个图表上?是否有可能使用相同的方法? –

+0

是的,它会工作... – Cyril

+0

我将如何分配一个函数'loadnewdata'到'poly'属性?我在分配颜色后尝试类似'loadnewdata:“loadnewdata”',但它不起作用 –

1

一种方式是基于其索引分配类每个多边形:

.attr("class", function(d, i) {return i}) 

的d是数据和i是指数,所以我们正在返回索引每个多边形作为类。这使我们能够做到这样的事情:

.attr("fill", function(d, i) { return (i === 0) ? "steelblue" : "red";}) 

所以你有这样的东西:https://jsfiddle.net/szjn7u1v/3/