https://mp.weixin.qq.com/s/aqANBvb3vpGdVv-zHajEmA

二、准备工作
引入 mxgraph.js:可以从 mxgraph 的官方网站或 CDN 获取 mxgraph.js 文件,并在 HTML 文件中引入。


<!-- 引入 mxGraph 库 -->
<link href="https://cdn.jsdelivr.net/npm/mxgraph@4.2.2/javascript/src/css/common.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/mxgraph@4.2.2/javascript/mxClient.min.js"></script>
创建 HTML 结构:在 HTML 文件中创建一个容器,用于放置流程图。

<div id="graph-container"></div>

三、初始化 mxgraph
编写 JavaScript 代码:使用以下代码初始化 mxgraph,并将其绑定到之前创建的容器上。


// 获取容器元素
const container = document.getElementById('graph-container');
// 创建mxGraph实例
const graph = new mxGraph(container);
// 获取默认父节点
const parent = graph.getDefaultParent();
// 开始编辑会话
graph.getModel().beginUpdate();
try {
    // 添加一个示例节点
    const vertex = graph.insertVertex(parent, null, '示例节点', 20, 20, 80, 30);
} finally {
    // 结束编辑会话
    graph.getModel().endUpdate();
}

代码解释:上述代码首先获取了 HTML 中的容器元素,然后创建了 mxGraph 实例并将其绑定到该容器上。接着获取默认父节点,开始编辑会话,并在会话中添加了一个示例节点。最后结束编辑会话,确保图表的正确渲染。
四、实现拖拽功能
图片

mxgraph.js 默认支持节点的拖拽功能,无需额外编写代码。当用户在浏览器中打开包含上述代码的页面时,即可直接拖拽节点。

下面分享一下添加节点的代码:


addSampleNodes() {
    const parent = this.graph.getDefaultParent();
    this.graph.getModel().beginUpdate();
    try {
        const v1 = this.graph.insertVertex(parent, null, 'Start', 20, 20, 80, 30);
        const v2 = this.graph.insertVertex(parent, null, 'Process', 200, 20, 80, 30);
        const e1 = this.graph.insertEdge(parent, null, '', v1, v2);
    } finally {
        this.graph.getModel().endUpdate();
    }
}

五、实现框选功能
启用框选:mxgraph.js 提供了内置的框选功能,只需设置相应的属性即可启用。


// 允许连线
this.graph.setConnectable(true);
// 允许悬空边
this.graph.setAllowDanglingEdges(false);
// 允许调整大小
this.graph.setCellsResizable(true);
// 允许编辑
this.graph.setCellsEditable(true);
// 允许选择
this.graph.setCellsSelectable(true);
// 允许移动
this.graph.setCellsMovable(true);
// 允许弯曲边
this.graph.setEdgeLabelsMovable(false);

代码解释:通过设置这些属性,不仅启用了框选功能,还允许对选中的节点进行连接、编辑、调整大小、删除、克隆和拖拽等操作。
六、实现连线功能
图片

添加连线:使用以下代码在两个节点之间添加连线。


// 添加另一个示例节点
const vertex2 = graph.insertVertex(parent, null, '另一个节点', 200, 20, 80, 30);
// 添加连线
const edge = graph.insertEdge(parent, null, '连线', vertex, vertex2);
// 连接节点
connectNodes(sourceNode, targetNode) {
    const parent = this.graph.getDefaultParent();
    this.graph.getModel().beginUpdate();
    try {
        const newEdge = this.graph.insertEdge(parent, null, '', sourceNode, targetNode);
        return newEdge;
    } finally {
        this.graph.getModel().endUpdate();
    }
}

代码解释:首先添加了另一个节点,然后使用graph.insertEdge方法在两个节点之间创建了一条连线,并为连线添加了标签。
七、优化与扩展
样式定制:mxgraph.js 允许通过设置节点和边的样式属性来自定义图表的外观。

// 设置节点样式
const style = 'fillColor=#FF9900;strokeColor=#000000;rounded=1';
const vertex3 = graph.insertVertex(parent, null, '定制样式节点', 400, 20, 80, 30, style);
// 设置边样式
const edgeStyle ='strokeColor=#0099FF;strokeWidth=2;endArrow=classic';
const edge2 = graph.insertEdge(parent, null, '定制样式连线', vertex2, vertex3, edgeStyle);
事件监听:可以监听各种事件,如节点的点击、拖拽结束等,以实现更复杂的交互逻辑。

