index.html 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <head>
  2. <style> body { margin: 0; } </style>
  3. <script src="//unpkg.com/three"></script>
  4. <script src="//unpkg.com/d3"></script>
  5. <script src="//unpkg.com/3d-force-graph"></script>
  6. <!--<script src="../../dist/3d-force-graph.js"></script>-->
  7. </head>
  8. <body>
  9. <div id="3d-graph"></div>
  10. <script>
  11. // Random tree
  12. const N = 25;
  13. const gData = {
  14. nodes: [...Array(N).keys()].map(i => ({ id: i })),
  15. links: [...Array(N).keys()]
  16. .filter(id => id)
  17. .map(id => ({
  18. source: id,
  19. target: Math.round(Math.random() * (id-1))
  20. }))
  21. };
  22. const nodeColorScale = d3.scaleOrdinal(d3.schemeRdYlGn[4]);
  23. const Graph = ForceGraph3D()
  24. (document.getElementById('3d-graph'))
  25. .nodeColor(node => nodeColorScale(node.id))
  26. .linkThreeObject(link => {
  27. // 2 (nodes) x 3 (r+g+b) bytes between [0, 1]
  28. // For example:
  29. // new Float32Array([
  30. // 1, 0, 0, // source node: red
  31. // 0, 1, 0 // target node: green
  32. // ]);
  33. const colors = new Float32Array([].concat(
  34. ...[link.source, link.target]
  35. .map(nodeColorScale)
  36. .map(d3.color)
  37. .map(({ r, g, b }) => [r, g, b].map(v => v / 255)
  38. )));
  39. const material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors });
  40. const geometry = new THREE.BufferGeometry();
  41. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  42. geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
  43. return new THREE.Line(geometry, material);
  44. })
  45. .linkPositionUpdate((line, { start, end }) => {
  46. const startR = Graph.nodeRelSize();
  47. const endR = Graph.nodeRelSize();
  48. const lineLen = Math.sqrt(['x', 'y', 'z'].map(dim => Math.pow((end[dim] || 0) - (start[dim] || 0), 2)).reduce((acc, v) => acc + v, 0));
  49. const linePos = line.geometry.getAttribute('position');
  50. // calculate coordinate on the node's surface instead of center
  51. linePos.set([startR / lineLen, 1 - endR / lineLen].map(t =>
  52. ['x', 'y', 'z'].map(dim => start[dim] + (end[dim] - start[dim]) * t)
  53. ).flat());
  54. linePos.needsUpdate = true;
  55. return true;
  56. })
  57. .graphData(gData);
  58. </script>
  59. </body>