mxgraph series [1]: Get started

Posted May 25, 20205 min read

mxgraph is an excellent SVG graphics engine and graphics editor, but the official documentation provided by the framework is too academic and has low practical value; community discussion on mxgraph There are also very few, leading to extremely high cost of framework entry. I plan to launch mxgraph tutorials from time to time in the coming year. Interested students are welcome to pay attention, learn together and grow together.

1 Introduction

mxgraph The first version was submitted in 2012, when the front-end engineering was still in the enlightenment stage, and the tool chain was seriously missing. Looking at mxgraph with the current vision is unsightly . However, the framework's architectural design is very elegant. Even if it is placed in the current front-end environment, it is still good enough. As a template, studying mxgraph source code can learn:

  1. Common design patterns in editor development and editor implementation
  2. Graphic layout algorithm
  3. How the graphics engine manages a large number of graphic elements
  4. How to express graphics abstractly to support custom expansion
  5. Wait

This article will serve as a starting point for a series of tutorials on how to start using mxgraph.

2 . Use local file

The easiest, you can use git clone git@github.com:jgraph/mxgraph.git to download the library file to the local, and use the script tag in the page to introduce for example:

<!-Use local file->
<script src = "./libs/mxgraph/mxClient.min.js"> </script>

The clone command will clone all the warehouses, of which only mxgraph/javascript/src/mxClient.min.js Or mxgraph/javascript/src/mxClient.js can meet application requirements, other files can be ignored.

After the introduction of mxClient.min.js, many properties of the mx prefix will be added to the global object window:

These global variables can be used later to build applications, such as:

<! DOCTYPE html>
<html lang = "en">
    <head>
        <meta charset = "utf-8" />
        <meta name = "viewport" content = "width = device-width, initial-scale = 1" />
        <title> mxgraph Demo </title>
    </head>
    <body>
        <div id = "root"> </div>

        <script type = "text/javascript" src = "../mxClient.min.js"> </script>
        <script type = "text/javascript">
            //mxgraph is exposed under the window, so it can be called directly
            const graph = new mxgraph(document.getElementById('root'));
            const parent = graph.getDefaultParent();

            //Start an update session
            graph.getModel(). beginUpdate();
            try {
                //Insert a rectangle
                const v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
                //Insert the second rectangle
                const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
                //Connect two rectangles
                graph.insertEdge(parent, null, '', v1, v2);
            } finally {
                //End the update session
                graph.getModel(). endUpdate();
            }
        </script>
    </body>
</html>

Example effect:

3 . Use CDN

There are two main disadvantages of using the mxClient.min.js file directly. One is that the library file needs to be downloaded and put into the project, which is not friendly to subsequent version management; the second is that the backward construction method leads to mxClient.min. js will expose many variables to the global space and cause pollution. In this case, if you still want to use <script>, you can consider using CDN service:

<script src = "//cdn.jsdelivr.net/npm/mxgraph@4.1.1/javascript/dist/build.min.js"> </script>

Note that the build.min.js file is used here. Unlike mxClient.min.js, this file wraps the mxgraph code into the factory function to solve the problem of global space pollution:

(function(root, factory) {
if(typeof define === 'function' && define.amd) {
define([], factory);
} else if(typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.mxgraph = factory();
}
})(this, function() {
return function(opts) {
for(var name in opts) {
this [name]= opts [name];
}
var __mxOutput = {};
/* Insert mxgraph code here * /
return __mxOutput;
};
});

build.min.js exposes a factory function externally. The usage is slightly different from the above example. You need to execute the factory function to initialize the mxgraph namespace first. Example:

4
<! DOCTYPE html>
<html lang = "en">
    <head>
        <meta charset = "utf-8" />
        <meta name = "viewport" content = "width = device-width, initial-scale = 1" />
        <title> mxgraph Demo </title>
    </head>
    <body>
        <div id = "root"> </div>
        <script src = "//cdn.jsdelivr.net/npm/mxgraph@4.1.0/javascript/dist/build.js"> </script>
        <script>
            //Initialize the namespace
            //mxgraph here is the factory function exposed by `build.min.js`
            const ns = mxgraph({
                mxBasePath:'//cdn.jsdelivr.net/npm/mxgraph@4.1.0/javascript/src',
            });

            const graph = new ns.mxgraph(document.getElementById('root'));
            const parent = graph.getDefaultParent();

            //Start an update session
            graph.getModel(). beginUpdate();
            try {
                const v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
                const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
                graph.insertEdge(parent, null, '', v1, v2);
            } finally {
                //End the update session
                graph.getModel(). endUpdate();
            }
        </script>
    </body>
</html>

Tips:

Although the above code can render hello world! Normally, many errors will be reported on the console, which is also a bug caused by the construction method. In this example, please ignore it directly.

3 . Introduced using modular solutions such as webpack

Since version 3.7.2, mxgraph has packaged and released the library to npm. Developers can use yarn add mxgraph to install it. The main entry file of the mxgraph package is build.min.js, and the default import is the factory function as mentioned in the previous example. Example:

const ns = require('mxgraph'))({});
//or import syntax
//import mxgraphFactory from 'mxgraph';
//const ns = mxgraphFactory({});
const graph = new ns.mxgraph(this. $refs.main);

const parent = graph.getDefaultParent();

graph.getModel(). beginUpdate();
try {
    const v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
    const v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
    const e1 = graph.insertEdge(parent, null, '', v1, v2);
} finally {
    graph.getModel(). endUpdate();
}

Tips:

Since it can be installed via npm, why did you spend a lot of time introducing the introduction of script? The main reason is that the mxgraph documentation is extremely imperfect, and the most valuable one is Official examples , and all the example code is <script> introduces local library files, so understanding the different import modes can help to better understand the examples.

In addition, the community currently does not have a good typescript type definition library for mxgraph, so it cannot be used freely in the ts environment.

Preview of the next section

mxgraph The engineering solution is very messy, the warehouse contains a lot of irrelevant code and tricks that are difficult to understand Understand the source code and make a good preparation.

Related Posts