MxGraph is a drawing framework that supports multiple languages (Java, JavaScript, PHP,.NET), drawing graphics that can be used in mainstream browsers and native applications. The official mxGraph resource is in English, and there are several mxGraph tutorials on the web that cover “getting started” and “using” in more detail. Therefore, this article is not about how to draw a graph or write a Hello world. Instead, it focuses on the knowledge points that are important, difficult to understand, or easy to ignore when learning mxGraph. Readers are required to have some knowledge of mxGraph documentation or to use mxGraph.

Usage scenarios for mxGraph

MxGraph can be used in four scenarios: graphics visualization, graphics interaction, graphics layout, and graphics analysis.

Graphic visualization

Graphics visualization is the main feature of mxGraph. It is easy to understand that abstract concepts are represented by graphics, such as common flow charts, mind maps, entity relationship diagrams, etc. It should be noted that mxGraph is mainly composed of “points” (including basic shapes such as rectangles and circles) and “edges”, so it would be inappropriate to use mxGraph to draw Mona Lisa. Below is a sample provided by the authorities. The author guessed that this would be achieved by using a map of the world as a background image and then drawing dots and lines on top of it. To test my guess, I visited the website provided by the official example and found that it was a JPG image with no connection. It could be the exported bitmap generated by the back end, or the source image has been replaced by the website.

Graphical interaction

In addition to drawing graphics, mxGraph provides rich editing capabilities such as drag and drop, select, copy, resize, and so on. MxGraph even provides an API class to support the online editor. I didn’t use ~ on this one

Graphical layout

A very important feature that automatically arranges graphic elements. MxGraph provides a variety of layouts, such as tree, stack, and circle. This will be highlighted later.

Graphical analysis

Support graph related algorithm analysis, such as finding the shortest path between two nodes in a graph. I haven’t used this yet, but I haven’t found the API, so I guess developers need to implement the algorithm themselves.

summary

The first step in learning a new technology or framework is to understand what it is and what it does. If it matches the function to be implemented then continue to study.

mxGraph

There are three ways to draw graphics on the front end:

  1. HTML + CSS.
  2. Canvas.
  3. SVG.

HTML+ CSS

advantages

  • Front end engineers are familiar with the most common approach, which is very simple to develop.
  • With CSS3 you can achieve cool animation effects.

disadvantages

  • It is very dependent on the browser environment and can be cumbersome to migrate to native applications or clients.
  • HTML and CSS have no suitable module mechanism, so the reuse of graphics is not convenient.

canvas

Canvas is also widely used. For example, Baidu’s famous open source project Echarts uses canvas to draw various graphics.

advantages

  • Powerful API to achieve complex graphics and effects.
  • Rendering speed is fast and can be accelerated with graphics cards.

disadvantages

  • It is also heavily dependent on the browser environment and is not supported by older browsers.
  • The code logic is complicated.
  • It is not convenient to save and export.

svg

advantages

  • Broad operating environment. Browsers, drawing tools, and editors all display normally.
  • Good editability. SVG can be modified in JavaScript on the front end, in a back-end language, and by designers in software.
  • Simple to use. SVG is an XML syntax, there is no complex logic, it is all configured
  • The vector diagram. Compared with bitmaps, no resolution is required and the zoom is clear.

disadvantages

  • Complex graphics render slowly.

summary

MxGraph draws SVG graphics by default (canvas is also supported by API documentation and source code), so it supports pre-rendering in back-end languages, saving and exporting, and converting to bitmaps is also very easy. Understanding this will help us understand the features of mxGraph and modify the source code.

The core concept of mxGraph is the Cell

The concept of cell can be understood as a data model in two-way data binding. When we need to modify the graph, we should modify the attributes of the mxCell instance through the API provided by mxGraph, and then mxGraph’s drawing function will modify the view according to the data model. Many of mxGraph’s other concepts are based on cells: styles, layouts, content text, events, locations……

myth

  1. MxGraph’s graphs are divided into two categories: Vertex and edge, but they are actually instances of the mxCell class, with different attribute values.
  2. Official documentationbeginUpdateandendUpdateIf you do not use these two functions, you will not have any effect on the drawing result. As far as rolling back is concerned, that’s overthinking.

MxGraph layout algorithm

Many developers see the word “algorithm” and cringe, finding it complex and hard to understand. But mxGraph’s layout algorithm isn’t that hard to understand.

  • All of the layout algorithm classes “inherit” from the base mxGraphLayout class, which defines some of the properties and implements the EXECUTE API, which mxGraph calls when drawing a graph.
  • The layout algorithm only involves manipulation of vertex points, and when vertex points are adjusted, mxGraph automatically adjusts the relationship between them to show either hidden or curved edges.
  • If you need to draw a large number of graphs that can cause performance problems, you should not implement this in the algorithm. This can be done by default using mxGraph: 1. Collapse/expand; 2. Drill/eject; 3. Display hierarchical filtering

