sha*_*adc 3 javascript svg collision-detection transitions d3.js
我正在使用d3为地图上的路径(路径)设置动画.当路线到达路线上的某个点时,我想弹出一些信息.
我的大多数代码都基于以下示例.http://bl.ocks.org/mbostock/1705868.我真的只是想确定是否有一种方法来检测过渡圆在这个例子中何时碰撞或重叠任何静止圆圈.
您可以检测补间功能中的冲突.定义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;
}
Run Code Online (Sandbox Code Playgroud)
points静止点在哪里,node是过渡元素.是什么collide做的是检查是否node 重叠与任何点(如图碰撞检测这里的例子).
因为我们需要将node其传递给补间函数,所以我们替换attrTweenMike的示例中使用的tween:
circle.transition()
.duration(10000)
.tween("attr", translateAlong(path.node()))
.each("end", transition);
Run Code Online (Sandbox Code Playgroud)
最后,调用我们的补间函数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")
};
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5697 次 |
| 最近记录: |