我正在使用d3来制作一些圆圈的动画,这些圆圈表示一些工具,您可以拖放这些工具。我希望能够创建一个函数来检测两个circles/g元素何时相互碰撞。
我已经有了很多代码,但这是我想要修改的相关代码。我真的只是在尝试确定是否有一种方法可以检测circle/g元素何时与其他元素发生冲突或重叠
function circCollide(g) {
node = g;
nodeBox = g.getBBox();
nodeLeft = nodeBox.x;
nodeRight = nodeBox.x + nodeBox.width;
nodeTop = nodeBox.y;
nodeBottom = nodeBox.y + nodeBox.height;
d3.selectAll(g)
.attr("fill", function() {
if (this !== node) {
otherBox = this.getBBox();
otherLeft = otherBox.x;
otherRight = otherBox.x + otherBox.width;
otherTop = otherBox.y;
otherBottom = otherBox.y + otherBox.height;
collideHoriz = nodeLeft < otherRight && nodeRight > otherLeft;
collideVert = nodeTop < otherBottom && nodeBottom > otherTop;
if ( collideHoriz && collideVert) {
return "tomato";
} else {
return "none"
}
} else {
return "none";
}
});
}
}现在我得到了以下错误(“未捕获TypeError: g.getBBox不是一个函数”),我该如何修复它并使我的碰撞检测工作
发布于 2020-02-12 18:20:23
g包含d3选择,而getBBox是绑定到DOM node的函数。
可以使用selection.node函数从d3选择中访问DOM节点。
尝试以下操作:
nodeBox = g.node().getBBox();也就是说,您可能希望使用getBoundingClientRect而不是getBBox,以便获得准确的值(例如,将转换考虑在内);c.f。详情请参阅上面链接的文章。
https://stackoverflow.com/questions/60185556
复制相似问题