Skip to content

用法

¥Usage

Mermaid 是一个 JavaScript 工具,它使用基于 Markdown 的语法来渲染可定制的图表、图表和可视化效果。

¥Mermaid is a JavaScript tool that makes use of a Markdown based syntax to render customizable diagrams, charts and visualizations.

可以通过修改图表的描述来重新渲染/修改图表。

¥Diagrams can be re-rendered/modified by modifying their descriptions.

CDN

https://www.jsdelivr.com/package/npm/mermaid

请注意,你可以通过右上角的下拉框切换版本。

¥Please note that you can switch versions through the dropdown box at the top right.

使用 Mermaid

¥Using mermaid

对于大多数用户来说,使用 在线编辑器 就足够了,但是你也可以选择将 mermaid 部署为依赖或使用 Mermaid API

¥For the majority of users, Using the Live Editor would be sufficient, however you may also opt to deploy mermaid as a dependency or using the Mermaid API.

我们整理了一些有关如何使用 Mermaid Live Editor 的视频 教程

¥We have compiled some Video Tutorials on how to use the Mermaid Live Editor.

在网页上安装和托管 Mermaid

¥Installing and Hosting Mermaid on a Webpage

使用 npm 包:

¥Using the npm package:

要求:

¥Requirements:

  • Node >= 16
bash
# NPM
npm install mermaid
# Yarn
yarn add mermaid
# PNPM
pnpm add mermaid

在网页上托管 Mermaid:

¥Hosting mermaid on a web page:

注意:该主题在 初学者用户指南 中进行了更深入的探讨

¥Note: This topic is explored in greater depth in the User Guide for Beginners

在网页上集成 Mermaid 的最简单方法需要两个元素:

¥The easiest way to integrate mermaid on a web page requires two elements:

  • 图形定义,位于标记为 class=mermaid<pre> 标签内。

    ¥A graph definition, inside <pre> tags labeled class=mermaid.

示例:

¥Example:

html
<pre class="mermaid">
    graph LR
    A --- B
    B-->C[fa:fa-ban forbidden]
    B-->D(fa:fa-spinner);
</pre>
  • Mermaid js 脚本。添加使用 script 标签作为 ESM 导入。

    ¥The mermaid js script. Added using a script tag as an ESM import.

示例:

¥Example:

html
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
</script>

按照这些指示,mermaid 在页面加载时启动,(当页面加载时)它将使用 class="mermaid" 找到 pre 标签内的图形定义,并按照给定的定义以 SVG 形式返回图表。

¥Following these directions, mermaid starts at page load and (when the page has loaded) it will locate the graph definitions inside the pre tags with class="mermaid" and return diagrams in SVG form, following given definitions.

简单完整的例子:

¥Simple full example:

html
<!doctype html>
<html lang="en">
  <body>
    <pre class="mermaid">
  graph LR
      A --- B
      B-->C[fa:fa-ban forbidden]
      B-->D(fa:fa-spinner);
    </pre>
    <script type="module">
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    </script>
  </body>
</html>

注意:

¥Notes:

id 属性也被添加到没有 id 的 Mermaid 标签中。

¥An id attribute is also added to mermaid tags without one.

Mermaid 可以在同一页面中加载多个图表。

¥Mermaid can load multiple diagrams, in the same page.

尝试一下,将此代码保存为 HTML 并使用任何浏览器加载它。(除 Internet Explorer 外,请勿使用 Internet Explorer。)

