d3力碰撞后如何获得圆的坐标(cx,cy)?
How to get coordinates(cx, cy) of circles after d3 force collision?
我试图在使用 d3 力碰撞后获取圆 (cx, cy) 的坐标,但我仍然得到原始位置。有没有什么方法可以转换(碰撞检查后)圆的坐标?
下面只是代码摘要。
let data = [
{ 'x': 100, 'y': 100, 'radius': 10, cluster: 4 },
{ 'x': 100, 'y': 100, 'radius': 6, cluster: 3 },
{ 'x': 50, 'y': 200, 'radius': 10, cluster: 2 },
{ 'x': 350, 'y': 200, 'radius': 10, cluster: 2 },
{ 'x': 100, 'y': 300, 'radius': 20, cluster: 3 },
{ 'x': 100, 'y': 300, 'radius': 25, cluster: 1 },
{ 'x': 100, 'y': 300, 'radius': 33, cluster: 2 }];
var collisionForce = d3.forceCollide((d) => d.radius).strength(1).iterations(100);
var simulation = d3.forceSimulation(data).alphaDecay(0.01).force('collisionForce', collisionForce)
.force('center', d3.forceCenter(width / 2, height / 2));
var node = svg.selectAll('circle').data(data)
.enter().append('circle')
.attr('r', function (d) {
return d.radius;
}).attr('cx', function (d) {
return d.x;
}).attr('cy', function (d) {
return d.y;
})
.attr('cluster', d => d.cluster)
.attr('fill', d => that.palette[d.cluster]);
function ticked() {
node.attr('cx', function (d) {
return d.x;
})
.attr('cy', function (d) {
return d.y;
});
}
simulation.on('tick', ticked);
您可以 listen to the end
模拟事件,然后通过将代码的最后一行更改为以下内容来访问圆圈的最终坐标:
simulation
.on('tick', ticked)
.on('end', () => {
d3.selectAll('circle').each(function () {
const thisD3 = d3.select(this)
console.log(thisD3.attr('cx'), thisD3.attr('cy'))
})
})
据我所知,传递给 d3.forceSimulation
的数组会就地编辑数组,因此您还可以直接在该数组中访问 x
和 y
坐标。这两种情况的关键是在模拟触发 end
事件时执行此操作。
希望对您有所帮助!
我试图在使用 d3 力碰撞后获取圆 (cx, cy) 的坐标,但我仍然得到原始位置。有没有什么方法可以转换(碰撞检查后)圆的坐标?
下面只是代码摘要。
let data = [
{ 'x': 100, 'y': 100, 'radius': 10, cluster: 4 },
{ 'x': 100, 'y': 100, 'radius': 6, cluster: 3 },
{ 'x': 50, 'y': 200, 'radius': 10, cluster: 2 },
{ 'x': 350, 'y': 200, 'radius': 10, cluster: 2 },
{ 'x': 100, 'y': 300, 'radius': 20, cluster: 3 },
{ 'x': 100, 'y': 300, 'radius': 25, cluster: 1 },
{ 'x': 100, 'y': 300, 'radius': 33, cluster: 2 }];
var collisionForce = d3.forceCollide((d) => d.radius).strength(1).iterations(100);
var simulation = d3.forceSimulation(data).alphaDecay(0.01).force('collisionForce', collisionForce)
.force('center', d3.forceCenter(width / 2, height / 2));
var node = svg.selectAll('circle').data(data)
.enter().append('circle')
.attr('r', function (d) {
return d.radius;
}).attr('cx', function (d) {
return d.x;
}).attr('cy', function (d) {
return d.y;
})
.attr('cluster', d => d.cluster)
.attr('fill', d => that.palette[d.cluster]);
function ticked() {
node.attr('cx', function (d) {
return d.x;
})
.attr('cy', function (d) {
return d.y;
});
}
simulation.on('tick', ticked);
您可以 listen to the end
模拟事件,然后通过将代码的最后一行更改为以下内容来访问圆圈的最终坐标:
simulation
.on('tick', ticked)
.on('end', () => {
d3.selectAll('circle').each(function () {
const thisD3 = d3.select(this)
console.log(thisD3.attr('cx'), thisD3.attr('cy'))
})
})
据我所知,传递给 d3.forceSimulation
的数组会就地编辑数组,因此您还可以直接在该数组中访问 x
和 y
坐标。这两种情况的关键是在模拟触发 end
事件时执行此操作。
希望对您有所帮助!