【React】基于Echarts实现关系图(图谱graph)

news/2024/7/15 19:20:08 标签: react.js, echarts, 前端

效果

在这里插入图片描述

环境

  • echarts: ^5.5.0
  • lodash: ^4.17.21
  • next: 14.1.3
  • react: ^18

目录

仅包含涉及到的文件

| - app
   |- page.tsx
| - components
    |- echarts
       |- graph
          |- echarts.ts
          |- index.tsx

实操

创建EchartsGraph组件

"use client"

import react, {useEffect, useRef} from "react";
import EchartsContainer from "./echarts"

type Props = {
    nodes: object[],
    edges: object[],
    categories: object[]
}

const ChartBoxStyles:react.CSSProperties = {
    width: '100%',
    height: '100%'
}

const EchartsGraph = function (props: Props) {
    let echartsRef = useRef<HTMLDivElement>(null);

    useEffect(()=>{
        const chart = EchartsContainer(echartsRef.current);
        chart.setOption({
            legend: [
                {
                    data: props.categories.map(function (a:any) {
                        return a.name;
                    })
                }
            ],
            series: [
                {
                    nodes: props.nodes,
                    edges: props.edges,
                    categories: props.categories,
                }
            ]
        });
        // 绑定鼠标松开触发事件,用于固定节点
        chart.on('mouseup', function (params: any) {
            let option = chart.getOption();
            option.series[0].nodes[params.dataIndex].x = params.event.offsetX || option.series[0].nodes[params.dataIndex].x;
            option.series[0].nodes[params.dataIndex].y = params.event.offsetY || option.series[0].nodes[params.dataIndex].y;
            option.series[0].nodes[params.dataIndex].fixed = true;
            chart.setOption(option);
        })

    }, [])

    return (
        <div ref={echartsRef} style={ChartBoxStyles}/>
    )
}

export default EchartsGraph
import type { EChartsType } from "echarts"
import _ from "lodash"
import * as echarts from "echarts"

class EchartsContainer {
    protected _echarts: EChartsType|null = null;
    protected _option:any = {}

    constructor(dom?:HTMLElement) {
        if (!window || !dom)throw Error('Not Set HTMLElement')

        this._echarts = echarts.init(dom);
        this._echarts?.showLoading();
        this._initOption();
    }

    private _initOption(){
        this._option.tooltip = {};
        this._option.legend = [];
        this._option.series = [
            {
                type: 'graph',
                // 布局: none、circular、force
                layout: 'force',
                // 开启动画
                animation: true,
                // 初始动画的时长
                animationDuration: 1500,
                // 数据更新动画的缓动效果
                animationEasingUpdate: 'quinticInOut',
                // 边两端的标记类型
                // @link https://echarts.apache.org/zh/option.html#series-graph.edgeSymbol
                edgeSymbol: ['arrow', ''],
                // @link https://echarts.apache.org/zh/option.html#series-graph.force
                force: {
                    // 边的两个节点之间的距离,这个距离也会受 repulsion。
                    // 值最大的边长度会趋向于 10,值最小的边长度会趋向于 50
                    edgeLength: 120,
                    // 节点之间的斥力因子
                    repulsion: 500,
                    // 节点受到的向中心的引力因子(该值越大节点越往中心点靠拢)。
                    gravity: .2,
                    // 减缓节点的移动速度(取值范围 0 到 1)
                    friction: .6
                },
                // 是否开启鼠标缩放和平移漫游
                roam: true,
                // 节点是否可拖拽
                draggable: true,
                // 高亮状态的图形样式
                // @link https://echarts.apache.org/zh/option.html#series-graph.emphasis
                // DEPRECATED: itemStyle.emphasis has been changed to emphasis.itemStyle since 4.0
                emphasis:{
                    //鼠标放上去有阴影效果
                    itemStyle: {
                        shadowColor: '#cccccc',
                        shadowOffsetX: 0,
                        shadowOffsetY: 0,
                        shadowBlur: 40,
                    },
                },
                // 文本标签配置
                // @link https://echarts.apache.org/zh/option.html#series-graph.label
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{b}'
                },
                // 标签的统一布局配置
                // @link https://echarts.apache.org/zh/option.html#series-graph.labelLayout
                // labelLayout: {
                //     hideOverlap: true,
                // },
                // 针对节点之间存在多边的情况,自动计算各边曲率,默认不开启。
                // @link https://echarts.apache.org/zh/option.html#series-graph.autoCurveness
                // autoCurveness: true,
                // 滚轮缩放的极限控制
                // @link https://echarts.apache.org/zh/option.html#series-graph.scaleLimit
                scaleLimit: {
                    min: 0.4,
                    max: 2
                },
                // 关系边的公用线条样式
                // @link https://echarts.apache.org/zh/option.html#series-graph.lineStyle
                lineStyle: {
                    color: 'source',
                    // 边的曲度,支持从 0 到 1 的值,值越大曲度越大。
                    curveness: .3
                },
                categories: [],
            }
        ];

