gpt4 book ai didi

javascript - 是否有可能获得当前在 D3 力模拟中活跃的力列表?

转载 作者:行者123 更新时间:2023-12-05 04:40:52 26 4
gpt4 key购买 nike

就说我有一个 d3-force 模拟,我添加了一些这样的力:

const simulation = d3
.forceSimulation()
.nodes(dots)
.force("charge", d3.forceManyBody())
.force("link", d3.forceLink(links))
.force("center", d3.forceCenter());
.on("tick", tick)

是否可以列出所有这些力?例如像 simulation.getForces() 方法?并让它返回 ["charge", "link", "center"]

最佳答案

恐怕不行。来自 the source看起来 forces Map 根本没有暴露在外面。我能想到的唯一解决方法是包装 simulation.force 对象并存储您自己的注册表(这是 hacky),或者保留所有可能值的数组并查看是否 simulation。 force(name) 返回任何内容:

const width = 600,
height = 600;

const svg = d3.select("body")
.append("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);

const g = svg.append("g");

const nodes = Array
.from({
length: 20
})
.map(() => {
const [x, y] = d3.pointRadial(2 * Math.PI * Math.random(), 200);
return {
id: Math.random(),
x,
y
};
});

simulation = d3.forceSimulation()
.force("collide", d3.forceCollide().radius(20))
.force("manyBody", d3.forceManyBody().strength(30))
.force("center", d3.forceCenter().strength(0.01))
.alpha(0.1)
.alphaDecay(0)
.nodes(nodes)
.on("tick", () => {
g.selectAll("circle:not(.exit)")
.data(simulation.nodes(), d => d.id)
.join(
enter => enter.append("circle")
.attr("fill", d => d3.interpolateSinebow(d.id))
.attr("r", 1)
.transition()
.duration(2000)
.attr("r", 19)
.selection(),
update => update
.attr("cx", d => d.x)
.attr("cy", d => d.y),
exit => exit
.classed("exit", true)
.transition()
.duration(2000)
.attr("fill", "#eee")
.attr("r", 1)
.remove()
);
});

const allPossibleForces = [
"x",
"y",
"manyBody",
"collide",
"center"
];

const allForces = allPossibleForces.filter(v => simulation.force(v) !== undefined);
console.log(allForces);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>

关于javascript - 是否有可能获得当前在 D3 力模拟中活跃的力列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70179766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com