用 mxgraph.js 打造超实用流程图:从入门到精通(附源码)
myzbx 2025-05-28 19:14 30 浏览
在技术快速发展的当下,流程图作为一种直观展示流程和逻辑关系的工具,在项目管理、软件开发、业务流程梳理等诸多领域发挥着重要作用。今天我就和大家分享一下如何使用 mxgraph.js 构建功能丰富的流程图,包含拖拽、框选、连线等功能,为有类似需求的技术小伙伴提供一份详细且实用的教程。
先演示一下我实现好的demo:
这个demo中具备的功能主要有:
- 创建基础形状
- 可编辑文本内容
- 支持拖拽元素大小
- 支持元素之间的连线
- 支持框选,多选移动
文末我会放这个案例的demo,大家可以基于这个demo轻松实现如下流程编辑器:
后面我打算将流程图集成到 flowmix/docx 多模态文档编辑器中,大家感兴趣也可以体验参考一下。
一、mxgraph.js 简介
mxgraph.js 是一款强大的 JavaScript 图表库,能够轻松创建交互式图表,包括流程图、组织结构图、UML 图等。它具有高度可定制性、跨平台支持以及丰富的文档和示例,使其成为开发者创建流程图的理想选择。 由于官方文档全英文,所以接下来给大家分享一下基础的使用方法。
二、准备工作
- 引入 mxgraph.js:可以从 mxgraph 的官方网站或 CDN 获取 mxgraph.js 文件,并在 HTML 文件中引入。
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,并将其绑定到之前创建的容器上。
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
每个月我们都会根据用户的需求和规划的迭代计划持续迭代, 大家可以参考一下.
相关推荐
- 大白话讲nnvm(大白话讲解什么是卷积)
-
之前工作经验中,在某大厂,开发过机器学习框架,在和业务同学的合作下,取得还可以的成绩,但是一直觉得缺少了什么,最近在刷ai-system相关的公开课,才明白计算图的重要性,以往觉得不能理解的东西,现在...
- Python之Json模块详解(python.json()用法)
-
Step1:Json是什么JSON(JavaScriptObjectNotation,JS对象标记)是一种轻量级的数据交换格式。具有数据格式简单,读写方便易懂等很多优点。许多主流的编程语言都...
- 最新潮最流行的影音资源——MAU影视
-
MAO影视,一款完全免费的影视软件,为您带来最新潮最流行的影音资源,软件本身并不具备任何资源,只是作为一款播放器提供给大家。配合相关的接口链接,即可为您呈现丰富多彩的影音节目。软件版本支持:1.安卓2...
- Python版的迷你程序——json文件转换为csv
-
浅话C语言是过去几十年软件和硬件两个阵营之间,签署的最坚实的契约。硬件为C语言的语义提供了最能发挥其性能的基础构件,而软件虽然搞了很多的圆环套圆环般的层次,但最终都以C语言作为最后的沉淀收尾。----...
- 没硬盘、网盘也能看片自由!NAS一键部署MoonTV,随时随地爽看。
-
本内容来源于@什么值得买APP,观点仅代表作者本人|作者:羊刀仙有没有一个应用服务,能满足既没有足够预算购置硬盘,也不想依托网盘的朋友的家庭观影需求?之前我介绍过LibreTV,本篇再来看看另一个更...
- 用云存储30分钟快速搭建APP,你信吗?
-
背景不管你承认与否,移动互联的时代已经到来,这是一个移动互联的时代,手机已经是当今世界上引领潮流的趋势,大型的全球化企业和中小企业都把APP程序开发纳入到他们的企业发展策略当中。但随着手机APP上传的...
- Python的dict和json区别(python中dict的特点)
-
大家有没有发现,python中的字典类型的数据结构,和我们目前比较流行的web端的json格式,非常类似,几乎有点分不清了。那么这2者的区别是什么呢?首先,从概念上,我们要理解这2者是截然不同的。py...
- 越晚搞懂 MySQL JSON 数据类型,你就越吃亏
-
作者介绍陈臣,甲骨文MySQL首席解决方案工程师,公众号《MySQL实战》作者,有大规模的MySQL,Redis,MongoDB,ES的管理和维护经验,擅长MySQL数据库的性能优化及日常操作的原理剖...
- 揭秘你不会画“信息结构图”的本质
-
编辑导语:产品信息结构图有助于清晰地展示产品信息,一定程度上可以为后台上传数据提供依据,但不少人可能觉得产品信息结构图很难,这可能是对数据库表结构不理解等因素导致的。本篇文章里,作者就产品信息结构图的...
- python之json基本操作(.json python)
-
1.概述JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,它具有简洁、清晰的层次结构,易于阅读和编写,还可以有效的提升网络传输效率。Python标准库的...
- JWT 和 JJWT 还傻傻的分不清吗(jwt jti)
-
JWTs是JSON对象的编码表示。JSON对象由零或多个名称/值对组成,其中名称为字符串,值为任意JSON值。JWT有助于在clear(例如在URL中)发送这样的信息,可以被信任为不可读(即加密的)、...
- 比json快20-100倍!protobuf原理深入剖析
-
一、protobuf语法指南1.1定义一个消息类型先来看一个非常简单的例子。假设你想定义一个“搜索请求”的消息格式,每一个请求含有一个查询字符串、你感兴趣的查询结果所在的页数,以及每一页多少条查询结...
- 了解一下ProtoBuf(了解一下相亲对象的年龄)
-
序列化与反序列化我们在进行网络通信调用的时候,总是需要将内存的数据块经过序列化,转换成为一种可以通过网络流进行传输的格式。而这种格式在经过了传输之后再经过序列化,能还原成我们预想中的数据结构。那么我们...
- JSON数据类型详细总结(json数据类型详细总结怎么写)
-
JSON详解一、JSON的概述及其使用JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。它基于javascript的一个子集。JSON是的数据交换语言,易...
- 接口自动化测试之JSON Schema模式该如何使用?
-
JSONSchema模式是一个词汇表,可用于注释和验证JSON文档。在实际工作中,对接口返回值进行断言校验,除了常用字段的断言检测以外,还要对其他字段的类型进行检测。对返回的字段一个个写断言显...
- 一周热门
- 最近发表
- 标签列表
-
- HTML 简介 (30)
- HTML 响应式设计 (31)
- HTML URL 编码 (32)
- HTML Web 服务器 (31)
- HTML 表单属性 (32)
- HTML 音频 (31)
- HTML5 支持 (33)
- HTML API (36)
- HTML 总结 (32)
- HTML 全局属性 (32)
- HTML 事件 (31)
- HTML 画布 (32)
- HTTP 方法 (30)
- 键盘快捷键 (30)
- CSS 语法 (35)
- CSS 轮廓宽度 (31)
- CSS 谷歌字体 (33)
- CSS 链接 (31)
- CSS 定位 (31)
- CSS 图片库 (32)
- CSS 图像精灵 (31)
- SVG 文本 (32)
- 时钟启动 (33)
- HTML 游戏 (34)
- JS Loop For (32)