前言
当我们需要使用模型绘制Mermaid图的时候,我们通常可以输入类似如下的提示词,只需要要求模型 "mermaid格式输出" 或者 "输出mermaid" 即可
以mermaid格式输出浏览器从输入ULR到解析出页面的完整过程
然后我们将得到一段mermaid代码
rust
sequenceDiagram
participant User
participant Browser
participant DNS
participant Server
participant RenderEngine
User->>Browser: 输入URL并回车
Browser->>Browser: 1. 解析URL
alt 缓存检查
Browser->>Browser: 检查强缓存(Expires/Cache-Control)
Browser-->>User: 命中缓存? 直接返回资源
else
Browser->>DNS: 2. DNS查询(递归查询)
DNS-->>Browser: 返回IP地址
Browser->>Server: 3. TCP三次握手建立连接
Browser->>Server: 4. 发送HTTP请求(GET /)
alt 需要协商缓存
Server->>Browser: 304 Not Modified
Browser->>Browser: 使用本地缓存
else
Server->>Browser: 5. 返回HTTP响应(200 OK + HTML)
end
Browser->>Server: 6. 断开连接(TCP四次挥手)
end
Browser->>Browser: 7. 解析HTML构建DOM树
Browser->>Browser: 8. 解析CSS构建CSSOM树
Browser->>Browser: 9. 合并DOM和CSSOM生成Render树
Browser->>Browser: 10. 布局计算(Layout/Reflow)
Browser->>Browser: 11. 绘制(Painting)
Browser->>RenderEngine: 12. 合成显示(Compositing)
Browser-->>User: 页面显示完成
在支持mermaid预览的模型平台或者mermaid官网使用在线编辑器得到预览效果

使用模型绘制图无疑是非常方便的,但是小溪建议mermaid深度使用者还是要学点mermaid基本知识和语法,模型不是万能的,也不可能完全理解我们的需求,对mermaid有基本了解,我们可以更大的发挥模型的作用且不至于当模型陷入死循环时而束手无策。
官网示例
先看两个官方示例,感受一下mermaid的魅力。
rust
sequenceDiagram
participant Alice
participant Bob
Alice->>John: Hello John, how are you?
loop HealthCheck
John->>John: Fight against hypochondria
end
Note right of John: Rational thoughts<br/>prevail...
John-->>Alice: Great!
John->>Bob: How about you?
Bob-->>John: Jolly good!

sql
sequenceDiagram
participant web as Web Browser
participant blog as Blog Service
participant account as Account Service
participant mail as Mail Service
participant db as Storage
Note over web,db: The user must be logged in to submit blog posts
web->>+account: Logs in using credentials
account->>db: Query stored accounts
db->>account: Respond with query result
alt Credentials not found
account->>web: Invalid credentials
else Credentials found
account->>-web: Successfully logged in
Note over web,db: When the user is authenticated, they can now submit new posts
web->>+blog: Submit new post
blog->>db: Store post data
par Notifications
blog--)mail: Send mail to blog subscribers
blog--)db: Store in-site notifications
and Response
blog-->>-web: Successfully posted
end
end

限制
- 全英文,需要一定英文阅读能力
- 免费套餐只能创建3个图
- 需要科学上网
优势
- 国内可用
- 有免费在线套餐
Mermaid
官网地址:mermaid.js.org/

在线编辑器
官网地址:mermaid.live/edit

Mermaid提供了Playground,只需在顶部打开【playground】切换到Playground即可

Playground提供了 可视化编程 和 AI对话两种模式 并提供实时预览
|------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| |
|
文档地址

注册登录
注册登录Mermaid可创建持久化图项目

登录成功后即可进入Mermaid管理后台

产品定价

基本使用
Mermaid提供了丰富的图类型,除了我们平时常用的 流程图 外,还支持 时序图、类图、甘特图 等。
流程图
官网文档:mermaid.js.org/syntax/flow...
流程图连线
连线
css
flowchart LR
A --- B

