d3 中具有不同翻转操作的多个多边形

Multiple polygons with different roll over actions in d3

本文关键字:操作 多边形 翻转 d3      更新时间:2023-09-26

我正在尝试将几个多边形变成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。这是我对多边形"按钮"的小提琴,但我只能将相同的操作分配给那里的两个多边形。

我的方法是在数据中设置悬停颜色:

像这样:

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.

此处的工作代码

您可以执行此类操作的一种方法是根据其索引将类分配给每个多边形:

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

d 是数据,i 是索引,因此我们返回每个多边形的索引作为类。这使我们能够做这样的事情:

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

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