1
Abstract: G6 is a graph visualization engine. It provides the basic capabilities of graph visualization such as graph drawing, layout, analysis, interaction, and animation.

This article is shared from the HUAWEI cloud community " will use these APIs to easily draw flowcharts-antv.g6 flowchart entry ", author: a brick mover.

Common graph attributes and methods

graph attribute

container

height

width

modes

image.png

graph = new G6.Graph({
    container: "container",
    height: 500,
    width: 500,
    modes: {
        default: [
            "drag-canvas",
            "hover-node",
            "select-node",
            "hover-edge",
            "keyboard",
            "customer-events"
        ],
        addEdge: ["add-edge"],
        moveNode: ["drag-item"]
    },
     renderer: 'svg'
     plugins: [grid]
});

graph method

Initialization data

data(data)
const data = {
  nodes: [
    {
      id: 'node1',
      label: 'node1',
    },
    {
      id: 'node2',
      label: 'node2',
    },
  ],
  edges: [
    {
      source: 'node1',
      target: 'node2',
    },
  ],
};

// graph 是 Graph 的实例
graph.data(data);

Add, delete, modify and check nodes and edges

add(type,model)

New elements (nodes and edges)

If it is a custom node or edge type, the name of the custom node or edge

addItem(type, model, stack)

New elements (nodes and edges)
image.png

this.edge = this.graph.addItem('edge', {
    source: item,
    target: item,
    start: startPoint,
    end: startPoint,
    type: 'link-edge'
});

remove(node/edge)

Remove nodes or edges

const node = this.graph.findById(item.id)

this.graph.remove(node)
removeItem(item, stack)

Delete element, when item is group ID, delete group
image.png

// 通过 ID 查询节点实例
const item = graph.findById('node');
graph.removeItem(item);

// 该操作不会进入到 undo & redo 栈,即 redo & undo 操作会忽略该操作
graph.removeItem(item, false);
//删除边
graph.removeItem(edge)

update(node/edge,nodeModel/edgeModel)

Update the attributes of a node or edge
image.png

graph.update(node, {name:1});
graph.update(edge, {name:1});

updateItem(item, model, stack)

Update elements, including updating data, styles, etc. If there is combo on the graph, after using this function to update the position of a node, you need to call updateCombo(combo) to update the position of the relevant combo.
image.png

graph.updateItem(edge, {
    routeName: response.routeName
});

find(type, fn)

Find a single element according to specific rules.
image.png

const findNode = graph.find('node', (node) => {
  return node.get('model').x === 100;
});

findById(id)

According to the ID, query the corresponding element instance
image.png

findAllByState(type,state)

Find all elements in a specified state
image.png

graph.findAllByState('node', 'selected')

getNodes()

Get the instances of all nodes in the graph.

⚠️ Note: What is returned here is the instance of the node, not the data item of the node.

Return value type: Array;

The state of nodes and edges are related

setItemState(item, state, value)

Set the element state. When you use a custom node node, the setItemState method is the setState method in this method.
image.png

graph.setItemState(item, 'normal', true);

Coordinate conversion

getPointByClient(clientX, clientY)

Since the position obtained from the screen is different from the position of the canvas, this method is to subtract the left and top positions of the canvas
image.png

Vision related

getZoom()

Get the zoom ratio of the current viewport

zoomTo(toRatio, center)

image.png

// 以 (100, 100) 为中心点,放大3倍
graph.zoomTo(3, { x: 100, y: 100 });

// 以当前元素位置为中心,缩小到 0.5
graph.zoomTo(0.5);

Attribute related

get(key)

image.png

// 获取 group
const group = graph.get('group');

// 获取 canvas 实例
const canvas = graph.get('canvas');

// 获取 autoPaint 值
const autoPaint = graph.get('autoPaint');
const width = graph.get("width");
const height = graph.get("height");

Canvas related

destroy()

Delete the canvas is canvas

graph.destroy()

setAutoPaint(auto)

Set whether to automatically redraw after update/delete, generally used with the paint() method. Used in conjunction with setItemState, it is called before and after the element state is changed. When you use a custom node node, the setItemState method is the setState method in this method. Calling setItemState is actually calling the setState method of the node.
image.png

const item = e.item;
const graph = this.graph;

const autoPaint = graph.get('autoPaint');
graph.setAutoPaint(false);

graph.setItemState(item, 'selected', true);

graph.paint();
graph.setAutoPaint(autoPaint);

paint()

Only the canvas is redrawn. After setting the element style or state, call the paint() method to make the changes take effect.

refresh()

When the data item of the existing node/edge/combo in the source data is changed, the view is refreshed according to the new data

graph.refresh();

setMode(mode)

Switch mode, refers to the mode defined in the custom behavior
The mode here refers to the configuration item modes of graph
image.png

graph = new G6.Graph({
    modes: {
        default: [
            "drag-canvas",
            "hover-node",
            "hover-edge",
            "keyboard",
        ],
        addEdge: ["add-edge"],
        moveNode: ["drag-item"]
    },
});
const behavors = {
    'hover-node': hoverNode,
    'add-edge': addLine,
    'drag-item': dragItem,
    'select-node': selectNode,
    'hover-edge': hoverEdge,
    'keyboard':keyboard
};
export function initBehavors() {
    for (let key in behavors) {
        G6.registerBehavior(key, behavors[key])
    }
}
this.graph.setMode('default')

Elements, nodes and edges

Common methods of elements

Concept: Elements are instances that contain nodes and edges

getModel()

Get the data model of the element

