【发布时间】:2019-03-24 17:33:38
【问题描述】:
其他在线教程/答案是关于 D3.js v3.x 或可拖动元素上的特定位置。
我查看了文档,但我不完全了解如何操作:
我试图在不改变矩形位置的情况下防止红色矩形与圆圈重叠。
我指定了fx 和fy,但仍然没有成功。
const nodes = d3.range(100).map(d => ({radius: 5, type: "circle"}));
const walls = [{}, {}, {}, {}].map((_, index) => ({
fx: 200 * index,
fy: 100,
type: "wall"
}));
const circleCenters = [100, 300, 500];
d3.forceSimulation(nodes.concat(walls))
.force('charge', d3.forceManyBody().strength(10))
.force('x', d3.forceX().x(function (d, i) {
if (d.type === "circle")
return circleCenters[i % 3];
else
return d.fx;
}))
.force('y', d3.forceY().y(100))
.force('collision', d3.forceCollide().radius(d => d.radius))
.on('tick', ticked);
function ticked() {
d3.select('svg')
.selectAll('rect')
.data(walls)
.enter()
.append('rect')
.attr('width', 100)
.attr('height', 10)
.attr('fill', 'red')
.attr('x', d => d.x)
.attr('y', d => d.y);
const u = d3.select('svg')
.selectAll('circle')
.data(nodes);
u.enter()
.append('circle')
.merge(u)
.attr('fill', 'blue')
.attr('r', d => d.radius)
.attr('cx', d => d.x)
.attr('cy', d => d.y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<svg width="90vw" height="90vh">
</svg>
【问题讨论】:
标签: javascript d3.js dom svg