-
Notifications
You must be signed in to change notification settings - Fork 292
/
index.html
72 lines (57 loc) · 2.11 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<head>
<style> body { margin: 0; } </style>
<script type="importmap">{ "imports": {
"react": "https://esm.sh/react",
"react-dom": "https://esm.sh/react-dom/client"
}}</script>
<!-- <script type="module">import * as React from 'react'; window.React = React;</script>-->
<!-- <script src="../../src/packages/react-force-graph-2d/dist/react-force-graph-2d.js" defer></script>-->
</head>
<body>
<div id="graph"></div>
<script src="//unpkg.com/@babel/standalone"></script>
<script type="text/jsx" data-type="module">
import ForceGraph2D from 'https://esm.sh/react-force-graph-2d?external=react';
import React, { useState, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom';
import { forceCollide } from 'https://esm.sh/d3-force-3d';
const CollisionDetectionFG = () => {
const fgRef = useRef();
const [graphData, setGraphData] = useState({ nodes: [], links: [] });
useEffect(() => {
const fg = fgRef.current;
// Deactivate existing forces
fg.d3Force('center', null);
fg.d3Force('charge', null);
// Add collision and bounding box forces
fg.d3Force('collide', forceCollide(4));
fg.d3Force('box', () => {
const SQUARE_HALF_SIDE = N * 2;
nodes.forEach(node => {
const x = node.x || 0, y = node.y || 0;
// bounce on box walls
if (Math.abs(x) > SQUARE_HALF_SIDE) { node.vx *= -1; }
if (Math.abs(y) > SQUARE_HALF_SIDE) { node.vy *= -1; }
});
});
// Generate nodes
const N = 80;
const nodes = [...Array(N).keys()].map(() => ({
// Initial velocity in random direction
vx: (Math.random() * 2) - 1,
vy: (Math.random() * 2) - 1
}));
setGraphData({ nodes, links: [] });
}, []);
return <ForceGraph2D
ref={fgRef}
graphData={graphData}
cooldownTime={Infinity}
d3AlphaDecay={0}
d3VelocityDecay={0}
/>;
};
createRoot(document.getElementById('graph'))
.render(<CollisionDetectionFG />);
</script>
</body>