-
Notifications
You must be signed in to change notification settings - Fork 852
/
Copy pathindex.html
68 lines (58 loc) · 2.39 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
<head>
<style> body { margin: 0; } </style>
<script src="//unpkg.com/3d-force-graph"></script>
<!--<script src="../../dist/3d-force-graph.js"></script>-->
</head>
<body>
<div id="3d-graph"></div>
<script type="module">
import * as THREE from 'https://esm.sh/three';
import { scaleOrdinal, schemeRdYlGn, color as d3Color } from 'https://esm.sh/d3';
// Random tree
const N = 25;
const gData = {
nodes: [...Array(N).keys()].map(i => ({ id: i })),
links: [...Array(N).keys()]
.filter(id => id)
.map(id => ({
source: id,
target: Math.round(Math.random() * (id-1))
}))
};
const nodeColorScale = scaleOrdinal(schemeRdYlGn[4]);
const Graph = new ForceGraph3D(document.getElementById('3d-graph'))
.nodeColor(node => nodeColorScale(node.id))
.linkThreeObject(link => {
// 2 (nodes) x 3 (r+g+b) bytes between [0, 1]
// For example:
// new Float32Array([
// 1, 0, 0, // source node: red
// 0, 1, 0 // target node: green
// ]);
const colors = new Float32Array([].concat(
...[link.source, link.target]
.map(nodeColorScale)
.map(d3Color)
.map(({ r, g, b }) => [r, g, b].map(v => v / 255)
)));
const material = new THREE.LineBasicMaterial({ vertexColors: true });
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
return new THREE.Line(geometry, material);
})
.linkPositionUpdate((line, { start, end }) => {
const startR = Graph.nodeRelSize();
const endR = Graph.nodeRelSize();
const lineLen = Math.sqrt(['x', 'y', 'z'].map(dim => Math.pow((end[dim] || 0) - (start[dim] || 0), 2)).reduce((acc, v) => acc + v, 0));
const linePos = line.geometry.getAttribute('position');
// calculate coordinate on the node's surface instead of center
linePos.set([startR / lineLen, 1 - endR / lineLen].map(t =>
['x', 'y', 'z'].map(dim => start[dim] + (end[dim] - start[dim]) * t)
).flat());
linePos.needsUpdate = true;
return true;
})
.graphData(gData);
</script>
</body>