mxGraph样例学习一
金蝶云社区-雪獒
雪獒
0人赞赏了该文章 1,498次浏览 未经作者许可,禁止转载编辑于2017年09月10日 18:37:43

一、Hello World
1、HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>mxGraph01</title>
<script>
mxBasePath = "../../src";
</script>
<script src="../../src/js/mxClient.js"></script>
<script src="./example01.js"></script>
<style>
#graphContainer{
position:relative;
overflow:hidden;
width:321px;
height:241px;
background:url('../editors/images/grid.gif');
cursor:default;
}
</style>
</head>
<body>
<div id="graphContainer"></div>
</body>
</html>

这段HTML代码有三个script标签,第一个标签中指定了mxBasePath的路径,此路径为mxGraph源码的路径,此路径下的文件有: css、images、js和resources;第二个标签中引入了mxClient.js,此js中会判断是否设置了mxBasePath,如果没有设置此值,mxClient.basePath的值就为当前路径,否则为设置的mxBasePath的路径。之后会在此路径下异步加载必须的其他js文件,或者也可以直接使用包含了所有文件的mxClient.js或mxClient.min.js,后者适用于正式使用的场景。第三个script中引入了当前页面的js。

2、script脚本(example01.js)
document.body.onload = function(){
var container = document.querySelector("#graphContainer");
var graph = new mxGraph(container);

var parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try{

var v1 = graph.insertVertex(parent, null, 'Hello', 20, 20, 80, 30);
var v2 = graph.insertVertex(parent, null, 'World', 200, 150, 80, 30);
var e1 = graph.insertEdge(parent, null, '连线', v1, v2);

}finally{
graph.getModel().endUpdate();
}
};

mxGraph在改变model时使用了事务,这个例子中插入了两个节点和一条线,分别调用了mxGraph的insertVertex和insertEdge方法。
API如下:
insertVertex(parent, id, value, x, y,width, height, style, relative) insertEdge(parent,id, value, source, target, style)每次改变model时需要先调用beginUpdate()方法,然后改变model,最后调用endUpdate()完成对model的改变并发出事件改变通知。
3、运行效果


二、其他辅助功能1、选择线框在选择图形的时候显示选择区域:var rubberband = new mxRubberband(graph);效果如下:

2、折叠/展开节点可以使用: graph.isCellFoldable = function(cell){ return true; };设置节点是可折叠的。效果如下:

3、自定义连线样式mxEdgeStyle中定义了线的各种样式:Loop、ElbowConnector、SideToSide等等,可以通过以下方式自定义连线样式: mxEdgeStyle.MyStyle = function(state, source, target, points, result){ if (source != null && target != null){ var pt = new mxPoint(target.getCenterX(), source.getCenterY()); if (mxUtils.contains(source, pt.x, pt.y)){ pt.y = source.y + source.height; } result.push(pt); } };定义好样式后,还需要注册到mxStyleRegistry中: mxStyleRegistry.putValue('myEdgeStyle', mxEdgeStyle.MyStyle);最后使用mxGraphModel的setStyle方法将样式设置到指定的线上: var e1 = graph.insertEdge(parent, null, '连线', v1, v2); graph.getModel().setStyle(e1, 'edgeStyle=myEdgeStyle');效果如下:

或者在定义好自定义样式后,直接修改连线的默认样式: var style = graph.getStylesheet().getDefaultEdgeStyle(); style[mxConstants.STYLE_EDGE] = mxEdgeStyle.MyStyle;

附:mxGraph官方样例: http://jgraph.github.io/mxgraph/javascript/index.html