antv3 x6 基本语法(一)

ps: 基于antv x6. 3.0版本 ,具体在文档 可以参考官网 

 

安装依赖 ,默认会安装最新版本 v3, 如果想使用v2版本 指定版本号安装,本示例安装最新版本:

npm install @antv/x6 --save

 

初始化画布

vue2

 

<template>
  <div class="conatainer">
    <div class="left">菜单部分</div>
    <div class="right" ref="right">
      <div style="width: 100%; height: 100%; " >
        <div id="container"></div>
      </div>
    </div>
  </div>
</template>

 

js

 initGraph() {
      const rightRef = this.$refs.right;
      const graph = new Graph({
        container: document.getElementById("container"),
        // 设置画布大小,默认为容器大小
        // width: rightRef.offsetWidth,
        // height: rightRef.offsetHeight,
        autoResize: true,
        // 设置画布背景颜色
        background: {
          color: "#F2F7FA",
        },
      });
    },

 

初始化结果:

image

 

 


 渲染节节(nodes)点和边(edges) , 节点与边样式 attrs 【nodes\edge\attrs】这三个属性基本属性

 

画布上添加 节点nodes及边 edge

      // 创建节点
      const data = {
        nodes: [
          {
            id: "node1",
            shape: "rect", // 外形
            x: 40, // 距离容器left大小
            y: 40, // 距离容器top 大小

            width: 100,
            height: 40,

            label: "hello",
            attrs: {
              body: {
                stroke: "#8f8f8f",
                strokeWidth: 1,
                fill: "#fff",
                rx: 6,
                ry: 6,
              },
            },
          },
          {
            id: "node2",
            shape: "rect",
            x: 160,
            y: 180,
            width: 100,
            height: 40,
            label: "world",
            attrs: {
              body: {
                stroke: "#8f8f8f",
                strokeWidth: 1,
                fill: "#fff",
                rx: 6,
                ry: 6,
              },
            },
          },
        ],
        edges: [
          {
            shape: "edge",
            source: "node1",
            target: "node2",
            label: "x6",
            attrs: {
              // line 是选择器名称,选中的边的 path 元素
              line: {
                stroke: "#8f8f8f",
                strokeWidth: 1,
              },
            },
          },
        ],
      };

      this.graph.fromJSON(data);
      this.graph.centerContent() // 居中显示

 

image

 

使用插件 -在antv3 版本中无需安装插件

对齐线功能

 

import { Snapline } from '@antv/x6'

graph.use(
  new Snapline({
    enabled: true,
  }),
)

 

数据导出。

graph.toJSON()

 

缩放与平移

const graph = new Graph({
  // ...其他配置
  panning: true,
  mousewheel: true
})

 

画布插件

import { Graph, Scroller, Snapline } from '@antv/x6'

const graph = new Graph({
  container: document.getElementById('container'),
  height: 300,
  width:800,
})

// Snapline 插件可以使节点在拖动过程中显示与其他节点的对齐线
graph.use(
  new Snapline({
    enabled: true,
  }),
)
// Scroller 插件可以使画布支持滚动
graph.use(
  new Scroller({
    enabled: true,
    pannable: true,
  }),
)

常用 API

graph.resize(800, 600) // resize 画布大小
graph.translate(20, 20) // 在 x、y 方向上平移画布
graph.zoom(0.2) // 将画布缩放级别增加 0.2(默认为1)
graph.zoom(-0.2) // 将画布缩放级别减少 0.2
graph.zoomTo(1.2) // 将画布缩放级别设置为 1.2
// 将画布中元素缩小或者放大一定级别,让画布正好容纳所有元素,可以通过 maxScale 配置最大缩放级别
graph.zoomToFit({ maxScale: 1 })
graph.centerContent() // 将画布中元素居中展示

 

节点渲染方式 -读一读-好好理解下

X6 是基于 SVG 的渲染引擎,可以使用不同的 SVG 元素渲染节点和边,非常适合节点内容比较简单的场景。面对复杂的节点, SVG 中有一个特殊的 foreignObject 元素,在该元素中可以内嵌任何 XHTML 元素,可以借助该元素来渲染 HTML、React/Vue/Angular 组件到需要位置,这会给项目开发带来非常大的便利。

