3d-force-graph笔记(2):快速入门

通过编写一个简单实例,快速上手。

安装

$ npm install 3d-force-graph

$ yarn add 3d-force-graph

导入

三种方式任选一。

import ForceGraph3D from '3d-force-graph';

var ForceGraph3D = require('3d-force-graph');

<script src="//unpkg.com/3d-force-graph"></script>

实例

创建ForceGraph3D对象,至少提供一个容器和一组关系数据。

import React, { useState, useEffect } from 'react';
import ForceGraph3D from '3d-force-graph';

export default function Demo(props) {
	useEffect(() => {
		const ele = document.getElementById('my-graph');
		const myGraph = ForceGraph3D();
		const myData = {
		    "nodes": [
		        {
		          "id": "id1",
		          "name": "name1",
		          "val": 1
		        },
		        {
		          "id": "id2",
		          "name": "name2",
		          "val": 10
		        }
		    ],
		    "links": [
		        {
		            "source": "id1",
		            "target": "id2"
		        }
		    ]
		};

		myGraph(ele).graphData(myData);
	}, []);

    return (
    	<>
    		<div id="my-graph"></div>
		</>
    )
}

实例中数据包含两个节点和一条关系,Demo为React组件,可以直接在React环境中使用。

注:3d-force-graph学习笔记系列中的代码块大部分会在React环境中编写。