Customization of mxGraph

Many times we also need to customize the graphics drawn by mxGraph, mainly as follows.

style

MxGraph’s support for styles is very patchy.

  • First, CSS is not supported. This means that features like style inheritance and style classes are no longer available.
  • When you modify it, you need to pass in the JSON object through the API function.
  • MxGraph does not use the defS tag to declare style classes when manipulating styles internally. Instead, it directly changes the tag’s style and fill attributes. This can lead to a lot of duplicate style code and inconvenient style overwriting.

For example, the following code is used to implement a highlighting style. If CSS style classes are supported, we just need to write a highlighting style and add and delete class names. Mxgraph, on the other hand, has to be written as an object and manually cleared when unhighlighted.

var common_highlight = {}
common_highlight[mxConstants.STYLE_FONTSTYLE] = mxConstants.FONT_BOLD
var vertex_highlight = Object.assign({}, common_highlight)
vertex_highlight[mxConstants.STYLE_FILLCOLOR] = '#00ffff'
var edge_highlight = Object.assign({}, common_highlight)
edge_highlight[mxConstants.STYLE_STROKECOLOR] = '#00ffff'
if (hover) {
  if(! state.styleList) {if (state.cell.edge) {
      state.styleList = new mxStylesheetList(Object.assign({}, graph.getStylesheet().styles.defaultEdge, state.style));
    } else if(state.cell.vertex) { state.styleList = new mxStylesheetList(Object.assign({}, graph.getStylesheet().styles.defaultVertex, state.style)); }}if (state.cell.vertex && state.cell.value) {
    state.styleList.add('highlight', vertex_highlight);
  }
  if (state.cell.edge) {
    state.styleList.add('highlight', edge_highlight); }}else {
  state.styleList.remove('highlight');
}
state.style = state.styleList.get();
state.shape.apply(state);
state.shape.redraw();
if(state.text ! = null) { state.text.apply(state); state.text.redraw(); }Copy the code

The HTML element

One of the strengths of mxGraph is the ability to insert HTML elements in SVG. Htmllabel.html does this in the examples provided here. To summarize the two-step implementation:

  1. Insert a UserObject object declaration at point creation to indicate that DOM elements can be inserted there.
  2. Override the convertValueToString function to return a DOM element.

The relevant codes are as follows:

var obj = doc.createElement('UserObject');
obj.setAttribute('label'.'FASTQ files');
var v1 = graph.insertVertex(col[0], null, obj, 0, 0, width, height)
...
graph.convertValueToString = function (cell) {
  let div = document.createElement('div')...return div;
}
Copy the code

edge

The edges of mxGraph are drawn automatically, and the API supports style changes to the edges, such as arrows and thickness. Edges are drawn in one of two forms, the default being rounded polylines drawn by bezier curves, and rectangular polylines. MxGraph is not internally optimized for these edges, and if the layout is not right, it will cross over and pass through points. In the development, I made a small modification to the drawing method of the edge, which was unified to directly use the three Times Bezier curve connection. The specific code is as follows:

// shap/mxShap.js
mxShape.prototype.addPoints = function(c, pts, rounded, arcSize, close, exclude, initialMove)
{
	if(pts ! = null && pts.length > 0) { initialMove = (initialMove ! = null) ? initialMove :true;
		var pe = pts[pts.length - 1];
		
		// Adds virtual waypoint in the center between start and end point
		if (close && rounded)
		{
			pts = pts.slice();
			var p0 = pts[0];
			var wp = new mxPoint(pe.x + (p0.x - pe.x) / 2, pe.y + (p0.y - pe.y) / 2);
			pts.splice(0, 0, wp);
		}
	
		var pt = pts[0];
		var i = 1;
	
		// Draws the line segments
		if (initialMove)
		{
			c.moveTo(pt.x, pt.y);
		}
		else{ c.lineTo(pt.x, pt.y); } const midX = pt.x / 2 + PE. X / 2 // call the built-in function to draw the Bezier curve three times c.curveto (midX, pt.y, midX, PE. Y, PEreturn; / /... }Copy the code

Reference:

  • The mxGraph Tutorial”
  • MxGraph User Manual — JavaScript Client

Original link: tech.gtxlab.com/mxgraph-kno… Author information: Zhu Delong, Renhe Future Senior front End Engineer.