在选择渲染方式时我们推荐:

  • 如果节点内容比较简单,而且需求比较固定,使用 SVG 节点
  • 其他场景,都推荐使用当前项目所使用的框架来渲染节点

 

添加节点-具备属性

   

image

 

 

   this.graph.addNode({
        shape: "rect",
        x: 390,
        y: 150,
        width: 100,
        height: 40,
        label:'test11',
        // angle: 90
      })

 

 

定制节点

我们可以通过 markup 和 attrs 来定制节点的形状和样式,markup 可以类比 HTMLattrs 类比 CSS

强烈建议仔细阅读 markup 和 attrs 文档。

 

Graph.registerNode(
  'custom-node',
  {
    inherit: 'rect', // 继承于 rect 节点
    width: 100,
    height: 40,
    markup: [
      {
        tagName: 'rect', // 标签名称
        selector: 'body', // 选择器
      },
      {
        tagName: 'image',
        selector: 'img',
      },
      {
        tagName: 'text',
        selector: 'label',
      },
    ],
    attrs: {
      body: {
        stroke: '#8f8f8f',
        strokeWidth: 1,
        fill: '#fff',
        rx: 6,
        ry: 6,
      },
      img: {
        'xlink:href':
          'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png',
        width: 16,
        height: 16,
        x: 12,
        y: 12,
      },
    },
  },
  true,
)

 

使用

  const source = this.graph.addNode({
        shape: "custom-node", // 可以直接使用上面注册过的 shape
        x: 40,
        y: 40,
        label: "hello",
      });

      const target = this.graph.addNode({
        shape: "custom-node",
        x: 160,
        y: 180,
        label: "world",
      });

      this.graph.addEdge({
        source,
        target,
        attrs: {
          line: {
            stroke: "#8f8f8f",
            strokeWidth: 1,
          },
        },
      });

 

 

 


修改节点

在渲染完成之后,我们还可以通过 API 修改节点的所有属性。我们会常用到下面两个方法:

    • node.prop(path, value),详细使用见 prop
    • node.attr(path, value),详细使用见 attr

 

 

const node = graph.addNode({
  shape: 'rect',
  width: 100,
  height: 40,
  x: 100,
  y: 100,
  label: 'node',
})
console.log(node.prop())

 

 

graph.addEdge({
  shape: 'edge',
  source: 'node1',
  target: 'node2',
})

 

配置边

下面分别看下上面的配置如何使用。

source/target

边的源和目标节点(点)。

 

具体其它使用看官网

修改边

节点类似,在渲染完成之后,我们还可以通过 API 修改边的所有属性。我们会常用到下面两个方法:

  • edge.prop(path, value),详细使用见 prop
  • edge.attr(path, value),详细使用见 attr

 

const edge = graph.addEdge({
  source: [200, 140],
  target: [500, 140],
  label: 'edge',
})
console.log(edge.prop())
edge.attr('line/stroke', '#ccc') // 修改边颜色,等价于 edge.prop('attrs/line/stroke', '#ccc')

 

连接桩

import React from 'react'
import { Graph } from '@antv/x6'
import './index.less'

Graph.registerNode(
  'custom-node-with-port',
  {
    inherit: 'rect',
    width: 100,
    height: 40,
    attrs: {
      body: {
        stroke: '#8f8f8f',
        strokeWidth: 1,
        fill: '#fff',
        rx: 6,
        ry: 6,
      },
    },
    ports: {
      groups: {
        top: {
          position: 'top',
          attrs: {
            circle: {
              magnet: true,
              stroke: '#8f8f8f',
              r: 5,
            },
          },
        },
        bottom: {
          position: 'bottom',
          attrs: {
            circle: {
              magnet: true,
              stroke: '#8f8f8f',
              r: 5,
            },
          },
        },
      },
    },
  },
  true,
)

export default class Example extends React.Component {
  private container: HTMLDivElement