// 监听节点点击事件
graph.cells.forEach((cell) => {
    if (cell.vertex) {
        cell.addEventListener('click', () => {
            console.log('节点被点击:', cell.value);
        });
    }
});

目前我基于 mxgraph.js 已经把图形编辑封装成了一个js插件(FlowchartEditorPlugin),我们只需要用如下方式使用即可:

// 使用插件
const editor = new FlowchartEditorPlugin('flowchart-container');

// 示例:添加新节点并连接
const newNode = editor.addNode('End', 400, 20, 80, 30);
editor.connectNodes(editor.graph.model.cells[Object.keys(editor.graph.model.cells)[1]], newNode);

插件完整代码如下:

// 定义流程图编辑器插件类


class FlowchartEditorPlugin {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        if (!this.container) {
            throw new Error(`Container with id "${containerId}" not found.`);
        }
        this.init();
    }

    init() {
        // 检查浏览器是否支持 mxGraph
        if (!mxClient.isBrowserSupported()) {
            mxUtils.error('Browser is not supported!', 200, false);
            return;
        }

        // 创建 mxGraph 实例
        this.graph = new mxGraph(this.container);

        // 配置图形
        this.configureGraph();

        // 添加示例节点
        this.addSampleNodes();

        // 设置右键菜单
        this.setupContextMenu();

        // 设置多选拖拽
        this.setupMultiSelect();

        // 设置连线
        this.setupConnections();
    }

    configureGraph() {
        // 允许连线
        this.graph.setConnectable(true);
        // 允许悬空边
        this.graph.setAllowDanglingEdges(false);
        // 允许调整大小
        this.graph.setCellsResizable(true);
        // 允许编辑
        this.graph.setCellsEditable(true);
        // 允许选择
        this.graph.setCellsSelectable(true);
        // 允许移动
        this.graph.setCellsMovable(true);
        // 允许弯曲边
        this.graph.setEdgeLabelsMovable(false);
        this.graph.setConnectableEdges(false);
        this.graph.setDisconnectOnMove(false);
    }

    addSampleNodes() {
        const parent = this.graph.getDefaultParent();
        this.graph.getModel().beginUpdate();
        try {
            const v1 = this.graph.insertVertex(parent, null, 'Start', 20, 20, 80, 30);
            const v2 = this.graph.insertVertex(parent, null, 'Process', 200, 20, 80, 30);
            const e1 = this.graph.insertEdge(parent, null, '', v1, v2);
        } finally {
            this.graph.getModel().endUpdate();
        }
    }

    setupContextMenu() {
        this.graph.popupMenuHandler.factoryMethod = (menu, cell, evt) => {
            if (cell) {
                menu.addItem('Copy', null, () => {
                    this.copyCell(cell);
                });
                menu.addItem('Delete', null, () => {
                    this.deleteCell(cell);
                });
            }
        };
    }

    setupMultiSelect() {
        // 启用橡皮筋选择
        new mxRubberband(this.graph);
    }

    setupConnections() {
        // 设置连接样式
        this.graph.connectionHandler.createEdgeState = (me) => {
            const edge = this.graph.createEdge(null, null, '', null, null);
            return new mxCellState(this.graph.view, edge, this.graph.getCellStyle(edge));
        };
    }

    addNode(label, x, y, width, height) {
        const parent = this.graph.getDefaultParent();
        this.graph.getModel().beginUpdate();
        try {
            const newNode = this.graph.insertVertex(parent, null, label, x, y, width, height);
            return newNode;
        } finally {
            this.graph.getModel().endUpdate();
        }
    }

    connectNodes(sourceNode, targetNode) {
        const parent = this.graph.getDefaultParent();
        this.graph.getModel().beginUpdate();
        try {
            const newEdge = this.graph.insertEdge(parent, null, '', sourceNode, targetNode);
            return newEdge;
        } finally {
            this.graph.getModel().endUpdate();
        }
    }

    copyCell(cell) {
        const clone = this.graph.cloneCells([cell])[0];
        clone.geometry.x += 10;
        clone.geometry.y += 10;
        this.graph.addCell(clone);
    }

    deleteCell(cell) {
        this.graph.removeCells([cell]);
    }
}
文档更新时间: 2025-02-16 08:07   作者:admin