// 获取元素的数据模型
const model = item.getModel();

// 等价于
const model = item.get('model');

hasState(state)

Determine whether the element has a certain specified state

item.hasState('normal')

getContainer()

Get group

// 获取元素的容器
const group = item.getContainer();

// 等价于
const group = item.get('group');

getType()

Get the type of element

// 获取元素的类型
const type = item.getType();

// 等价于
const type = item.get('type');

getBBox()

Get the bounding box of the element

item.getBBox();

Common methods of nodes

Concept: The node inherits to the element, and all the method nodes of the element also have

getEdges()

Get all edges associated with the current node

// 获取与 node 关联的所有边
const edges = node.getEdges();

getInEdges()

Get all incoming edges associated with the current node

getOutEdges()

Get all outgoing edges associated with the current node

// 获取与 node 关联的所有出边
const edges = node.getOutEdges();

Edge common method

getModel()

Get the model of the edge

get(key)

Get attribute value

getSource()

Get the starting node of the current edge

Use of groups

Common method

addShape(type,cfgs)

image.png

Custom behavior

The customization mechanism of G6 includes related methods of custom nodes, custom edges, custom combos, custom interaction behaviors, and custom layouts. They are all mounted on the G6 global and called by G6.registerXXX.

Custom node

registerNode(nodeName, options, extendedNodeName)

image.png

G6.registerNode(
  'nodeName',
  {
    /**
     * 绘制节点,包含文本
     * @param  {Object} cfg 节点的配置项
     * @param  {G.Group} group 图形分组,节点中的图形对象的容器
     * @return {G.Shape} 绘制的图形,通过 node.get('keyShape') 可以获取到
     */
    draw(cfg, group) {},
    /**
     * 绘制后的附加操作,默认没有任何操作
     * @param  {Object} cfg 节点的配置项
     * @param  {G.Group} group 图形分组,节点中的图形对象的容器
     */
    afterDraw(cfg, group) {},
    /**
     * 更新节点,包含文本
     * @override
     * @param  {Object} cfg 节点的配置项
     * @param  {Node} node 节点
     */
    update(cfg, node) {},
    /**
     * 更新节点后的操作,一般同 afterDraw 配合使用
     * @override
     * @param  {Object} cfg 节点的配置项
     * @param  {Node} node 节点
     */
    afterUpdate(cfg, node) {},
    /**
     * 设置节点的状态,主要是交互状态,业务状态请在 draw 方法中实现
     * 单图形的节点仅考虑 selected、active 状态,有其他状态需求的用户自己复写这个方法
     * @param  {String} name 状态名称
     * @param  {Object} value 状态值
     * @param  {Node} node 节点
     */
    setState(name, value, node) {},
    /**
     * 获取锚点(相关边的连入点)
     * @param  {Object} cfg 节点的配置项
     * @return {Array|null} 锚点(相关边的连入点)的数组,如果为 null,则没有锚点
     */
    getAnchorPoints(cfg) {},
  },
  'extendedNodeName',
);

Precautions for registering custom behaviors

1. Must have a custom file
2. Must use registerBehavior
3. Add registered behavior in modes

Custom file: selectNode.js, the content is as follows:

//自定义文件
let selectNode = {
    getEvents(){
        return {
            'node:click':'onClick'
        }
    },
    onClick(e){
         console.log(e)
    }
}
//注册自定义行为
this.behavors = {
    'select-node':selectNode
}
 
for(let key in this.behavors){
    G6.registerBehavior(key,this.behavors[key])
}
//Graph对象中引用该行为
const graph = new G6.Graph({
    container: 'flow_container', 
    width, 
    height,
    fitCenter: true,
    modes: {
        default: ["select-node",],
     }
});

Custom edge

registerEdge(edgeName, options, extendedEdgeName)

image.png

G6.registerEdge(
  'edgeName',
  {
    /**
     * 绘制边,包含文本
     * @param  {Object} cfg 边的配置项
     * @param  {G.Group} group 图形分组,边中的图形对象的容器
     * @return {G.Shape} 绘制的图形,通过 node.get('keyShape') 可以获取到
     */
    draw(cfg, group) {},
    /**
     * 绘制后的附加操作,默认没有任何操作
     * @param  {Object} cfg 边的配置项
     * @param  {G.Group} group 图形分组,边中的图形对象的容器
     */
    afterDraw(cfg, group) {},
    /**
     * 更新边,包含文本
     * @override
     * @param  {Object} cfg 边的配置项
     * @param  {Edge} edge 边
     */
    update(cfg, edge) {},
    /**
     * 更新边后的操作,一般同 afterDraw 配合使用
     * @override
     * @param  {Object} cfg 边的配置项
     * @param  {Edge} edge 边
     */
    afterUpdate(cfg, edge) {},
    /**
     * 设置边的状态,主要是交互状态,业务状态请在 draw 方法中实现
     * 单图形的边仅考虑 selected、active 状态,有其他状态需求的用户自己复写这个方法
     * @param  {String} name 状态名称
     * @param  {Object} value 状态值
     * @param  {Edge} edge 边
     */
    setState(name, value, edge) {},
  },
  'extendedEdgeName',
);

The above are the common methods related to drawing flowcharts through G6, I hope it will be helpful to everyone~

If you want to learn more about the dry goods of AI technology, welcome to the AI area of HUAWEI CLOUD. There are currently six practical camps such as AI programming and Python for everyone to learn for free. (Six actual combat camp link: http://su.modelarts.club/qQB9)

Click to follow, and learn about Huawei Cloud's fresh technology for the first time~


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量