¥Try it out, save this code as HTML and load it using any browser. (Except Internet Explorer, please don't use Internet Explorer.)

启用节点中的点击事件和标签

¥Enabling Click Event and Tags in Nodes

必须首先清除 securityLevel 配置。securityLevel 设置解析图表的信任级别并限制单击功能。这是在 8.2 版本中作为安全改进引入的,旨在防止恶意使用。

¥A securityLevel configuration has to first be cleared. securityLevel sets the level of trust for the parsed diagrams and limits click functionality. This was introduced in version 8.2 as a security improvement, aimed at preventing malicious use.

网站所有者有责任区分可信和不可信的用户群,我们鼓励谨慎使用。

¥It is the site owner's responsibility to discriminate between trustworthy and untrustworthy user-bases and we encourage the use of discretion.

securityLevel

参数描述类型必需的
securityLevel解析图的信任级别字符串可选的'sandbox'、'strict'、'loose'、'antiscript'

值:

¥Values:

  • strict:(默认)文本中的 HTML 标记已编码,并且单击功能被禁用。

    ¥strict: (default) HTML tags in the text are encoded and click functionality is disabled.

  • 反标:允许文本中的 HTML 标签(仅删除脚本元素)并启用单击功能。

    ¥antiscript: HTML tags in text are allowed (only script elements are removed) and click functionality is enabled.

  • loose:允许文本中包含 HTML 标签,并启用单击功能。

    ¥loose: HTML tags in text are allowed and click functionality is enabled.

  • sandbox:在此安全级别下,所有渲染都在沙盒 iframe 中进行。这可以防止任何 JavaScript 在上下文中运行。这可能会阻碍图表的交互功能,例如脚本、序列图中的弹出窗口、到其他选项卡或目标的链接等。

    ¥sandbox: With this security level, all rendering takes place in a sandboxed iframe. This prevents any JavaScript from running in the context. This may hinder interactive functionality of the diagram, like scripts, popups in the sequence diagram, links to other tabs or targets, etc.

INFO

This changes the default behaviour of mermaid so that after upgrade to 8.2, unless the securityLevel is not changed, tags in flowcharts are encoded as tags and clicking is disabled. sandbox security level is still in the beta version.

如果你负责图表源安全,你可以将 securityLevel 设置为你选择的值。这允许点击和标签。

¥If you are taking responsibility for the diagram source security you can set the securityLevel to a value of your choosing. This allows clicks and tags are allowed.

要更改 securityLevel,你必须调用 mermaid.initialize

¥To change securityLevel, you have to call mermaid.initialize:

javascript
mermaid.initialize({
  securityLevel: 'loose',
});

标签超出范围

¥Labels out of bounds

如果你使用通过 CSS 加载的动态加载字体,例如字体,mermaid 应该等待整个页面加载(dom + asset,特别是字体文件)。

¥If you use dynamically loaded fonts that are loaded through CSS, such as fonts, mermaid should wait for the whole page to load (dom + assets, particularly the fonts file).

javascript
$(document).ready(function () {
  mermaid.initialize();
});

不这样做很可能会导致 Mermaid 渲染图的标签超出范围。mermaid 中的默认集成使用 window.load 事件来开始渲染。

¥Not doing so will most likely result in mermaid rendering graphs that have labels out of bounds. The default integration in mermaid uses the window.load event to start rendering.

如果你的页面正文中有其他字体,则可能会使用这些字体来代替 Mermaid 字体。在样式中指定字体是解决此问题的方法。

¥If your page has other fonts in its body those might be used instead of the mermaid font. Specifying the font in your styling is a workaround for this.

css
pre.mermaid {
  font-family: 'trebuchet ms', verdana, arial;
}

使用 mermaid.run

¥Using mermaid.run

mermaid.run 是在 v10 中添加的,是处理更复杂集成的首选方式。默认情况下,当文档准备好时,将调用 mermaid.run,用 class="mermaid" 渲染所有元素。

¥mermaid.run was added in v10 and is the preferred way of handling more complex integration. By default, mermaid.run will be called when the document is ready, rendering all elements with class="mermaid".

你可以通过调用 await mermaid.run(<config>) 来自定义该行为。

¥You can customize that behavior by calling await mermaid.run(<config>).

mermaid.initialize({startOnLoad: false}) 将阻止 mermaid.run 在加载后被自动调用。

¥mermaid.initialize({startOnLoad: false}) will prevent mermaid.run from being called automatically after load.

使用 querySelector ".someOtherClass" 渲染所有元素

¥Render all elements with querySelector ".someOtherClass"

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  querySelector: '.someOtherClass',
});

渲染作为数组传递的所有元素

¥Render all elements passed as an array

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  nodes: [document.getElementById('someId'), document.getElementById('anotherId')],
});
await mermaid.run({
  nodes: document.querySelectorAll('.yetAnotherClass'),
});

渲染所有 .mermaid 元素,同时抑制任何错误

¥Render all .mermaid elements while suppressing any error

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  suppressErrors: true,
});

调用 mermaid.init - 已弃用

¥Calling mermaid.init - Deprecated

WARNING

mermaid.init is deprecated in v10 and will be removed in v11. Please use mermaid.run instead.

