您现在的位置是:首页>漫生活>详细内容
# 宇加业务协同平台-Mxgraph常用方法
发布时间:2018-11-16 11:24:59 编辑:黄小妹22浏览(2799)评论(2)
# 宇加业务协同平台-Mxgraph常用方法
###仅供参考,不对的地方或者有更好的方法可以修正
##判断浏览器兼容性
```
if (!mxClient.isBrowserSupported()) {
// Displays an error message if the browser is not supported.
mxUtils.error('您当前浏览器不支持此组件!', 200, false);
}else {
....正文
}
```
##常用的全局属性配置[graph.setXXXX(bool)]
```
// j禁用浏览器右键菜单
mxEvent.disableContextMenu(container);
//添加框选
new mxRubberband(graph);
//细胞可以克隆
graph.setCellsCloneable(true);
//是否允许线悬吊着,摆动不定
graph.setAllowDanglingEdges(false);
//禁止放大缩小
graph.setCellsResizable(false);
//禁用折叠
graph.foldingEnabled = false;
// 启用工具提示、新连接和平移
graph.setPanning(true);
// 开启鼠标悬停提示
graph.setTooltips(true);
//设置可连接性
graph.setConnectable(true);
graph.setMultigraph(false);
//去锯齿效果
mxRectangleShape.prototype.crisp = true;
// 是否启用对齐线帮助定位
mxGraphHandler.prototype.guidesEnabled = true;
//定义对齐线颜色
mxConstants.GUIDE_COLOR = "#00A3D9";
// 是否缩放网格
// mxGraphHandler.prototype.scaleGrid = true;
// 是否开启旋转
mxGraphHandler.prototype.rotationEnabled = false;
// 选择基本元素开启
graph.setEnabled(true);
// 开启文字编辑功能
graph.setCellsEditable(true);
//开启回车退出编辑
graph.setEnterStopsCellEditing(true);
// 鼠标悬浮在节点上显示浮动框
new mxCellTracker(graph, '#8BF19F');
```
##常用方法
```
//根据ID获取cell
graph.getModel().getCell(uuid)
```
##属性重定义方法[graph.isXXX(function(cell){})]
```
//根据ID获取cell
graph.getModel().getCell(uuid)
```
##属性重定义方法[graph.isXXX(function(cell){})]
```
// 重定义哪些cell锁定
graph.isCellLocked = function(cell) { //锁定连线,不可随意拖动
// if (graph.getModel().isEdge(cell)) {
// return true;
// }else{
return false;
//}
};
//重定义哪些cell可以移动
graph.isCellMovable = function(cell) {
if(cell.type && cell.type == "taskType") {
return false;
} else {
return true;
}
};
//获取当前选中的cell
var cell = graph.getSelectionCell();
if (cell == null) {
// Ext.Msg.alert('没有选择图形元素'); //'没有选择图形元素!'
return;
}
var objId = cell.getId(); //元素ID
var enc = new mxCodec();
var node = enc.encode(cell); //解析为DOM对象时自定义属性才可以识别
var nodetype = node.getAttribute('nodetype'); //取节点类型,如果是线则为空
var source = node.getAttribute('source'); //取线的来源节点ID,如果是节点则值为空
// var config = mxUtils.getXml(node);
// 新窗口打开
mxUtils.popup(mxUtils.getXml(node));
// }
```
## 添加监听事件的方法
```
graph.addMouseListener(mxEvent.MOUSE_DOWN,function () {
alert(1111);
});
//设置节点的鼠标移入手型移出鼠标指示效果
var track = new mxCellTracker(graph);
track.mouseMove = function (sender, me) {
var cell = this.getCell(me);
if (cell) {
//设置鼠标为样式为手状
me.getState().setCursor('pointer');
// updateStyle(cell, true);
} else {
// updateStyle(cell, false);
}
};
//最常用的监听点击事件的
graph.addListener(mxEvent.CLICK, function (sender, evt) {
var cell = evt.getProperty('cell');
if (!cell) return false;
console.log('我点击了节点哦!');
console.log(cell);
var enc = new mxCodec();
var node = enc.encode(cell);
console.log(node);
});
//监听鼠标按下,移动,抬起事件
graph.addMouseListener({
mouseDown: function (sender, me) {
console.log('mouseDown');
},
mouseMove: function (sender, me) {
// console.log('mouseMove');
},
mouseUp: function (sender, me) {
console.log('mouseUp');
},
dragEnter: function (evt, state) {
console.log('dragEnter');
// if (state != null) {
// this.previousStyle = state.style;
// state.style = mxUtils.clone(state.style);
// updateStyle(state, true);
// state.shape.apply(state);
// state.shape.redraw();
//
// if (state.text != null) {
// state.text.apply(state);
// state.text.redraw();
// }
// }
},
dragLeave: function (evt, state) {
console.log('dragLeave');
// if (state != null) {
// state.style = this.previousStyle;
// updateStyle(state, false);
// state.shape.apply(state);
// state.shape.redraw();
//
// if (state.text != null) {
// state.text.apply(state);
// state.text.redraw();
// }
// }
},
dragover: function (evt, state) {
console.log('dragover');
},
drop: function (evt, state) {
console.log('drop');
}
});
graph.addListener({
dragover: function (evt, state) {
console.log('dragover');
},
drop: function (evt, state) {
console.log('drop');
}
});
mxEvent.addListener(container, 'dragover', function (evt) {
if (graph.isEnabled()) {
evt.stopPropagation();
evt.preventDefault();
}
});
mxEvent.addListener(container, 'drop', function (evt) {
if (graph.isEnabled()) {
evt.stopPropagation();
evt.preventDefault();
// Gets drop location point for vertex
var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
var tr = graph.view.translate;
var scale = graph.view.scale;
var x = pt.x / scale - tr.x;
var y = pt.y / scale - tr.y;
console.log(x);
console.log(y);
console.log(event);
// Converts local images to data urls
var filesArray = event.dataTransfer.files;
console.log(filesArray);
// for (var i = 0; i < filesArray.length; i++) {
// handleDrop(graph, filesArray[i], x + i * 10, y + i * 10);
// }
}
});
```
## 定义默认样式以及样式类
```
//默认VertexStyle
var style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE;
style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_LEFT;
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE;
style[mxConstants.STYLE_FONTCOLOR] = '#000000';
style[mxConstants.STYLE_FONTSIZE] = '11';
style[mxConstants.STYLE_FONTSTYLE] = 0;
graph.getStylesheet().putDefaultVertexStyle(style);
var style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE;
style[mxConstants.STYLE_OPACITY] = 50;
style[mxConstants.STYLE_FONTCOLOR] = '#774400';
graph.getStylesheet().putCellStyle('ROUNDED', style);
//标准子过程样式
style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_SWIMLANE; //形状
style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER; //垂直对齐
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP; //水平对齐
style[mxConstants.STYLE_GRADIENTCOLOR] = '#DEE6E8'; //渐变色
style[mxConstants.STYLE_FILLCOLOR] = '#FAFAFA'; //填充色
style[mxConstants.STYLE_SWIMLANE_FILLCOLOR] = '#ffffff'; //swimlane填充色
style[mxConstants.STYLE_STROKECOLOR] = '#9DA5A7'; //表头边框颜色
style[mxConstants.STYLE_FONTCOLOR] = '#000000'; //字体颜色
style[mxConstants.STYLE_STROKEWIDTH] = '1'; //边框粗细
style[mxConstants.STYLE_STARTSIZE] = '28'; //表头部高度
style[mxConstants.STYLE_VERTICAL_ALIGN] = 'middle';
style[mxConstants.STYLE_FONTSIZE] = '12'; //字体大小
style[mxConstants.STYLE_FONTSTYLE] = 1;
graph.getStylesheet().putCellStyle('standrad_tabStyle', style);
//本节点
thisPointStyle = mxUtils.clone(style);
thisPointStyle["image"] = 'resources/images/graph/thisPoint.png';
thisPointStyle["fontSize"] = '16';
thisPointStyle["fontColor"] = '#fff';
thisPointStyle['constituent'] = "1";
thisPointStyle["verticalLabelPosition"] = "middle";
thisPointStyle["verticalAlign"] = "middle";
thisPointStyle["spacingTop"] = "4";
thisPointStyle["align"] = "center";
graph.getStylesheet().putCellStyle("thisPointStyle", thisPointStyle);
//节点状态
statusPointStyle = mxUtils.clone(style);
statusPointStyle['constituent'] = "1";
statusPointStyle["image"] = 'resources/images/graph/status-normal.png';
graph.getStylesheet().putCellStyle("statusPointStyle", statusPointStyle);
//添加数据节点
addDataPointStyle = mxUtils.clone(style);
addDataPointStyle["image"] = 'resources/images/graph/addDataPoint.png';
addDataPointStyle["imageWidth"] = '64';
addDataPointStyle["imageHeight"] = '64';
addDataPointStyle["fontColor"] = '#00A3D9';
//默认线条样式
edgeStyle = graph.getStylesheet().getDefaultEdgeStyle();
edgeStyle["rounded"] = true;
edgeStyle["shape"] = "connector";
edgeStyle["strokeWidth"] = 1;
edgeStyle["strokeColor"] = "#2C9C39";
MQEdgeStyle = mxUtils.clone(edgeStyle);
MQEdgeStyle["edgeStyle"] = 'elbowEdgeStyle';
MQEdgeStyle["startArrow"] = 'oval';
//MQEdgeStyle["endArrow"] = 'block';
MQEdgeStyle["endArrow"] = 'oval';
MQEdgeStyle["startFill"] = 0;
MQEdgeStyle["endFill"] = 0;
MQEdgeStyle["entryX"] = 0;
MQEdgeStyle["entryY"] = 0.5;
MQEdgeStyle["exitX"] = 1;
MQEdgeStyle["exitY"] = 0.5;
graph.getStylesheet().putCellStyle("MQEdgeStyle", MQEdgeStyle);
```
## 画图
```
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent();
//Adds cells to the model in a single step
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);
//画方块 默认情况下
graph.insertVertex(parent, null, '矩形', 50, 50, 150, 150);
// 画方块 圆角矩形
shape=rounded 定义圆角 arcSize=10 定义圆角弧度
graph.insertVertex(parent, null, '圆角矩形', 300, 50, 150, 150, "rounded=true;perimeter=ellipsePerimeter;arcSize=20;");
//画椭圆
shape=elipse 定义椭圆 perimeter=ellipsePerimeter 让连线的箭头或起点触到边缘
graph.insertVertex(parent, null, '椭圆', 550, 50, 150, 150, "shape=ellipse;perimeter=ellipsePerimeter;");
//画三角形
shape=triangl 定义三角形 perimeter=ellipsePerimeter 让连线的箭头或起点触到边缘 direction=south 让三角形倒立
graph.insertVertex(parent, null, '三角形', 800, 50, 150, 150, "shape=triangle;perimeter=ellipsePerimeter;direction=south;");
//画菱形
shape=rhombus 定义菱形
graph.insertVertex(parent, null, '三角形', 1050, 50, 150, 150, "shape=rhombus;perimeter=ellipsePerimeter;");
//画柱形
shape=cylinder 定义柱形
graph.insertVertex(parent, null, '柱形', 1300, 50, 150, 150, "shape=cylinder;perimeter=ellipsePerimeter;");
//画人
shape=actor 定义演员
graph.insertVertex(parent, null, '演员', 50, 300, 150, 150, "shape=actor;perimeter=ellipsePerimeter;");
//画云
graph.insertVertex(parent, null, '云', 300, 300, 150, 150, "shape=cloud;perimeter=ellipsePerimeter;");
// 矩形默认情况下
graph.insertVertex(parent, null, '矩形', 550, 300, 150, 150, "shape=rectangle;perimeter=ellipsePerimeter;");
// 泳道
graph.insertVertex(parent, null, '泳道', 800, 300, 150, 150, "shape=swimlane;perimeter=ellipsePerimeter;");
// 双圆
graph.insertVertex(parent, null, '双圆', 1050, 300, 150, 150, "shape=doubleEllipse;perimeter=ellipsePerimeter;");
// 六边形
graph.insertVertex(parent, null, '六边形', 1300, 300, 150, 150, "shape=hexagon;perimeter=ellipsePerimeter;");
}finally {
// Updates the display
graph.getModel().endUpdate();
}
```
## 导出XML
```
//转XML格式输出
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
console.log(mxUtils.getXml(node));
扩充版(解决浏览器兼容问题)
//获取当前编辑指标的名称、xml
getGraphXML : function() {
//生成graph视图的xml格式文件
var getGraphXml = function(graph) {
var encoder = new mxCodec();
var code = encoder.encode(graph);
return code;
}
var model = graph.getModel();
if (model) {
var graphXmlObj = getGraphXml(model);
if (judgeIsIe8()) {
//console.log("ie8");
graphXmlForIe = graphXmlObj.xml; //<>转义得用第三变量传递一下,不能用var graphXml
return graphXmlForIe;
} else {
var oSerializer = new XMLSerializer();
var report_xmlStr = oSerializer.serializeToString(graphXmlObj);
graphXmlOther = report_xmlStr;
return graphXmlOther;
}
}
}
```
## 回显XML
```
// XML回显到编辑区(渲染画布)
var xmlFile = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="Hello," vertex="1" parent="1"><mxGeometry x="20" y="20" width="80" height="30" as="geometry"/></mxCell><mxCell id="3" value="World!" vertex="1" parent="1"><mxGeometry x="200" y="150" width="80" height="30" as="geometry"/></mxCell><mxCell id="4" value="" edge="1" parent="1" source="2" target="3"><mxGeometry relative="1" as="geometry"/></mxCell><mxCell id="5" value="矩形" vertex="1" parent="1"><mxGeometry x="50" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="6" value="圆角矩形" style="rounded=true;perimeter=ellipsePerimeter;arcSize=20;" vertex="1" parent="1"><mxGeometry x="300" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="7" value="椭圆" style="shape=ellipse;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="550" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="8" value="三角形" style="shape=triangle;perimeter=ellipsePerimeter;direction=south;" vertex="1" parent="1"><mxGeometry x="800" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="9" value="三角形" style="shape=rhombus;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="1050" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="10" value="柱形" style="shape=cylinder;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="1300" y="50" width="150" height="150" as="geometry"/></mxCell><mxCell id="11" value="演员" style="shape=actor;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="50" y="300" width="150" height="150" as="geometry"/></mxCell><mxCell id="12" value="云" style="shape=cloud;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="300" y="300" width="150" height="150" as="geometry"/></mxCell><mxCell id="13" value="矩形" style="shape=rectangle;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="550" y="300" width="150" height="150" as="geometry"/></mxCell><mxCell id="14" value="泳道" style="shape=swimlane;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="800" y="300" width="150" height="150" as="geometry"/></mxCell><mxCell id="15" value="双圆" style="shape=doubleEllipse;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="1050" y="300" width="150" height="150" as="geometry"/></mxCell><mxCell id="16" value="六边形" style="shape=hexagon;perimeter=ellipsePerimeter;" vertex="1" parent="1"><mxGeometry x="1300" y="300" width="150" height="150" as="geometry"/></mxCell></root></mxGraphModel>';
var doc = mxUtils.parseXml(xmlFile),
dec = new mxCodec(doc);
dec.decode(doc.documentElement, graph.getModel());
扩充版(解决浏览器兼容问题)
//解析xml字符串并转化成graph视图
createXmlDom : function(str) {
if (document.all) { //判断浏览器是否是IE
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
xmlDom.loadXML(str);
return xmlDom;
} else {
return (new DOMParser()).parseFromString(str, "text/xml");
}
},
readGraphXML : function(xmlstr, graph) {
if (xmlstr) {
graph.getModel().beginUpdate();
try {
var xmlDoc = this.createXmlDom(xmlstr);
var node = xmlDoc.documentElement;
var dec = new mxCodec(node.ownerDocument);
dec.decode(node, graph.getModel());
console.log(dec);
} finally {
graph.getModel().endUpdate();
}
}
}
```
##右键菜单
```
graph.popupMenuHandler.autoExpand = true;
graph.popupMenuHandler.factoryMethod = function(menu, cell, evt) {
if(cell != null) {
menu.addItem('添加节点', null, function() {
changeTaskType(cell.id, "")
});
//二级菜单
var conn_pos = menu.addItem('连接位置', null, function() {});
menu.addItem('左右', null, function() {}, conn_pos);
menu.addItem('三面', null, function() {}, conn_pos);
menu.addItem('四面', null, function() {}, conn_pos);
menu.addItem('设置', null, function() {});
menu.addItem('详细信息', null, function() {});
menu.addItem('远程更新版本', null, function() {});
menu.addItem('远程控制(新窗口)', null, function() {
window.open('index.html?serverUUID=' + cell.id + '&serverName=' + encodeURI(cell.value));
});
menu.addItem('查看目录', null, function() {
viewDataDirectoryWin.show(data.UUID, data.subOrSup);
});
menu.addItem('查看话题', null, function() {
viewTopicWin.show(data.UUID, data.subOrSup);
});
}
}
```
## 组合型shape配置
```
// Helper method to mark parts with constituent=1 in the style
//在style里面用constituent=1标记部件
graph.isPart = function(cell) {
var state = this.view.getState(cell);
var style = (state != null) ? state.style : this.getCellStyle(cell);
return style['constituent'] == '1';
};
// 重定义组合型图形的选中事件,不能选中里面的子部件
graph.selectCellForEvent = function(cell) {
if(this.isPart(cell)) {
cell = this.model.getParent(cell);
}
mxGraph.prototype.selectCellForEvent.apply(this, arguments);
};
```
## 绘制组合图形
```$xslt
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try {
var taskWrap = graph.insertVertex(parent, "Taskid", 'Looped\nSub-Process', 200, 200, 200, 100, 'whiteSpace=wrap;');
//constituent=1;表示节点作为一个part存在的
var taskTypeCell = graph.insertVertex(taskWrap, null, 'dfdfgd', 0.5, 1, 30, 30, 'shape=ellipse;fontSize=9;constituent=1;resizable=0;;outlineConnect=0;');
taskTypeCell.type = "taskType";
taskTypeCell.expr = "ffffffffffffffffff";
taskTypeCell.geometry.relative = true;
taskTypeCell.geometry.offset = new mxPoint(-15, -35);
taskTypeCell.connectable = false;
taskTypeCell.value = "jshdjhsdbvf";
} finally {
// Updates the display
graph.getModel().endUpdate();
}
```
##边缘事件
```
参考/examples/boundary.html
```
## 设置style样式[graph.setCellStyles(mxConstant.xxxx,设置的val, [cells])]
```
var changeTaskType = function(cellId, Task) {
var endFill = "";
var graph = myGraphInfo.graph;
switch(examine) {
case "EXAMINE_ADOPT": //审批通过
endFill = 1;
break;
case "EXAMINE_REJECT": //审批拒绝 case :
case "EXAMINE_CONNECT":
case "EXAMINE_NOT": //未审批 case :
case "EXAMINING": //待审批
endFill = 0;
break;
}
var thisCell = graph.getModel().getCell(uuid);
var thisEdge = thisCell.edges[0];
graph.setCellStyles("shape", "", [cell]);
graph.refresh(thisEdge);//刷新改细胞
}
```
##限制最大最小宽度
```aidl
graph.cellResized = function (cell, rect, ignoreRelative, recurse) {
var flagClass = "mxCol_" + cell.id;
if (rect.width < 40) {
rect.width = 40;
$("." + flagClass).width("0px");
} else if (rect.width > 800) {
rect.width = 800;
$("." + flagClass).width((800 - 43) + "px");
} else {
$("." + flagClass).width((rect.width - 43) + "px");
}
return mxGraph.prototype.cellResized.apply(this, arguments);
};
```
##关于是否可连接设置
```aidl
//目标可连接性设置
graph.isValidTarget = function (cell) {
if (cell) {
if (cell.type) {
if (cell.type == "table" || cell.type == "gather") {
// designMxgraph.setTabConnectable(true);
return true;
}
}
}
}
//连线可行性验证
graph.validateEdge = function (edge, source, target) {
if (!edge) {
// designMxgraph.setTabConnectable(false);
} else {
return true;
}
}
```
##Drop拖动目标验证
```aidl
//Drop拖动目标验证
//cell:target
//cells:source 一般用于group
graph.isValidDropTarget = function (cell, cells, evt) {
if (cell) {
if (cells.length == 1) {
source = cells[0];
if (cell.type == "group" && cells[0].type != "group" && cells[0].type != "gather") {
if (source.edges) {
for (var i = 0; i < source.edges.length; i++) {
if (source.edges[i].id.indexOf("flowline_") != -1) {//针对流向线
if (source.edges[i].target.id != source.id) {
return false;//一旦线的目标终点不是source本身,就不可以拖进去
} else if (source.edges[i].source.id == cell.id) {
return false;
} else {
continue;
}
}
}
}
return true;
}
}
}
}
```
##获取所有画布内得图形对象
```aidl
graph.getChildCells()---包括连线
graph.getChildVertices()---不包括连线
```
##设置细胞可连接性
```aidl
cell.setConnectable(bool);
```
##泳道布局
```aidl
//配置泳道里的细胞自动布局,泳道布局
editor.layoutSwimlanes = true;
editor.createSwimlaneLayout = function () {
var layout = new mxStackLayout(this.graph, false);
layout.fill = true;
layout.resizeParent = true;
// Overrides the function to always return true
layout.isVertexMovable = function (cell) {
return true;
};
return layout;
};
```
##添加A细胞到B细胞的连线
```aidl
var newLine = graph.insertEdge(parent, id, label, startCell, endCell, 'dashed=1;' +
'startArrow=oval;endArrow=oval;sourcePerimeterSpacing=4;startFill=1;endFill=1;strokeColor=green;' +
'strokeWidth=1;fontSize=12;edgeStyle=sideToSideEdgeStyle;');
dashed----
startArrow----线头起始形状 有oval(圆形),classic(箭头),none(无)
endArrow-----线头结束形状
startFill、endFill-----是否填充颜色
edgeStyle----线条的类型
entryX,entryY---结尾的落点坐标
exitX,exitY----开始的坐标
sourcePerimeterSpacing---留白
```
关键字词:MXgraph