Skip to content

Instantly share code, notes, and snippets.

@vasturiano
Last active December 23, 2023 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vasturiano/2f602ea6c51c664c29ec56cbe2d6a5f6 to your computer and use it in GitHub Desktop.
Save vasturiano/2f602ea6c51c664c29ec56cbe2d6a5f6 to your computer and use it in GitHub Desktop.
Dynamic 3D Graph

Graph data dynamic updates using 3d-force-graph. Clicking on a node removes it from the graph.

<head>
<script src="//unpkg.com/3d-force-graph"></script>
<style>
body { margin: 0; }
</style>
</head>
<body>
<div id="3d-graph"></div>
<script>
const initData = {
nodes: [ {id: 0 } ],
links: []
};
const elem = document.getElementById("3d-graph");
const Graph = ForceGraph3D()(elem)
.enableNodeDrag(false)
.onNodeHover(node => elem.style.cursor = node ? 'pointer' : null)
.onNodeClick(removeNode)
.graphData(initData);
setInterval(() => {
const { nodes, links } = Graph.graphData();
const id = nodes.length;
Graph.graphData({
nodes: [...nodes, { id }],
links: [...links, { source: id, target: Math.round(Math.random() * (id-1)) }]
});
}, 1000);
//
function removeNode(node) {
let { nodes, links } = Graph.graphData();
links = links.filter(l => l.source !== node && l.target !== node); // Remove links attached to node
nodes.splice(node.id, 1); // Remove node
nodes.forEach((n, idx) => { n.id = idx; }); // Reset node ids to array index
Graph.graphData({ nodes, links });
}
</script>
</body>
@mahdisoultana
Copy link

thank you very much @vasturiano for this library it is really helpful and good example to show hoe it's work .

@rsodha
Copy link

rsodha commented Dec 23, 2023

How do I achieve const { nodes, links } = Graph.graphData(); for ReactForceGraph2d?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment