d3过渡中圆的碰撞/重叠检测

时间:2015-02-21 15:42:03

标签: javascript svg d3.js collision-detection transitions

我正在使用d3为地图上的路径(路径)设置动画。当路线到达路线上的某个点时,我想弹出一些信息。

我的大多数代码都基于以下示例。 http://bl.ocks.org/mbostock/1705868。我真的只是想确定是否有一种方法来检测过渡圆在这个例子中何时碰撞或重叠任何静止圆圈。

2 个答案:

答案 0 :(得分:5)

您可以在补间功能中detect collision。从补间函数内部定义要调用的collide函数,如下所示:

function collide(node){
    var trans = d3.transform(d3.select(node).attr("transform")).translate,
      x1 = trans[0],
      x2 = trans[0] + (+d3.select(node).attr("r")),
      y1 = trans[1],
      y2 = trans[1] + (+d3.select(node).attr("r"));

  var colliding = false;
  points.each(function(d,i){
    var ntrans = d3.transform(d3.select(this).attr("transform")).translate,
      nx1 = ntrans[0],
      nx2 = ntrans[0] + (+d3.select(this).attr("r")),
      ny1 = ntrans[1],
      ny2 = ntrans[1] + (+d3.select(this).attr("r"));


      if(!(x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1))
        colliding=true;
  })

  return colliding;
}

points是静止点,node是过渡元素。 collide做的是检查node 是否与任何点重叠(如collision detection example here所示)。

因为我们需要将node传递给补间函数,所以我们用attrTween替换迈克示例中使用的tween

circle.transition()
      .duration(10000)
      .tween("attr", translateAlong(path.node()))
      .each("end", transition);

最后,补间函数调用我们的collide

function translateAlong(path) {
  var l = path.getTotalLength();
  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength(t * l);

      d3.select(this).attr("transform","translate(" + p.x + "," + p.y + ")");

      if(collide(this))
        d3.select(this).style("fill", "red")
       else
        d3.select(this).style("fill", "steelblue")
    };
  };
}

请参阅full demo here

答案 1 :(得分:0)

最简单的方法就是检查&#34;关闭&#34;过渡圈到其他点。

var pop = d3.select("body").append("div")
    .style("position","absolute")
    .style("top",0)
    .style("left",0)
    .style("display", "none")
    .style("background", "yellow")
    .style("border", "1px solid black");

// Returns an attrTween for translating along the specified path element.
function translateAlong(path) {
  var l = path.getTotalLength();
  var epsilon = 5;
  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength(t * l);
      points.forEach(function(d,i){
        if ((Math.abs(d[0] - p.x) < epsilon) && 
            (Math.abs(d[1] - p.y) < epsilon)){
          pop.style("left",d[0]+"px")
            .style("top",d[1]+20+"px")
            .style("display","block")
            .html(d);
          return false;
        }
      })
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}

圆圈移动得越快,你的epsilon就越大。

示例here

enter image description here

相关问题