默认情况下,当文档准备好时,会调用 mermaid.init,查找所有带有 class="mermaid" 的元素。如果你在加载 mermaid 后添加内容,或者需要对此行为进行更细粒度的控制,你可以使用以下命令自行调用 init

¥By default, mermaid.init will be called when the document is ready, finding all elements with class="mermaid". If you are adding content after mermaid is loaded, or otherwise need finer-grained control of this behavior, you can call init yourself with:

  • 配置对象

    ¥a configuration object

  • 一些节点,如

    ¥some nodes, as

    • 一个节点

      ¥a node

    • 类似数组的节点

      ¥an array-like of nodes

    • 或 W3C 选择器将找到你的节点

      ¥or W3C selector that will find your nodes

示例:

¥Example:

javascript
mermaid.init({ noteMargin: 10 }, '.someOtherClass');

或者没有配置对象,并且有 jQuery 选择:

¥Or with no config object, and a jQuery selection:

javascript
mermaid.init(undefined, $('#someId .yetAnotherClass'));

WARNING

This type of integration is deprecated. Instead the preferred way of handling more complex integration is to use the mermaidAPI instead.

与 webpack 一起使用

¥Usage with webpack

mermaid 完全支持 webpack。这是 工作演示

¥mermaid fully supports webpack. Here is a working demo.

API 使用

¥API usage

该 API 的主要思想是能够使用图形定义作为字符串来调用渲染函数。渲染函数将渲染图形并使用生成的 SVG 代码调用回调。通过这种方法,站点创建者可以从站点(可能从文本区域)获取图形定义,进行渲染并将图形放置在站点中的某个位置。

¥The main idea of the API is to be able to call a render function with the graph definition as a string. The render function will render the graph and call a callback with the resulting SVG code. With this approach it is up to the site creator to fetch the graph definition from the site (perhaps from a textarea), render it and place the graph somewhere in the site.

下面的示例显示了如何使用它的示例。该示例只是将生成的 SVG 记录到 JavaScript 控制台。

¥The example below shows an example of how this could be used. The example just logs the resulting SVG to the JavaScript console.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  mermaid.initialize({ startOnLoad: false });

  // Example of using the render function
  const drawDiagram = async function () {
    element = document.querySelector('#graphDiv');
    const graphDefinition = 'graph TB\na-->b';
    const { svg } = await mermaid.render('graphDiv', graphDefinition);
    element.innerHTML = svg;
  };

  await drawDiagram();
</script>

要确定给定文本中存在的图表类型,你可以使用 mermaid.detectType 函数,如下例所示。

¥To determine the type of diagram present in a given text, you can utilize the mermaid.detectType function, as demonstrated in the example below.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  const graphDefinition = `sequenceDiagram
    Pumbaa->>Timon:I ate like a pig.
    Timon->>Pumbaa:Pumbaa, you ARE a pig.`;
  try {
    const type = mermaid.detectType(graphDefinition);
    console.log(type); // 'sequence'
  } catch (error) {
    // UnknownDiagramError
  }
</script>

绑定事件

¥Binding events

有时,生成的图表还具有定义的交互,例如工具提示和单击事件。使用 API 时,必须在将图形插入 DOM 后添加这些事件。

¥Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must add those events after the graph has been inserted into the DOM.

下面的示例代码是 mermaid 使用 API 时所做操作的摘录。该示例展示了在使用 API 进行渲染时如何将事件绑定到 SVG。

¥The example code below is an extract of what mermaid does when using the API. The example shows how it is possible to bind events to an SVG when using the API for rendering.

javascript
// Example of using the bindFunctions
const drawDiagram = async function () {
  element = document.querySelector('#graphDiv');
  const graphDefinition = 'graph TB\na-->b';
  const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
  element.innerHTML = svg;
  // This can also be written as `bindFunctions?.(element);` using the `?` shorthand.
  if (bindFunctions) {
    bindFunctions(element);
  }
};
  1. 该图是使用渲染调用生成的。

    ¥The graph is generated using the render call.

  2. 生成后,渲染函数调用提供的回调函数,在本例中称为 insertSvg。

    ¥After generation the render function calls the provided callback function, in this case it's called insertSvg.

  3. 使用两个参数调用回调函数:生成的图形的 SVG 代码和一个函数。该函数在将 SVG 插入 DOM 后将事件绑定到 SVG。

    ¥The callback function is called with two parameters, the SVG code of the generated graph and a function. This function binds events to the SVG after it is inserted into the DOM.

  4. 将 SVG 代码插入 DOM 中进行演示。

    ¥Insert the SVG code into the DOM for presentation.

  5. 调用绑定事件的绑定函数。

    ¥Call the binding function that binds the events.

