JavaScript is required

编辑并保存的数据

完整的图编辑应用程序

功能齐全的图编辑器,具有本地存储、上下文菜单、工具栏以及交互式节点/线条创建。

完整的图编辑应用程序

功能概述

这是一个完整的图编辑应用程序,具有本地存储持久化、右键单击上下文菜单、工具栏控件以及交互式添加/删除节点和线条的功能。

核心特性实现

1. 本地存储持久化

保存和加载图数据:

const myLocalDataItemKey = 'rg-my-graph-app';

const initializeGraph = async () => {
    const mySavedDataString = localStorage.getItem(myLocalDataItemKey);
    const mySavedData = mySavedDataString ? JSON.parse(mySavedDataString) : null;

    if (mySavedData) {
        graphInstance.updateOptions({
            layout: { layoutName: 'fixed' }  // 使用固定布局以恢复位置
        });
        await graphInstance.setJsonData(mySavedData);
    } else {
        await graphInstance.setJsonData(myJsonData);
    }
};

const onSave = () => {
    const jsonData = graphInstance.getGraphJsonData();
    localStorage.setItem(myLocalDataItemKey, JSON.stringify(jsonData));
};

2. 右键单击上下文菜单

右键单击时显示上下文菜单:

const onContextmenu = (e: RGUserEvent, objectType: string, object: any) => {
    const xyOnGraphView = graphInstance.getViewXyByEvent(e);
    setMenuPos(xyOnGraphView);
    setCurrentObj({ type: objectType, data: object });
    setShowNodeTipsPanel(true);
};

3. 通过拖动添加节点

交互式节点创建:

const startAddNode = (e: React.MouseEvent | React.TouchEvent) => {
    const newNodeSize = { width: 140, height: 30 };
    graphInstance.startCreatingNodePlot(e.nativeEvent, {
        templateNode: { text: 'New Node', color: '#ffffff', ...newNodeSize },
        onCreateNode: (x, y) => {
            addNodeOnCanvas({
                x: x - newNodeSize.width / 2,
                y: y - newNodeSize.height / 2
            }, newNodeSize);
        }
    });
};

4. 通过拖动添加线条

交互式线条创建:

const startAddLine = (e: React.MouseEvent | React.TouchEvent) => {
    const newLineTemplate: JsonLineLike = {
        lineWidth: 2,
        color: '#cebf88ff',
        fontColor: '#cebf88ff',
        text: 'New Line'
    };

    graphInstance.startCreatingLinePlot(e.nativeEvent, {
        template: newLineTemplate,
        onCreateLine: (from, to) => {
            if (to && 'id' in to) {
                const lineId = graphInstance.generateNewUUID(5);
                graphInstance.addLines([{
                    id: lineId,
                    ...newLineTemplate,
                    from: from.id,
                    to: to.id,
                    text: `New Line-${lineId}`
                }]);
            }
        }
    });
};

5. 删除节点和线条

通过上下文菜单删除元素:

const handleDelete = () => {
    if (currentObj.type === 'node') {
        graphInstance.removeNodeById(currentObj.data.id);
    } else if (currentObj.type === 'line') {
        graphInstance.removeLineById(currentObj.data.id);
    }
};

创意使用场景

  • 图编辑器:构建自定义图编辑应用程序
  • 图表工具:创建流程图或图表编辑器
  • 规划工具:交互式规划和头脑风暴
  • 教育软件:交互式教授图概念
  • 白板应用程序:在线协作白板
  • 文档工具:可视化文档编辑器