在技术快速发展的当下,流程图作为一种直观展示流程和逻辑关系的工具,在项目管理、软件开发、业务流程梳理等诸多领域发挥着重要作用。今天我就和大家分享一下如何使用 mxgraph.js 构建功能丰富的流程图,包含拖拽、框选、连线等功能,为有类似需求的技术小伙伴提供一份详细且实用的教程。
先演示一下我实现好的demo:
这个demo中具备的功能主要有:
- 创建基础形状
- 可编辑文本内容
- 支持拖拽元素大小
- 支持元素之间的连线
- 支持框选,多选移动
文末我会放这个案例的demo,大家可以基于这个demo轻松实现如下流程编辑器:
后面我打算将流程图集成到 flowmix/docx 多模态文档编辑器中,大家感兴趣也可以体验参考一下。
一、mxgraph.js 简介
mxgraph.js 是一款强大的 JavaScript 图表库,能够轻松创建交互式图表,包括流程图、组织结构图、UML 图等。它具有高度可定制性、跨平台支持以及丰富的文档和示例,使其成为开发者创建流程图的理想选择。 由于官方文档全英文,所以接下来给大家分享一下基础的使用方法。
二、准备工作
- 引入 mxgraph.js:可以从 mxgraph 的官方网站或 CDN 获取 mxgraph.js 文件,并在 HTML 文件中引入。
html
<script src="https://cdn.jsdelivr.net/npm/mxgraph@4.2.2/javascript/mxClient.min.js"></script>
- 创建 HTML 结构:在 HTML 文件中创建一个容器,用于放置流程图。
三、初始化 mxgraph
- 编写 JavaScript 代码:使用以下代码初始化 mxgraph,并将其绑定到之前创建的容器上。
js// 获取容器元素
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 默认支持节点的拖拽功能,无需额外编写代码。当用户在浏览器中打开包含上述代码的页面时,即可直接拖拽节点。
下面分享一下添加节点的代码:
jsaddSampleNodes() {
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 提供了内置的框选功能,只需设置相应的属性即可启用。
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);
- 代码解释:通过设置这些属性,不仅启用了框选功能,还允许对选中的节点进行连接、编辑、调整大小、删除、克隆和拖拽等操作。
六、实现连线功能
- 添加连线:使用以下代码在两个节点之间添加连线。
js// 添加另一个示例节点
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),我们只需要用如下方式使用即可:
js// 使用插件
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);
插件完整代码如下:
js// 定义流程图编辑器插件类
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]);
}
}
八、总结
通过本文的教程,我们可以轻松掌握使用 mxgraph.js 创建支持拖拽、框选、连线的流程图的基本方法。
mxgraph.js 的强大功能远不止于此,我们可以进一步探索其文档,了解更多高级功能,如布局算法、数据绑定等,以满足不同场景下的需求。希望本文能帮助你在项目中快速应用 mxgraph.js,提升工作效率和用户体验。
最近我们做了一款文档管理类Saas系统, 底层基于Flowmix/Docx 多模态文档引擎, 这里简单和大家分享一下:
大家可以注册使用来管理自己的内容知识文档, 同时能一键生成自己的专属知识库.
文档地址: https://orange.turntip.cn/doc
每个月我们都会根据用户的需求和规划的迭代计划持续迭代, 大家可以参考一下.