UNPKG

3d-force-graph

Version:

UI component for a 3D force-directed graph using ThreeJS and d3-force-3d layout engine

68 lines (58 loc) 2.46 kB
<head> <style> body { margin: 0; } </style> <script src="//cdn.jsdelivr.net/npm/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>