需要用到three-forcegraph,然而网上很多文章都是关于3d-force-graph的,导致走了很多弯路。我反省!希望这篇文章对和我遇到同样问题的朋友有帮助。
官方解释
three-forcegraph three-forcegraph GitHub地址
3d-force-graph 3d-force-graph GitHub地址
我的理解
3d-force-graph=three-forcegraph+threejs+...
npm安装过3d-force-graph依赖之后,会发现,node-modules里有three-forcegraph:
简单来说,three-forcegraph用于生成图形数据结构,3d-force-graph使用three-forcegraph生成图形数据结构,再使用threejs初始化场景等进行渲染。下面两个文件的效果是一样的。
1.使用three-forcegraph
<head>
<style>
body {
margin: 0;
}
</style>
<!-- //unpkg.com 本地访问不到 -->
<!-- <script src="//unpkg.com/three"></script>
<script src="//unpkg.com/three/examples/js/controls/TrackballControls.js"></script>
<script src="//unpkg.com/three-forcegraph"></script> -->
<!-- 我找了其他threejs -->
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/TrackballControls.js"></script>
<script src="../../dist/three-forcegraph.js"></script>
</head>
<body>
<div id="3d-graph"></div>
<script>
// Gen random data
const N = 300;
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 Graph = new ThreeForceGraph().graphData(gData);
// Setup renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('3d-graph').appendChild(renderer.domElement);
// Setup scene
const scene = new THREE.Scene();
scene.add(Graph);
scene.add(new THREE.AmbientLight(0xbbbbbb));
// Setup camera
const camera = new THREE.PerspectiveCamera();
camera.far = 10000;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix(); //更新相机对象的投影矩阵属性
camera.lookAt(Graph.position);
camera.position.z = Math.cbrt(N) * 180; //给定数字的立方根
// Add camera controls
const tbControls = new THREE.TrackballControls(camera, renderer.domElement); //轨迹球控件
// Kick-off renderer
(function animate() {
// IIFE
Graph.tickFrame();
// Frame cycle
tbControls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
})();
</script>
</body>
2.使用3d-force-graph
<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>
// Random tree
const N = 300;
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 Graph = ForceGraph3D()(document.getElementById('3d-graph')).graphData(gData);
</script>
</body>