  componentDidMount() {
    const graph = new Graph({
      container: this.container,
      background: {
        color: '#F2F7FA',
      },
    })

    const source = graph.addNode({
      shape: 'custom-node-with-port',
      x: 40,
      y: 40,
      label: 'hello',
      ports: {
        items: [
          {
            id: 'port_1',
            group: 'bottom',
          },
          {
            id: 'port_2',
            group: 'bottom',
          },
        ],
      },
    })

    const target = graph.addNode({
      shape: 'custom-node-with-port',
      x: 160,
      y: 180,
      label: 'world',
      ports: {
        items: [
          {
            id: 'port_3',
            group: 'top',
          },
          {
            id: 'port_4',
            group: 'top',
          },
        ],
      },
    })

    graph.addEdge({
      source: { cell: source, port: 'port_2' },
      target: { cell: target, port: 'port_3' },
      attrs: {
        line: {
          stroke: '#8f8f8f',
          strokeWidth: 1,
        },
      },
    })

    graph.centerContent()
  }

  refContainer = (container: HTMLDivElement) => {
    this.container = container
  }

  render() {
    return (
      <div className="config-app">
        <div className="app-content" ref={this.refContainer} />
      </div>
    )
  }
}

 

交互


validateXXX

我们还可以通过 validateXXX 方法来定义是否能创建连线或者连线是否有效。相比 allowXXXvalidateXXX 更具备灵活性。默认支持以下项:

    • validateMagnet:点击 magnet=true 的元素时 根据 validateMagnet 返回值来判断是否新增边,触发时机是元素被按下,如果返回 false,则没有任何反应,如果返回 true,会在当前元素创建一条新的边。
    • validateConnection:在移动边的时候判断连接是否有效,如果返回 false,当鼠标放开的时候,不会连接到当前元素,常常配合高亮功能一起使用。
    • validateEdge:当停止拖动边的时候根据 validateEdge 返回值来判断边是否生效,如果返回 false,该边会被清除。

 

交互限制

可以通过配置 interacting 来启动、禁用一些元素的交互行为,如果画布上元素纯预览,不能进行任何交互,可以直接设置为 false

new Graph({
  interacting: false,
})

如果需要更细节的定义允许哪些交互、禁用哪些交互,我们可以针对不同的属性值进行配置,支持的属性包括:

  • nodeMovable 节点是否可以被移动。
  • magnetConnectable 当在具有 magnet 属性的元素上按下鼠标开始拖动时,是否触发连线交互。
  • edgeMovable 边是否可以被移动。
  • edgeLabelMovable 边的标签是否可以被移动。
  • arrowheadMovable 边的起始/终止箭头(在使用 arrowhead 工具后)是否可以被移动。
  • vertexMovable 边的路径点是否可以被移动。
  • vertexAddable 是否可以添加边的路径点。
  • vertexDeletable 边的路径点是否可以被删除。

 

事件

image

 

 

画布缩放/平移

graph.on('scale', ({ sx, sy, ox, oy }) => {})
graph.on('resize', ({ width, height }) => {})
graph.on('translate', ({ tx, ty }) => {})

 

 

节点/边

添加/删除/修改

节点/边被添加到画布时,触发以下事件:

  • added
  • cell:added
  • node:added(仅当 cell 是节点时才触发)
  • edge:added(仅当 cell 是边时才触发)

当节点/边被移除时,触发以下事件:

  • removed
  • cell:removed
  • node:removed(仅当 cell 是节点时才触发)
  • edge:removed(仅当 cell 是边时才触发)

当节点/边发生任何改变时,触发以下事件:

  • changed
  • cell:changed
  • node:changed(仅当 cell 是节点时才触发)
  • edge:changed(仅当 cell 是边时才触发)

 

视图

由于 X6 实现了异步的渲染调度算法,所以节点的添加不一定意味着挂载到画布上。节点在被挂载到画布时以及从画布上卸载时会分别触发单独的事件

graph.on('view:mounted', ({ view }) => {})
graph.on('view:unmounted', ({ view }) => {})

 

数据

导出  graph.toJSON() 

导入 graph.fromJSON

 

动画

 

posted on 2026-02-14 14:47  Mc525  阅读(5)  评论(0)    收藏  举报

导航