单向箭头
css
flowchart LR
A --> B

连线文本
css
flowchart LR
A-- A到B ---B
或者
flowchart LR
A---|A到B|B

箭头文本
css
flowchart LR
A-- A到B -->B
或者
flowchart LR
A-->|A到B|B

虚线文本
css
flowchart LR
A -.A到B.-> B
或者
flowchart LR
A -.-> |A到B|B

连线动画
kotlin
flowchart LR
A e1@--> B
e1@{ animate: true }

流程图的方向
css
graph TD
A --> B
B --> C

- graph:Mermaid 语法中定义流程图的关键词
- TD:布局方向的缩写,表示流程图的布局是从上到下(Top-Down),同理可知其他方向类型:
- LR(Left-Right):从左到右布局
- RL(Right-Left):从右到左布局
- TB(Top-Bottom):从上到下布局(与 TD 相同,只是另一种写法)
- BT(Bottom-Top):从下到上布局(注意没有DT写法)

流程图方向不支持从下到上,如果这么写就会报错

也可以使用flowchart代替graph

流程图节点备注
流程图节点后面使用[]可以为节点添加备注
css
flowchart LR
A[这是A] --> B[这是B]
flowchart LR
A["这是A"] --> B["这是B"]

流程图节点类型
流程图节点提供了很多类型的节点,这里展示一下常用的节点类型,详情的可查看流程图文档:mermaid.js.org/syntax/flow...
矩形节点
css
flowchart LR
A[这是A] --> B[这是B]

圆边节点
css
flowchart LR
A(这是A) --> B(这是B)

圆角节点
css
flowchart LR
A(这是A) --> B(这是B)

子例程节点
lua
flowchart LR
A[[这是A]] --> B[[这是B]]

圆柱形节点
css
flowchart LR
A[(这是A)] --> B[(这是B)]

条件节点
css
flowchart TB
A(这是A) --> B{这是B}

子流程图
子流程图节点语法如下,需要以end节点作为结束
arduino
subgraph title
graph definition
end
sql
flowchart TB
C1 --> A1
subgraph one
A1 --> A2
end
subgraph two
C1 --> C2
end

sql
flowchart TB
C1 --> A1
subgraph one[这是第一个模块]
A1 --> A2
end
subgraph two[这是第二个模块]
C1 --> C2
end

流程图节点事件
less
flowchart LR
A-->B
B-->C
C-->D
D-->E
click A "https://www.github.com" _blank
click B "https://www.github.com" "Open this in a new tab" _blank
click C href "https://www.github.com" _blank
click D href "https://www.github.com" "Open this in a new tab" _blank

时序图
官网文档:mermaid.js.org/syntax/sequ...
时序图participant
rust
sequenceDiagram
Alice->>John: 实线箭头
John-->>Alice: 虚线箭头
Alice-)John: See you later!
sequenceDiagram
participant Alice
participant John
Alice->>John: 实线箭头
John-->>Alice: 虚线箭头
Alice-)John: See you later!

时序图actor
less
sequenceDiagram
participant A as Alice
participant J as John
A->>J: 实线箭头
J-->>A: 虚线箭头
A-)J: See you later!

时序图别名
less
sequenceDiagram
participant A as Alice
participant J as John
A->>J: 实线箭头
J-->>A: 虚线箭头
A-)J: See you later!

时序图盒子
less
sequenceDiagram
box pink Alice & John
participant A
participant J
end
box Another Group
participant B
participant C
end
A->>J: Hello John, how are you?
J->>A: Great!
A->>B: Hello Bob, how is Charley?
B->>C: Hello Charley, how are you?

时序图活动
rust
sequenceDiagram
Alice->>John: Hello John, how are you?
activate John
John-->>Alice: Great!
deactivate John
或者
sequenceDiagram
Alice->>+John: Hello John, how are you?
John-->>-Alice: Great!

