react项目需要npm安装mxGraph
npm install mxgraph --save
1、导入文件,mxBasePase配置
const mx = require('mxgraph')({
mxBasePath: 'mxgraph' //mxGraph路径
})
const { mxGraph, mxClient } = mx //mxGraph图形创建,mxClient 用于下方浏览器检查
2、检查是否支持浏览器
componentDidMount(){
if(mxClient.isBrowserSupported()){ //浏览器支持mxGraph
// Action
}
else{
alert('该浏览器不支持mxGraph!')
}
}
3、创建mxGraph对象
//this.containerRef.current:ref连接到绘制节点
graph = new mxGraph(this.containerRef.current)
4、创建边和顶点
const parent = graph.getDefaultParent() //默认父级,无参数创建mxGraph会生成一个默认根节点
//页面初始渲染
graph.getModel().beginUpdate() //启动一个新事务或子事务,为了确保不因为try-catch模块中出现错误而不执行beginUpdate(),该函数不能写于try-catch模块内
//beginUpdate和endUpdate函数用于graph或者group的改变,必须成对出现
try {
const v1 = graph.insertVertex(parent, null, 'hello', 50, 10, 80, 20) //插入点( parent, id, value, x, y, width, height, style )
const v2 = graph.insertVertex(parent, null, 'world', 200, 10, 80, 20)
graph.insertEdge(parent, null, '', v1, v2) //插入线( parent, id, value, source, target, style )
} finally {
graph.getModel().endUpdate(); //结束一个新事务或子事务,确保只要执行了beginUpdate函数就必须执行endUpdate()函数,两者必须同时出现
}
默认情况下为相对定位, x:顶点的最左边相对于父组件的最左边的偏移量;y:顶点的最上边相对于父组件的最上边的偏移量
5、连接节点
<div ref={this.containerRef} className='container'></div>
<!-- 使用ref连接div,类组件中this.containerRef.current进行图形创建,函数组件中需要采用react hook --!>
完整代码:
react类组件:
import React from 'react'
const mx = require('mxgraph')({
mxBasePath: 'mxgraph'
})
const { mxGraph, mxClient } = mx
export default class AppClass extends React.Component{
constructor(props){
super(props)
this.containerRef = React.createRef()
this.state = {
graph: null,
}
}
componentDidMount(){
if(mxClient.isBrowserSupported()){ //浏览器支持mxGraph
console.log(mxClient.isBrowserSupported())
var graph = this.state.graph
graph = new mxGraph(this.containerRef.current)
const parent = graph.getDefaultParent() //默认父级
//页面初始渲染
graph.getModel().beginUpdate() //启动一个新事务或子事务
try {
const v1 = graph.insertVertex(parent, null, 'vertex 1', 50, 10, 80, 20) //插入点( parent, id, value, x, y, width, height, style )
const v2 = graph.insertVertex(parent, null, 'vertex 2', 200, 10, 80, 20)
graph.insertEdge(parent, null, '', v1, v2) //插入线( parent, id, value, source, target, style )
} finally {
graph.getModel().endUpdate(); //结束一个新事务或子事务
}
}
else{
alert('该浏览器不支持mxGraph!')
}
}
componentDidUpdate(){
}
render(){
return(
<div ref={this.containerRef} className='container' style={{height: 500,border: '1px solid #000000',overflow: 'auto'}}></div>
<!-- overflow: 'auto':当移动顶点超出画面,则出现滑动条; 设置了宽高后,若将顶点移动超出固定区域则canvas会移动,可能会导致原本边缘上的顶点看不见,使用overflow: 'auto'出现滑动条可以滑动画布,寻找其他顶点 --!>
)
}
}