        this.setOption(this._option);
        this._echarts?.hideLoading();
    }

    public setOption(option: any){
        if (Object.keys(option).length>0){
            this._echarts?.setOption(_.merge({}, this._option, option))
        }
    }

    public getOption(){
        return this._echarts?.getOption();
    }

    public on(event: string, handler: any){
        this._echarts?.on(event, handler)
    }
}

const getSingle = (className: any) => {
    if (typeof className !== 'function') {
        throw('参数必须为一个类或一个函数')
    }
    const single = (fn: Function) => {
        let instance:any = null
        return (...args:any[]) => {
            if (!instance) {
                instance = fn.call(null, ...args)
            }
            return instance;
        }
    }
    const fn = (...args: any[]) => {
        return new className(...args);
    };
    return single(fn);
}

export default getSingle(EchartsContainer)

页面调用

demo数据源于官方的一个演示接口数据:
https://echarts.apache.org/examples/data/asset/data/les-miserables.json

import EchartsGraph from "@/components/echarts/graph";
import demoData from "./demo"

export default function Home() {

  return (
    <main style={{
        width: '100%',
        height: '100vh'
    }}>
      <EchartsGraph nodes={demoData.nodes}
                    edges={demoData.links}
                    categories={demoData.categories} />
    </main>
  );
}

http://www.niftyadmin.cn/n/5424647.html

相关文章

面试经典-3-合并区间

题目 以数组 intervals 表示若干个区间的集合&#xff0c;其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间&#xff0c;并返回 一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中的所有区间 。 示例 1&#xff1a; 输入&#xff1a;intervals…

【大厂面试演练】知道ZooKeeper有什么应用场景吗

面试官&#xff1a;咳咳咳&#xff0c;看你简历写了精通ZooKeeper&#xff0c;那我就随便考考你吧 面试官&#xff1a;不用慌尽管说&#xff0c;错了也没关系&#x1f60a;。。。 每日分享大厂面试演练&#xff0c;感兴趣就关注我吧❤️ 面试官&#xff1a;知道ZooKeeper有什么…

突破编程_C++_设计模式(命令模式)

1 命令模式的基本概念 C 命令模式是一种设计模式&#xff0c;它允许将请求封装为一个对象&#xff0c;从而可以用不同的请求对客户进行参数化&#xff1b;对请求排队或记录请求日志&#xff0c;以及支持可撤销的操作。命令模式的主要目的是将请求封装为对象&#xff0c;从而可…

Python学习:首选开发环境VScode

Visual Studio Code 打开官网 https://code.visualstudio.com/&#xff0c;下载软件包&#xff0c;一步步安装即可。 我认为Visual Studio Code最好的Web前端开发工具。 Visual Studio Code是什么 Visual Studio Code (简称 VS Code) 是一款由 Microsoft 开发的轻量级、免费和…

[leetcode~dfs]1261. 在受污染的二叉树中查找元素

给出一个满足下述规则的二叉树&#xff1a; root.val 0 如果 treeNode.val x 且 treeNode.left ! null&#xff0c;那么 treeNode.left.val 2 * x 1 如果 treeNode.val x 且 treeNode.right ! null&#xff0c;那么 treeNode.right.val 2 * x 2 现在这个二叉树受到「污…

vue项目:webpack打包优化实践

本文目录 一、项目基本信息二、分析当前项目情况1、使用 webpack-bundle-analyzer 插件2、使用 speed-measure-webpack-plugin 插件 三、解决构建问题1、caniuse-lite 提示的问题2、 warning 问题 四、打包速度优化1、修改source map2、处理 loader 五、webpack性能优化1、使用…

课时62:流程控制_if条件控制_其他实践

2.2.4 其他实践 学习目标 这一节&#xff0c;我们从 条件进阶、单行命令、小结 三个方面来学习。 条件进阶 简介 if条件控制语句支持(())来代替let命令测试表达式的执行效果&#xff0c;支持[[]]实现正则级别的内容匹配。表达式的样式如下&#xff1a; if (( 表达式 )) 或…

easyExcel 导入、导出Excel 封装公共的方法

文档包含三部分功能 1、easyExcel 公共导出list<对象>方法 2、easyExcel 导入逻辑 3、easyExcel 自定义导出 list<map> 、 list<对象> &#xff08;可优化&#xff09; 1、easyExcel 公共导出方法 1&#xff09;依赖&#xff1a; <!-- hutool --> …