时序图备注
sql
sequenceDiagram
create participant John
Note right of John: Text in note

sql
sequenceDiagram
Alice->John: Hello John, how are you?
Note over Alice,John: A typical interaction

类图
官网文档:mermaid.js.org/syntax/clas...
创建类图
yaml
classDiagram
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()

类图继承
scss
classDiagram
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
Animal <|-- Duck
class Duck{
+String beakColor
+swim()
+quack()
}
Animal <|-- Fish
class Fish{
-int sizeInFeet
-canEat()
}

类图类型定义
csharp
classDiagram
class Square~Shape~{
int id
List~int~ position
setPoints(List~int~ points)
getPoints() List~int~
}
Square : -List~string~ messages
Square : +setMessages(List~string~ messages)
Square : +getMessages() List~string~
Square : +getDistanceMatrix() List~List~int~~

c
classDiagram
class BankAccount {
int id
string name
}
BankAccount : +owner() string
BankAccount : +deposit(amount)
BankAccount : +withdrawal(amount)

状态图
官网文档:mermaid.js.org/syntax/stat...
状态图开始与结束
状态图中使用[*]表示开始与结束节点
lua
stateDiagram
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]

状态图备注
lua
stateDiagram
Still --> Moving: 从still到moving

状态图复合模式
css
stateDiagram
[*] --> First
state First {
[*] --> second
second --> [*]
}
[*] --> NamedComposite
NamedComposite: Another Composite
state NamedComposite {
[*] --> namedSimple
namedSimple --> [*]
namedSimple: Another simple
}

sql
stateDiagram
[*] --> First
state First {
[*] --> Second
state Second {
[*] --> Third
Third --> [*]
}
}

sql
stateDiagram
[*] --> First
First --> Second
First --> Third
state First {
[*] --> fir
fir --> [*]
}
state Second {
[*] --> sec
sec --> [*]
}
state Third {
[*] --> thi
thi --> [*]
}

状态图选择
lua
stateDiagram
state if_state <<choice>>
[*] --> IsPositive
IsPositive --> if_state
if_state --> False: if n < 0
if_state --> True : if n >= 0

状态图分支
sql
stateDiagram
state fork_state <<fork>>
[*] --> fork_state
fork_state --> State2
fork_state --> State3
state join_state <<join>>
State2 --> join_state
State3 --> join_state
join_state --> State4
State4 --> [*]