标记渲染器的示例

¥Example of a marked renderer

这是用于将文档从 Markdown 转换为 html 的渲染器,其中 html 中有 Mermaid 图。

¥This is the renderer used for transforming the documentation from Markdown to html with mermaid diagrams in the html.

javascript
const renderer = new marked.Renderer();
renderer.code = function (code, language) {
  if (code.match(/^sequenceDiagram/) || code.match(/^graph/)) {
    return '<pre class="mermaid">' + code + '</pre>';
  } else {
    return '<pre><code>' + code + '</code></pre>';
  }
};

CoffeeScript 中的另一个示例也在生成的标记中包含 Mermaid 脚本标签。

¥Another example in CoffeeScript that also includes the mermaid script tag in the generated markup.

coffee
marked = require 'marked'

module.exports = (options) ->
  hasMermaid = false
  renderer = new marked.Renderer()
  renderer.defaultCode = renderer.code
  renderer.code = (code, language) ->
    if language is 'mermaid'
      html = ''
      if not hasMermaid
        hasMermaid = true
        html += '<script src="'+options.mermaidPath+'"></script>'
      html + '<pre class="mermaid">'+code+'</pre>'
    else
      @defaultCode(code, language)

  renderer

高级用法

¥Advanced usage

无需渲染即可进行语法验证

¥Syntax validation without rendering

mermaid.parse(text, parseOptions) 函数验证图形定义而不渲染图形。

¥The mermaid.parse(text, parseOptions) function validates graph definitions without rendering a graph.

函数 mermaid.parse(text, parseOptions) 采用文本字符串作为参数,如果定义遵循 mermaid 的语法,则返回 { diagramType: string }

¥The function mermaid.parse(text, parseOptions), takes a text string as an argument and returns { diagramType: string } if the definition follows mermaid's syntax.

如果定义无效,则当 parseOptions.suppressErrors 设置为 true 时,该函数返回 false。否则,它会抛出错误。

¥If the definition is invalid, the function returns false if parseOptions.suppressErrors is set to true. Otherwise, it throws an error.

当 parse 函数抛出错误时,将调用 parseError 函数。如果 parseOptions.suppressErrors 设置为 true,则不会被调用。

¥The parseError function will be called when the parse function throws an error. It will not be called if parseOptions.suppressErrors is set to true.

可以重写此函数以便以应用特定的方式处理错误。

¥It is possible to override this function in order to handle the error in an application-specific way.

下面元代码中的代码示例说明了这是如何工作的:

¥The code-example below in meta code illustrates how this could work:

javascript
mermaid.parseError = function (err, hash) {
  displayErrorInGui(err);
};

const textFieldUpdated = async function () {
  const textStr = getTextFromFormField('code');

  if (await mermaid.parse(textStr)) {
    reRender(textStr);
  }
};

bindEventHandler('change', 'code', textFieldUpdated);

配置

¥Configuration

你可以将所需的配置传递给 mermaid.initialize 调用。这是配置 mermaid 的首选方式。配置对象列表在 在 mermaidAPI 文档中 中进行了描述。

¥You can pass the required configuration to the mermaid.initialize call. This is the preferred way of configuring mermaid. The list of configuration objects are described in the mermaidAPI documentation.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  let config = { startOnLoad: true, flowchart: { useMaxWidth: false, htmlLabels: true } };
  mermaid.initialize(config);
</script>

INFO

This is the preferred way of configuring mermaid.

以下方法已被弃用,保留仅是为了向后兼容。

¥The following methods are deprecated and are kept only for backwards compatibility.

使用 Mermaid 对象

¥Using the mermaid object

可以通过 Mermaid 对象设置一些配置。使用此方法支持的两个参数是:

¥It is possible to set some configuration via the mermaid object. The two parameters that are supported using this approach are:

  • mermaid.startOnLoad

  • mermaid.htmlLabels

javascript
mermaid.startOnLoad = true;

WARNING

This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.