实体关系图
官网文档:mermaid.js.org/syntax/enti...
实体关系图一对多
- o{和}o:表示0或多个
- }|和|{:表示至少至少一个
css
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM: contains
CUSTOMER }|..|{ DELIVERY-ADDRESS : uses

css
erDiagram
CAR ||--o{ NAMED-DRIVER : allows
PERSON }o..o{ NAMED-DRIVER : is

实体关系图属性
c
erDiagram
CUSTOMER ||--o{ ORDER : places
CUSTOMER {
string name
string custNumber
string sector
}
ORDER ||--|{ LINE-ITEM: contains
ORDER {
int orderNumber
string deliveryAddress
}
LINE-ITEM {
string productCode
int quantity
float pricePerUnit
}
CUSTOMER }|..|{ DELIVERY-ADDRESS : uses

甘特图
官网文档:mermaid.js.org/syntax/gant...
甘特图基本用法
less
gantt
title A Gantt Diagram
dateFormat YYYY-MM-DD
section Section
A task :a1, 2014-01-01, 30d
Another task :after a1, 20d
section Another
Task in Another :2014-01-12, 12d
another task :24d

甘特图里程碑
arduino
gantt
dateFormat HH:mm
axisFormat %H:%M
Initial milestone : milestone, m1, 17:49, 2m
Task A : 10m
Task B : 5m
Final milestone : milestone, m2, 18:08, 4m

饼图
官网文档:mermaid.js.org/syntax/pie....
饼图基本用法
csharp
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 15

饼图展示数据
csharp
pie showData
title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 15

饼图样式调整
csharp
%%{init: {"pie": {"textPosition": 0.5}, "themeVariables": {"pieOuterStrokeWidth": "5px"}} }%%
pie showData
title Key elements in Product X
"Calcium" : 42.96
"Potassium" : 50.05
"Magnesium" : 10.01
"Iron" : 5

思维导图
官网文档:mermaid.js.org/syntax/mind...
scss
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness<br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid

时间线图
官网文档:mermaid.js.org/syntax/time...
时间线图基本用法
yaml
timeline
title History of Social Media Platform
2002 : LinkedIn
2004 : Facebook
: Google
2005 : YouTube
2006 : Twitter

多级时间线图
less
timeline
title Timeline of Industrial Revolution
section 17th-20th century
Industry 1.0 : Machinery, Water power, Steam <br>power
Industry 2.0 : Electricity, Internal combustion engine, Mass production
Industry 3.0 : Electronics, Computers, Automation
section 21st century
Industry 4.0 : Internet, Robotics, Internet of Things
Industry 5.0 : Artificial intelligence, Big data, 3D printing

UML图
官网文档:mermaid.js.org/syntax/zenu...
UML图基本使用
rust
zenuml
title Demo
Alice->John: Hello John, how are you?
John->Alice: Great!
Alice->John: See you later!

UML图角色
scss
zenuml
title Annotators
@Actor Alice
@Database Bob
Alice->Bob: Hi Bob
Bob->Alice: Hi Alice

UML图嵌套
css
zenuml
A.method() {
B.nested_sync_method()
B->C: nested async message
}

XY图
官网文档:mermaid.js.org/syntax/xyCh...
yaml
xychart-beta
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
bar [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]
line [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]

方框图
官网文档:mermaid.js.org/syntax/bloc...
动态布局
less
block-beta
columns 3
a:3
block:group1:2
columns 2
h i j k
end
g
block:group2:3
%% columns auto (default)
l m n o p q r
end

箭头
scss
block-beta
blockArrowId<["Label"]>(right)
blockArrowId2<["Label"]>(left)
blockArrowId3<["Label"]>(up)
blockArrowId4<["Label"]>(down)
blockArrowId5<["Label"]>(x)
blockArrowId6<["Label"]>(y)

边框样式
scss
block-beta
columns 1
db(("DB"))
blockArrowId<[" "]>(down)
block:ID
A
B["A wide one in the middle"]
C
end
space
D
ID --> D
C --> D
style B fill:#939,stroke:#333,stroke-width:4px

系统架构
css
block-beta
columns 3
Frontend blockArrowId6<[" "]>(right) Backend
space:2 down<[" "]>(down)
Disk left<[" "]>(left) Database[("Database")]
classDef front fill:#696,stroke:#333;
classDef back fill:#969,stroke:#333;
class Frontend front
class Backend,Database back

看板图
官网文档:mermaid.js.org/syntax/kanb...
css
kanban
Todo
[Create Documentation]
docs[Create Blog about the new diagram]
[In progress]
id6[Create renderer so that it works in all cases. We also add som extra text here for testing purposes. And some more just for the extra flare.]
id9[Ready for deploy]
id8[Design grammar]@{ assigned: 'knsv' }
id10[Ready for test]
id4[Create parsing tests]@{ ticket: MC-2038, assigned: 'K.Sveidqvist', priority: 'High' }
id66[last item]@{ priority: 'Very Low', assigned: 'knsv' }
id11[Done]
id5[define getData]
id2[Title of diagram is more than 100 chars when user duplicates diagram with 100 char]@{ ticket: MC-2036, priority: 'Very High'}
id3[Update DB function]@{ ticket: MC-2037, assigned: knsv, priority: 'High' }
id12[Can't reproduce]
id3[Weird flickering in Firefox]

友情提示
本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。