# G6 — Full Documentation > G6 是一个简单、易用、完备的图可视化引擎,它在高定制能力的基础上,提供了一系列设计优雅、便于使用的图可视化解决方案。能帮助开发者搭建属于自己的图可视化、图分析、或图编辑器应用。 - [Resource index](/llms.txt) - Canonical site: https://g6.antv.antgroup.com/zh/ - Source repository: https://github.com/antvis/G6 - Languages: zh - Current version: 5.1.1 ## 中文文档 ### api #### 数据 - Canonical page: https://g6.antv.antgroup.com/zh/api/data/ - Markdown source: https://g6.antv.antgroup.com/zh/api/data.md - Description: 数据 --- title: "数据" description: "数据" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/data/" version: "5.1.1" --- ## 数据操作概述 G6 提供了一套全面的 [数据](/zh/manual/data/) 操作 API,覆盖了图数据从查询、修改到更新的完整生命周期。 ## API 参考 ### Graph.getData() 获取图的完整数据。 ```typescript getData(): Required; ``` **返回值**: - **类型**: [GraphData](#graphdata) - **描述**: 返回包含所有节点、边和组合数据的完整图数据 **示例**: ```typescript const graphData = graph.getData(); console.log('节点数据:', graphData.nodes); console.log('边数据:', graphData.edges); console.log('组合数据:', graphData.combos); ``` ### Graph.getNodeData() 获取节点数据,支持三种调用方式。 ```typescript // 获取所有节点数据 getNodeData(): NodeData[]; // 获取单个节点数据 getNodeData(id: ID): NodeData; // 批量获取多个节点数据 getNodeData(ids: ID[]): NodeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------ | -------- | ------ | ---- | | id | 节点 ID | string | - | | | ids | 节点 ID 数组 | string[] | - | | **返回值**: - **类型**: [NodeData](#nodedata) | [NodeData](#nodedata)[] - **描述**: 返回指定的节点数据或节点数据数组 **示例**: ```typescript // 获取所有节点 const nodes = graph.getNodeData(); // 获取单个节点 const node = graph.getNodeData('node1'); console.log('节点位置:', node.style.x, node.style.y); // 获取多个节点 const [node1, node2] = graph.getNodeData(['node1', 'node2']); ``` ### Graph.getEdgeData() 获取边数据,支持三种调用方式。 ```typescript // 获取所有边数据 getEdgeData(): EdgeData[]; // 获取单条边数据 getEdgeData(id: ID): EdgeData; // 批量获取多条边数据 getEdgeData(ids: ID[]): EdgeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ---------- | -------- | ------ | ---- | | id | 边 ID | string | - | | | ids | 边 ID 数组 | string[] | - | | **返回值**: - **类型**: [EdgeData](#edgedata) | [EdgeData](#edgedata)[] - **描述**: 返回指定的边数据或边数据数组 **示例**: ```typescript // 获取所有边 const edges = graph.getEdgeData(); // 获取单条边 const edge = graph.getEdgeData('edge1'); console.log('边的起点和终点:', edge.source, edge.target); // 获取多条边 const [edge1, edge2] = graph.getEdgeData(['edge1', 'edge2']); ``` ### Graph.getComboData() 获取组合数据,支持三种调用方式。 ```typescript // 获取所有组合数据 getComboData(): ComboData[]; // 获取单个组合数据 getComboData(id: ID): ComboData; // 批量获取多个组合数据 getComboData(ids: ID[]): ComboData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------ | -------- | ------ | ---- | | id | 组合 ID | string | - | | | ids | 组合 ID 数组 | string[] | - | | **返回值**: - **类型**: [ComboData](#combodata) | [ComboData](#combodata)[] - **描述**: 返回指定的组合数据或组合数据数组 **示例**: ```typescript // 获取所有组合 const combos = graph.getComboData(); // 获取单个组合 const combo = graph.getComboData('combo1'); console.log('组合包含的节点:', combo.children); // 获取多个组合 const [combo1, combo2] = graph.getComboData(['combo1', 'combo2']); ``` ### Graph.getElementData() 获取单个元素数据,支持两种调用方式。 ⚠️ **注意**: 此 API 直接获取元素的数据而不必考虑元素类型。 ```typescript // 获取单个元素数据 getElementData(id: ID): ElementDatum; // 批量获取多个元素数据 getElementData(ids: ID[]): ElementDatum[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------ | -------- | ------ | ---- | | id | 元素 ID | string | - | | | ids | 元素 ID 数组 | string[] | - | | **返回值**: - **类型**: ElementDatum \| ElementDatum[] - **描述**: 直接获取元素的数据而不必考虑元素类型 **示例**: ```typescript const element = graph.getElementData('node-1'); console.log('元素数据:', element); const elements = graph.getElementData(['node-1', 'edge-1']); console.log('多个元素数据:', elements); ``` ### Graph.getElementDataByState() 获取指定状态下的元素数据,支持三种调用方式。 ```typescript // 获取指定状态下的节点数据 getElementDataByState(elementType: 'node', state: string): NodeData[]; // 获取指定状态下的边数据 getElementDataByState(elementType: 'edge', state: string): EdgeData[]; // 获取指定状态下的组合数据 getElementDataByState(elementType: 'combo', state: string): ComboData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----------- | -------- | --------------------------------- | ------ | ---- | | elementType | 元素类型 | `'node'` \| `'edge'` \| `'combo'` | - | ✓ | | state | 状态 | string | - | ✓ | **返回值**: - **类型**: NodeData[] \| EdgeData[] \| ComboData[] - **描述**: 返回指定状态下的节点数据、边数据或组合数据 **示例**: ```typescript const selectedNodes = graph.getElementDataByState('node', 'selected'); console.log('选中的节点:', selectedNodes); const selectedEdges = graph.getElementDataByState('edge', 'selected'); console.log('选中的边:', selectedEdges); const selectedCombos = graph.getElementDataByState('combo', 'selected'); console.log('选中的组合:', selectedCombos); ``` **内置状态**: - `'selected'` - `'highlight'` - `'active'` - `'inactive'` - `'disabled'` ### Graph.getNeighborNodesData() 获取节点或组合的一跳邻居节点数据。 ```typescript getNeighborNodesData(id: ID): NodeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | --------------- | ------ | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | **返回值**: - **类型**: NodeData[] - **描述**: 返回邻居节点数据 **示例**: ```typescript const neighbors = graph.getNeighborNodesData('node-1'); console.log('邻居节点:', neighbors); ``` ### Graph.getRelatedEdgesData() 获取节点或组合关联边的数据。 ```typescript getRelatedEdgesData(id: ID, direction?: EdgeDirection): EdgeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | --------------- | ----------------------------- | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | | direction | 边的方向 | `'in'` \| `'out'` \| `'both'` | - | | **返回值**: - **类型**: EdgeData[] - **描述**: 返回与指定节点或组合关联的边数据 **示例**: ```typescript const relatedEdges = graph.getRelatedEdgesData('node-1'); console.log('关联边:', relatedEdges); ``` ### Graph.getParentData() 获取节点或组合的父元素数据。 ```typescript getParentData(id: ID, hierarchy: HierarchyKey): NodeLikeData | undefined; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------- | --------------------- | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | | hierarchy | 指定层级关系类型 | `'tree'` \| `'combo'` | - | | **返回值**: - **类型**: NodeData \| ComboData \| undefined - **描述**: 返回父元素数据,如果不存在则返回 undefined **示例**: ```typescript // 获取树图中节点的父节点 const treeParent = graph.getParentData('node1', 'tree'); // 获取组合中节点的父组合 const comboParent = graph.getParentData('node1', 'combo'); ``` ### Graph.getChildrenData() 获取节点或组合的子元素数据。 ```typescript getChildrenData(id: ID):(NodeData \| ComboData)[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | --------------- | ------ | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | **返回值**: - **类型**: (NodeData \| ComboData)[] - **描述**: 返回子元素数据数组 **注意**: - **查询 combo 的子元素**:如果 id 对应的是 combo 元素,可以直接通过此 API 获取其所有子元素。 - **查询节点的子元素**:如果 id 对应的是节点,只有当图数据为树结构(即节点数据中维护有 `children` 字段,且 `children` 为该节点的子节点 ID 数组)时,才能通过此 API 获取到该节点的子元素。否则返回空数组。 **示例**: ```typescript // 获取组合的子元素 const children = graph.getChildrenData('combo1'); console.log('子节点数量:', children.length); // 处理每个子元素 children.forEach((child) => { console.log('子元素ID:', child.id); }); ``` ### Graph.getAncestorsData() 获取节点或组合的所有祖先元素数据。 ```typescript getAncestorsData(id: ID, hierarchy: HierarchyKey): NodeLikeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------- | --------------------- | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | | hierarchy | 指定层级关系类型 | `'tree'` \| `'combo'` | - | ✓ | **返回值**: - **类型**: [NodeData](#nodedata)[] \| [ComboData](#combodata)[] - **描述**: 返回祖先元素数据数组,从父节点到根节点的顺序排列 **示例**: ```typescript // 获取树图中节点的所有祖先节点 const treeAncestors = graph.getAncestorsData('node1', 'tree'); console.log( '祖先节点路径:', treeAncestors.map((node) => node.id), ); // 获取组合中节点的所有父组合 const comboAncestors = graph.getAncestorsData('node1', 'combo'); ``` ### Graph.getDescendantsData() 获取节点或组合的所有后代元素数据。 ```typescript getDescendantsData(id: ID): NodeLikeData[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | --------------- | ------ | ------ | ---- | | id | 节点或组合的 ID | string | - | ✓ | **返回值**: - **类型**: [NodeData](#nodedata)[] \| [ComboData](#combodata)[] - **描述**: 返回后代元素数据数组 **示例**: ```typescript // 获取节点的所有后代 const descendants = graph.getDescendantsData('node1'); console.log('后代数量:', descendants.length); // 处理所有后代元素 descendants.forEach((descendant) => { console.log('后代元素ID:', descendant.id); }); ``` ### Graph.setData() 设置图的完整数据。 ```typescript setData(data: GraphData | ((prev: GraphData) => GraphData)): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------ | ----------------------------------------------------------- | ------ | ---- | | data | 新的图数据或返回新图数据的函数 | [GraphData](#graphdata) \| ((prev: GraphData) => GraphData) | - | ✓ | **示例**: ```typescript // 直接设置数据 graph.setData({ nodes: [ { id: 'node1', style: { x: 100, y: 100 } }, { id: 'node2', style: { x: 200, y: 200 } }, ], edges: [{ id: 'edge1', source: 'node1', target: 'node2' }], }); // 使用函数式增量更新:获取当前图数据,并返回新的图数据 graph.setData((prev) => ({ ...prev, nodes: [...prev.nodes, { id: 'node3', style: { x: 300, y: 300 } }], })); ``` ### Graph.addData() 新增元素数据。 ```typescript addData(data: GraphData | ((prev: GraphData) => GraphData)): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | ----------------------------------------------------------- | ------ | ---- | | data | 需要添加的图数据或返回新图数据的函数 | [GraphData](#graphdata) \| ((prev: GraphData) => GraphData) | - | ✓ | **示例**: ```typescript graph.addData({ nodes: [{ id: 'node-1' }, { id: 'node-2' }], edges: [{ source: 'node-1', target: 'node-2' }], }); ``` ### Graph.addNodeData() 新增节点数据。 ```typescript addNodeData(data: NodeData[] | ((prev: NodeData[]) => NodeData[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | ----------------------------------------------------------- | ------ | ---- | | data | 要添加的节点数据或返回节点数据的函数 | [NodeData](#nodedata)[] \| (prev: NodeData[]) => NodeData[] | - | ✓ | **示例**: ```typescript // 添加单个节点 graph.addNodeData([ { id: 'node1', style: { x: 100, y: 100 }, data: { label: '节点 1' }, }, ]); // 批量添加节点 graph.addNodeData([ { id: 'node2', style: { x: 200, y: 200 } }, { id: 'node3', style: { x: 300, y: 300 } }, ]); // 函数式添加 graph.addNodeData((prev) => [...prev, { id: 'node4', style: { x: 400, y: 400 } }]); ``` ### Graph.addEdgeData() 新增边数据。 ```typescript addEdgeData(data: EdgeData[] | ((prev: EdgeData[]) => EdgeData[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------------------------------- | ------------------------------------------------------------- | ------ | ---- | | data | 要添加的边数据或返回边数据的函数 | [EdgeData](#edgedata)[] \| ((prev: EdgeData[]) => EdgeData[]) | - | ✓ | **示例**: ```typescript // 添加单条边 graph.addEdgeData([ { id: 'edge1', source: 'node1', target: 'node2', data: { weight: 1, label: '关系', }, }, ]); // 批量添加边 graph.addEdgeData([ { id: 'edge2', source: 'node2', target: 'node3' }, { id: 'edge3', source: 'node3', target: 'node1' }, ]); // 函数式添加 graph.addEdgeData((prev) => [...prev, { id: 'edge4', source: 'node1', target: 'node4' }]); ``` ### Graph.addComboData() 新增组合数据。 ```typescript addComboData(data: ComboData[] | ((prev: ComboData[]) => ComboData[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | --------------------------------------------------------------- | ------ | ---- | | data | 要添加的组合数据或返回组合数据的函数 | [ComboData](#combodata)[] \| (prev: ComboData[]) => ComboData[] | - | ✓ | **示例**: ```typescript graph.addComboData([{ id: 'combo1', children: ['node1', 'node2'] }]); ``` ### Graph.addChildrenData() 为树图节点添加子节点数据。 ⚠️ **注意**: 为组合添加子节点使用 addNodeData / addComboData 方法。 ```typescript addChildrenData(parentId: ID, childrenData: NodeData[]): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------------ | ---------- | ----------------------- | ------ | ---- | | parentId | 父节点 ID | string | - | ✓ | | childrenData | 子节点数据 | [NodeData](#nodedata)[] | - | ✓ | **示例**: ```typescript graph.addChildrenData('node1', [{ id: 'node2' }]); ``` ### Graph.removeData() 删除元素数据。 ```typescript removeData(ids: DataID | ((data: GraphData) => DataID)): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | -------------------------------------------------- | ------ | ---- | | ids | 要删除的元素 ID 或返回元素 ID 的函数 | [DataID](#dataid) \| ((data: GraphData) => DataID) | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.removeData({ nodes: ['node-1', 'node-2'], edges: ['edge-1'], }); ``` ### Graph.removeNodeData() 删除节点数据。 ```typescript removeNodeData(ids: ID[] | ((data: NodeData[]) => ID[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | --------------------------------------------------------------- | ------ | ---- | | ids | 要删除的节点 ID 或返回节点 ID 的函数 | [ID](#id)[] \| ((data: [NodeData](#nodedata)[]) => [ID](#id)[]) | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.removeNodeData(['node-1', 'node-2']); ``` ### Graph.removeEdgeData() 删除边数据。 ```typescript removeEdgeData(ids: ID[] | ((data: EdgeData[]) => ID[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------------------------------- | --------------------------------------------------------------- | ------ | ---- | | ids | 要删除的边 ID 或返回边 ID 的函数 | [ID](#id)[] \| ((data: [EdgeData](#edgedata)[]) => [ID](#id)[]) | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.removeEdgeData(['edge-1']); ``` ### Graph.removeComboData() 删除组合数据。 ```typescript removeComboData(ids: ID[] | ((data: ComboData[]) => ID[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | --------------------------------------------------------------- | ------ | ---- | | ids | 要删除的组合 ID 或返回组合 ID 的函数 | [ID](#id)[] \| (data: [ComboData](#combodata)[]) => [ID](#id)[] | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.removeComboData(['combo-1']); ``` ### Graph.updateData() 更新元素数据。 ⚠️ **注意**: 只需要传入需要更新的数据即可,不必传入完整的数据。 ```typescript updateData(data: PartialGraphData | ((prev: GraphData) => PartialGraphData)): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | -------------------------------------------------------------------------------- | ------ | ---- | | data | 要更新的元素数据或返回元素数据的函数 | [PartialGraphData](#partialgraphdata) \| ((prev: GraphData) => PartialGraphData) | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.updateData({ nodes: [{ id: 'node-1', style: { x: 100, y: 100 } }], edges: [{ id: 'edge-1', style: { lineWidth: 2 } }], }); ``` ### Graph.updateNodeData() 更新节点数据。 ⚠️ **注意**: 只需要传入需要更新的数据即可,不必传入完整的数据。 ```typescript updateNodeData(data: NodeData[] | ((prev: NodeData[]) => NodeData[])): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | ---------------------------------------------- | ------ | ---- | | data | 要更新的节点数据或返回节点数据的函数 | NodeData[] \| (prev: NodeData[]) => NodeData[] | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.updateNodeData([{ id: 'node-1', style: { x: 100, y: 100 } }]); ``` ### Graph.updateEdgeData() 更新边数据。 ⚠️ **注意**: 只需要传入需要更新的数据即可,不必传入完整的数据。 ```typescript updateEdgeData(data: (PartialEdgeData[] | ((prev: EdgeData[]) => PartialEdgeData[]))): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------ | ---- | | data | 要更新的边数据或返回边数据的函数 | [PartialEdgeData\](#partialedgedata)[] \| (prev: EdgeData[]) => [PartialEdgeData\](#partialedgedata)[] | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.updateEdgeData([{ id: 'edge-1', style: { lineWidth: 2 } }]); ``` ### Graph.updateComboData() 更新组合数据。 ⚠️ **注意**: 只需要传入需要更新的数据即可,不必传入完整的数据。 ```typescript updateComboData(data: (ComboData[] | ((prev: ComboData[]) => ComboData[]))): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------------------ | --------------------------------------------------------------- | ------ | ---- | | data | 要更新的组合数据或返回组合数据的函数 | [ComboData](#combodata)[] \| (prev: ComboData[]) => ComboData[] | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript graph.updateComboData([{ id: 'combo-1', style: { x: 100, y: 100 } }]); ``` ### Graph.hasNode() 判断节点是否存在 ```typescript hasNode(id:ID): boolean; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------------------- | --------- | ------ | ---- | | id | 需要进行判断的节点id | [ID](#id) | - | ✓ | **返回值**: - **类型**: boolean **示例**: ```typescript graph.hasNode('node-1'); ``` ### Graph.hasEdge() 判断边是否存在 ```typescript hasEdge(id:ID): boolean; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------ | --------- | ------ | ---- | | id | 需要进行判断的边id | [ID](#id) | - | ✓ | **返回值**: - **类型**: boolean **示例**: ```typescript graph.hasEdge('edge-1'); ``` ### Graph.hasCombo() 判断combo是否存在 ```typescript hasCombo(id:ID): boolean; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------------------------- | --------- | ------ | ---- | | id | 需要进行判断的combo组合id | [ID](#id) | - | ✓ | **返回值**: - **类型**: boolean **示例**: ```typescript graph.hasCombo('combo-1'); ``` ## 类型定义 ### ID 元素 ID 类型。 ```typescript type ID = string; ``` ### DataID 多个元素 ID 类型。 ```typescript interface DataID { nodes?: ID[]; edges?: ID[]; combos?: ID[]; } ``` ### GraphData G6 图数据类型。 ```typescript interface GraphData { nodes?: NodeData[]; edges?: EdgeData[]; combos?: ComboData[]; } ``` ### NodeData 节点数据类型。 ```typescript interface NodeData { id: string; // 节点 ID type?: string; // 节点类型 data?: Record; // 节点数据 style?: Record; // 节点样式 states?: string[]; // 节点初始状态 combo?: string; // 所属组合 children?: string[]; // 子节点 ID 数组 } ``` 详细类型定义请参考 [节点数据](/zh/manual/data/#节点数据nodedata)。 ### EdgeData 边数据类型。 ```typescript interface EdgeData { source: string; // 起点 ID target: string; // 终点 ID id?: string; // 边 ID type?: string; // 边类型 data?: Record; // 边数据 style?: Record; // 边样式 states?: string[]; // 边初始状态 } ``` 详细类型定义请参考 [边数据](/zh/manual/data/#边数据edgedata)。 ### ComboData 组合数据类型。 ```typescript interface ComboData { id: string; // 组合 ID type?: string; // 组合类型 data?: Record; // 组合数据 style?: Record; // 组合样式 states?: string[]; // 组合初始状态 combo?: string; // 父组合 ID } ``` 详细类型定义请参考 [组合数据](/zh/manual/data/#组合数据combodata)。 #### 画布操作 - Canonical page: https://g6.antv.antgroup.com/zh/api/canvas/ - Markdown source: https://g6.antv.antgroup.com/zh/api/canvas.md - Description: 画布操作 --- title: "画布操作" description: "画布操作" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/canvas/" version: "5.1.1" --- ## 画布操作概述 G6 提供了一系列画布操作 API,用于控制和获取画布的基本信息。通过这些 API,你可以: - 获取画布实例 - 获取和设置画布尺寸 - 操作画布渲染器和图层 ## API 参考 ### Graph.getCanvas() 获取画布实例,返回的实例可用于进行底层的画布操作。 ```typescript getCanvas(): Canvas; ``` **返回值类型说明** Canvas 实例包含以下主要功能: - `getLayer(name?: string)`: 获取指定图层 - `getLayers()`: 获取所有图层 - `getCamera()`: 获取相机实例 - `getRoot()`: 获取根节点 - `setCursor(cursor: string)`: 设置鼠标样式 **示例** ```typescript // 获取画布实例 const canvas = graph.getCanvas(); // 获取主图层 const mainLayer = canvas.getLayer('main'); // 设置鼠标样式 canvas.setCursor('pointer'); // 获取画布根节点 const root = canvas.getRoot(); ``` ### Graph.getSize() 获取当前画布容器的尺寸。返回一个包含宽度和高度的数组。 ```typescript getSize(): [number, number]; ``` **示例** ```typescript // 获取画布尺寸 const [width, height] = graph.getSize(); console.log('画布宽度:', width); console.log('画布高度:', height); // 使用尺寸信息进行计算 const centerX = width / 2; const centerY = height / 2; ``` ### Graph.setSize(width, height) 设置画布容器的尺寸。这个方法会同时更新画布和容器的大小。 ```typescript setSize(width: number, height: number): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | ---------------- | ------ | ------ | ---- | | width | 画布宽度(像素) | number | - | ✓ | | height | 画布高度(像素) | number | - | ✓ | **示例** ```typescript // 设置固定尺寸 graph.setSize(800, 600); ``` #### 元素操作 - Canonical page: https://g6.antv.antgroup.com/zh/api/element/ - Markdown source: https://g6.antv.antgroup.com/zh/api/element.md - Description: 元素操作 --- title: "元素操作" description: "元素操作" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/element/" version: "5.1.1" --- ## 元素操作概述 G6 中的 [元素](/zh/manual/element/overview/) 操作 API 允许您控制图中节点、边和组合(Combo)等元素的行为和属性。这些 API 可以用于: 1. **元素状态管理**:设置、更新或移除元素的状态 2. **元素显示控制**:控制元素的层级、可见性 3. **元素展开/收起**:操作可折叠元素的展开/收起状态 4. **元素位置操作**:移动、对齐元素位置 5. **元素聚焦**:将视口聚焦到特定元素 通过这些操作,您可以实现丰富的交互效果和视觉呈现。 ## API 参考 ### Graph.getElementPosition(id) 获取元素位置。 ```typescript getElementPosition(id: ID): Point; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: [number, number] \| [number, number, number] - **描述**: 返回元素的坐标位置 **示例**: ```typescript graph.getElementPosition('node1'); ``` ### Graph.getElementRenderBounds(id) 获取元素自身以及子节点在世界坐标系下的渲染包围盒。 ```typescript getElementRenderBounds(id: ID): AABB; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: [AABB](#aabb) - **描述**: 返回元素的渲染包围盒 ### Graph.getElementRenderStyle(id) 获取元素的渲染样式。 ```typescript getElementRenderStyle(id: ID): Record; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: Record\ - **描述**: 返回元素的渲染样式 ### Graph.getElementState(id) 获取元素的状态。 ```typescript getElementState(id: ID): State[]; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: [State](#state)[] - **描述**: 返回元素的状态 ### Graph.getElementType(id) 获取元素类型。 ```typescript getElementType(id: ID): string; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: string - **描述**: 返回元素的类型 ### Graph.getElementVisibility(id) 获取元素可见性。 ```typescript getElementVisibility(id: ID): 'visible' | 'hidden' ; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: 'visible' | 'hidden' - **描述**: 返回元素的可见性 ### Graph.getElementZIndex(id) 获取元素层级。 ```typescript getElementZIndex(id: ID): number; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | **返回值**: - **类型**: number - **描述**: 返回元素的层级 ### Graph.setElementState(id, state, options) 设置元素状态,支持两种调用方式: ```typescript // 设置单个元素状态 setElementState(id: ID, state: State | State[], animation?: boolean): Promise; // 批量设置元素状态 setElementState(state: Record, animation?: boolean): Promise; ``` **参数**: **单个元素状态设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------- | -------------------------- | ------ | ---- | | id | 要设置状态的元素 ID | string | - | ✓ | | state | 要设置的状态 | [State](#state) \| State[] | - | ✓ | | animation | 是否启用动画 | boolean | - | | **批量元素状态设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------ | -------------------------------------- | ------ | ---- | | state | 元素ID到状态的映射 | Record | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,状态设置操作完成后 resolve **示例**: ```typescript // 设置单个元素状态 await graph.setElementState('node1', 'selected'); // 设置多个元素状态 await graph.setElementState({ node1: 'selected', node2: 'hover', node3: ['selected', 'hover'], }); ``` ### Graph.setElementVisibility(id, visibility, animation) 设置元素的可见性,支持两种调用方式: ```typescript // 设置单个元素可见性 setElementVisibility(id: ID, visibility: 'visible' | 'hidden', animation?: boolean): Promise; // 批量设置元素可见性 setElementVisibility(visibility: Record, animation?: boolean): Promise; ``` **参数**: **单个元素可见性设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---------- | --------------------- | ------------------------- | ------ | ---- | | id | 要设置可见性的元素 ID | string | - | ✓ | | visibility | 要设置的可见性 | `'visible'` \| `'hidden'` | - | ✓ | | animation | 是否启用动画 | boolean | - | | **批量元素可见性设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---------- | -------------------- | ------------------------------------- | ------ | ---- | | visibility | 元素ID到可见性的映射 | Record | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,可见性设置操作完成后 resolve **示例**: ```typescript // 设置单个元素可见性 await graph.setElementVisibility('node1', 'hidden'); // 设置多个元素可见性 await graph.setElementVisibility({ node1: 'hidden', node2: 'visibility', }); ``` ### Graph.setElementZIndex(id, zIndex) 设置元素的层级,有两种调用方式: ```typescript // 设置单个元素层级 setElementZIndex(id: ID, zIndex: number): Promise; // 批量设置元素层级 setElementZIndex(zIndex: Record): Promise; ``` **参数**: **单个元素层级设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | ------- | ------ | ------ | ---- | | id | 元素 ID | string | - | ✓ | | zIndex | 层级 | number | - | ✓ | **批量元素层级设置** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | ------------------ | ------------------ | ------ | ---- | | zIndex | 元素ID到层级的映射 | Record | - | ✓ | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,层级设置操作完成后 resolve **示例**: ```typescript // 设置单个元素层级 await graph.setElementZIndex('node1', 10); // 设置多个元素层级 await graph.setElementZIndex({ node1: 10, node2: 20, node3: 30, }); ``` ### Graph.setNode(node) 设置节点样式映射。即 `options.node` 的值。 ```typescript setNode(node: NodeOptions): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------- | -------------------------------------------- | ------ | ---- | | node | 节点配置 | [NodeOptions](/zh/manual/element/node/overview/) | - | ✓ | **示例**: ```typescript // 设置所有的节点填充色为红色 graph.setNode({ style: { fill: 'red', }, }); ``` ### Graph.setEdge(edge) 设置边样式映射。即 `options.edge` 的值。 ```typescript setEdge(edge: EdgeOptions): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------ | -------------------------------------------- | ------ | ---- | | edge | 边配置 | [EdgeOptions](/zh/manual/element/edge/overview/) | - | ✓ | ### Graph.setCombo(combo) 设置组合样式映射。即 `options.combo` 的值。 ```typescript setCombo(combo: ComboOptions): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----- | -------- | ---------------------------------------------- | ------ | ---- | | combo | 组合配置 | [ComboOptions](/zh/manual/element/combo/overview/) | - | ✓ | ### Graph.collapseElement(id, options) 收起指定元素,通常用于折叠组合(Combo)或具有子元素的节点。 ```typescript collapseElement(id: ID, options?: boolean | CollapseExpandNodeOptions): Promise; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------- | ---------------------------------- | ------------------------------------------------------------------ | ------ | ---- | | id | 要收起的元素 ID | string | - | ✓ | | options | 是否启用动画或收起节点的详细配置项 | boolean \| [CollapseExpandNodeOptions](#collapseexpandnodeoptions) | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,收起操作完成后 resolve **示例**: ```typescript // 简单收起,使用默认配置 await graph.collapseElement('combo1'); // 收起并启用动画 await graph.collapseElement('combo1', true); // 收起并保证展开/收起的节点位置不变 await graph.collapseElement('combo1', { align: true, }); ``` ### Graph.expandElement(id, options) 展开指定元素,通常用于展开先前收起的组合(Combo)或节点。 ```typescript expandElement(id: ID, options?: boolean | CollapseExpandNodeOptions): Promise; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------- | ---------------------------------- | ------------------------------------------------------------------ | ------ | ---- | | id | 要展开的元素 ID | string | - | ✓ | | options | 是否启用动画或展开节点的详细配置项 | boolean \| [CollapseExpandNodeOptions](#collapseexpandnodeoptions) | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,展开操作完成后 resolve **示例**: ```typescript // 简单展开,使用默认配置 await graph.expandElement('combo1'); // 展开并启用动画 await graph.expandElement('combo1', true); // 展开并保证展开/收起的节点位置不变 await graph.expandElement('combo1', { align: true, }); ``` ### Graph.frontElement(id) 将指定元素置于最顶层,使其显示在其他重叠元素之上。 ```typescript frontElement(id: ID | ID[]): void; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ------- | ------------------ | ------ | ---- | | id | 元素 ID | string \| string[] | - | ✓ | **返回值**: - **类型**: void **示例**: ```typescript // 将节点置于最顶层 graph.frontElement('node1'); // 对于选中的多个节点,都置于最顶层 graph.frontElement(['node1', 'node2', 'node3']); ``` ### Graph.showElement(id, animation) 显示指定元素。 ```typescript showElement(id: ID | ID[], animation?: boolean): Promise; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------ | ------------------ | ------ | ---- | | id | 元素 ID | string \| string[] | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,显示操作完成后 resolve **示例**: ```typescript // 显示单个元素 await graph.showElement('node1'); // 带动画显示元素 await graph.showElement('node1', true); // 显示多个元素 await graph.showElement(['node1', 'node2', 'node3']); ``` ### Graph.hideElement(id, animation) 隐藏指定元素。 ```typescript hideElement(id: ID | ID[], animation?: boolean): Promise; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------ | ------------------ | ------ | ---- | | id | 元素 ID | string \| string[] | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,隐藏操作完成后 resolve **示例**: ```typescript // 无动画隐藏元素 await graph.hideElement('node1'); // 带动画隐藏元素 await graph.hideElement('node1', true); // 隐藏多个元素 await graph.hideElement(['node1', 'node2', 'node3'], true); ``` ### Graph.translateElementBy(id, offset, animation) 相对平移元素指定距离,支持两种调用方式: ```typescript // 将元素平移指定距离(相对平移) translateElement(id: ID, offset: Point, animation?: boolean): Promise; // 批量将元素平移指定距离(相对平移) translateElement(offsets: Record, animation?: boolean): Promise; ``` **参数**: **单个元素平移** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ----------------------- | ---------------- | ------ | ---- | | id | 要平移的元素 ID | string | - | ✓ | | offset | 平移的相对距离 [dx, dy] | [number, number] | - | ✓ | | animation | 是否启用动画 | boolean | - | | **批量元素平移** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------------- | ---------------------------- | ------ | ---- | | offsets | 元素ID到平移距离的映射 | Record | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,平移操作完成后 resolve **示例**: ```typescript // 向右平移100像素,向下平移50像素 await graph.translateElementBy('node1', [100, 50]); // 带动画平移 await graph.translateElementBy('node1', [100, 50], true); // 对多个节点应用相同的平移 await graph.translateElementBy( { node1: [50, 50], node2: [100, 100], node3: [150, 150], }, true, ); ``` ### Graph.translateElementTo(id, position, animation) 将元素移动到指定位置,支持两种调用方式: ```typescript // 将元素移动到指定位置(绝对位置) translateElementTo(id: ID, position: Point, animation?: boolean): Promise; // 批量将元素移动到指定位置(绝对位置) translateElementTo(positions: Record, animation?: boolean): Promise; ``` **参数**: **单个元素移动** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------- | ---------------- | ------ | ---- | | id | 要移动的元素 ID | string | - | ✓ | | position | 目标绝对位置 [x, y] | [number, number] | - | ✓ | | animation | 是否启用动画 | boolean | - | | **批量元素移动** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------------- | -------------------------------- | ------ | ---- | | positions | 元素ID到目标位置的映射 | Record | - | ✓ | | animation | 是否启用动画 | boolean | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,移动操作完成后 resolve **示例**: ```typescript // 将节点移动到画布的 (200, 300) 位置 await graph.translateElementTo('node1', [200, 300]); // 带动画移动 await graph.translateElementTo('node1', [200, 300], true); // 将一组节点整齐排列 await graph.translateElementTo( { node1: [100, 100], node2: [200, 200], node3: [300, 100], }, true, ); ``` ### Graph.focusElement(id, animation) 聚焦到指定元素,使元素居中于视口。 ```typescript focusElement(id: ID | ID[], animation?: ViewportAnimationEffectTiming): Promise; ``` **参数**: | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------------- | --------------------------------------------------------------- | ------ | ---- | | id | 要聚焦的一个或多个元素 ID | string \| string[] | - | ✓ | | animation | 视口动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | **返回值**: - **类型**: Promise\ - **描述**: 返回一个 Promise,聚焦操作完成后 resolve **示例**: ```typescript // 聚焦到单个节点 await graph.focusElement('node1'); // 使用自定义动画配置 await graph.focusElement('node1', { duration: 800, easing: 'ease-in-out', }); // 聚焦到多个节点 await graph.focusElement(['node1', 'node2', 'node3']); ``` ## 类型定义 ### CollapseExpandNodeOptions 收起或展开元素的配置选项。 ```typescript interface CollapseExpandNodeOptions { /** * 是否使用动画 */ animation?: boolean; /** * 保证展开/收起的节点位置不变 */ align?: boolean; } ``` ### ViewportAnimationEffectTiming 视口动画配置类型。 ```typescript type ViewportAnimationEffectTiming = | boolean // 是否启用动画 | { easing?: string; // 缓动函数 duration?: number; // 动画持续时间(ms) }; ``` ### AABB AABB (Axis-Aligned Bounding Box) 是"轴对齐包围盒"的缩写,是计算机图形学中的一个基础概念。 ```typescript interface AABB { x: number; // 矩形左上角的 x 坐标 y: number; // 矩形左上角的 y 坐标 width: number; // 矩形宽度 height: number; // 矩形高度 } ``` ### State 元素状态类型。 ```typescript type State = 'selected' | 'hover' | 'active' | 'inactive' | 'disabled' | string; ``` #### 图实例 - Canonical page: https://g6.antv.antgroup.com/zh/api/graph/ - Markdown source: https://g6.antv.antgroup.com/zh/api/graph.md - Description: 图实例 --- title: "图实例" description: "图实例" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/graph/" version: "5.1.1" --- ## API 参考 ### Graph.destroy() 销毁当前图实例,释放与图实例相关的所有资源。 ⚠️ **注意**: 销毁后无法进行任何操作,如果需要重新使用,需要重新创建一个新的图实例。 ```typescript destroy(): void; ``` **使用场景**: - 当用户关闭图表或切换到其他视图时,可以调用此方法来释放资源。 - 在需要重新创建图实例时,确保先销毁旧的实例,以避免内存泄漏。 #### 绘制与渲染 - Canonical page: https://g6.antv.antgroup.com/zh/api/render/ - Markdown source: https://g6.antv.antgroup.com/zh/api/render.md - Description: 绘制与渲染 --- title: "绘制与渲染" description: "绘制与渲染" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/render/" version: "5.1.1" --- ## 绘制与渲染概述 G6 提供了一系列绘制和渲染相关的 API,用于控制图形元素的显示过程。在 G6 中,绘制和渲染是两个不同的概念: - **绘制(draw)**: 仅负责将图形元素绘制到画布上,不涉及布局计算 - **渲染(render)**: 完整的渲染流程,包括数据处理、布局计算和最终绘制 理解这些 API 的区别对于优化性能和实现特定效果至关重要。 ## API 参考 ### Graph.draw() 绘制元素,但不执行布局计算。 ```typescript draw(): Promise; ``` **说明** `draw` 方法仅执行元素的绘制过程,不会重新计算布局。 ⚠️ **注意**: `draw` 为异步方法,需要使用 `await` 或 Promise 链式调用来确保绘制完成后再执行后续操作。 **示例 1**: 基础用法 ```typescript // 基本用法 await graph.draw(); ``` **示例 2**: 修改节点样式后重新绘制 ```javascript // 修改节点样式后重新绘制 graph.updateNodeData([ { id: 'node1', style: { fill: 'red', stroke: 'blue', lineWidth: 2, }, }, ]); // 仅绘制更新后的样式,不重新布局 await graph.draw(); ``` **示例 3**: 批量更新多个元素后一次性绘制 ```javascript // 更新多个节点 graph.updateNodeData([{ id: 'node1', style: { fill: 'red' } }]); graph.updateNodeData([{ id: 'node2', style: { fill: 'blue' } }]); // 更新边 graph.updateEdgeData([{ id: 'edge1', style: { stroke: 'green' } }]); // 批量操作完成后绘制 await graph.draw(); ``` **示例 4**: 使用事件监听绘制完成 ```javascript import { GraphEvent } from '@antv/g6'; graph.on(GraphEvent.AFTER_DRAW, () => { console.log('绘制完成'); }); await graph.draw(); ``` ### Graph.render() 执行完整的渲染流程,包括数据处理、布局计算和绘制。 ```typescript render(): Promise; ``` **说明** `render` 方法会执行完整的渲染流程: 1. 处理数据更新 2. 绘制元素到画布上 3. 执行布局算法 **示例 1**: 基本用法 ```typescript // 基本用法 await graph.render(); ``` **示例 2**: 添加新数据后渲染 ```typescript graph.addData({ nodes: [{ id: 'node3' }, { id: 'node4' }], edges: [{ id: 'edge2', source: 'node1', target: 'node3' }], }); await graph.render(); ``` **示例 3**: 监听渲染事件 ```typescript import { GraphEvent } from '@antv/g6'; // 渲染开始前 graph.on(GraphEvent.BEFORE_RENDER, () => { console.log('渲染开始...'); // 显示加载指示器 showLoadingIndicator(); }); // 渲染完成后 graph.on(GraphEvent.AFTER_RENDER, () => { console.log('渲染完成'); // 隐藏加载指示器 hideLoadingIndicator(); }); graph.render(); ``` ### Graph.clear() 清空画布上的所有元素,包括节点、边和其他图形元素。 ```typescript clear(): Promise; ``` **说明** 此方法会删除图中的所有元素,但保留画布配置和样式。这是一个异步方法,返回一个 Promise。 **示例** ```typescript // 基本用法 await graph.clear(); ``` ## 使用技巧 ### draw 与 render 的选择 - 使用 `draw()` 当: - 仅修改了元素样式或状态,不需要重新计算位置 - 性能敏感,希望避免不必要的布局计算 - 使用 `render()` 当: - 初始化图表 - 更改了布局配置 - 添加或删除了大量节点/边 - 需要重新计算所有元素位置 #### 视口操作 - Canonical page: https://g6.antv.antgroup.com/zh/api/viewport/ - Markdown source: https://g6.antv.antgroup.com/zh/api/viewport.md - Description: 视口操作 --- title: "视口操作" description: "视口操作" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/viewport/" version: "5.1.1" --- ## 视口操作概述 G6 提供了一系列视口操作 API,用于控制画布的缩放、平移和旋转。这些操作可以帮助用户更好地查看和交互图形内容。通过视口操作,你可以实现以下功能: - 缩放画布以查看细节或全局视图 - 平移画布以查看不同区域 - 旋转画布以获得不同视角 - 自动适配内容到视口 ### 视口操作分类 G6 的视口操作主要分为以下几类: 1. **缩放操作**:如 `zoomTo`、`zoomBy` 2. **平移操作**:如 `translateTo`、`translateBy` 3. **旋转操作**:如 `rotateTo`、`rotateBy` 4. **自适应操作**:如 `fitView`、`fitCenter` 5. **视口信息获取**:如 `getZoom`、`getPosition` ## API 参考 ### Graph.zoomTo(zoom, animation, origin) 缩放画布至指定比例(绝对缩放)。 ```typescript zoomTo(zoom: number, animation?: ViewportAnimationEffectTiming, origin?: Point): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | --------------------------------------------- | --------------------------------------------------------------- | ------ | ---- | | zoom | 目标缩放比例 (1 = 原始大小, >1 放大, <1 缩小) | number | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | | origin | 缩放中心点(视口坐标) | [Point](#point) | - | | **示例** ```typescript // 放大到2倍 graph.zoomTo(2); // 带动画效果的缩小到0.5倍 graph.zoomTo(0.5, { duration: 500, easing: 'ease', }); // 以视口中心点为原点放大 graph.zoomTo(1.5, false, graph.getCanvasCenter()); ``` ### Graph.zoomBy(ratio, animation, origin) 基于当前缩放比例进行缩放(相对缩放)。 ```typescript zoomBy(ratio: number, animation?: ViewportAnimationEffectTiming, origin?: Point): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | --------------------------- | --------------------------------------------------------------- | ------ | ---- | | ratio | 缩放比例 (>1 放大, <1 缩小) | number | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | | origin | 缩放中心点(视口坐标) | [Point](#point) | - | | **示例** ```typescript // 在当前比例基础上放大1.2倍 graph.zoomBy(1.2); // 在当前比例基础上缩小到0.8倍,带动画 graph.zoomBy(0.8, { duration: 300, }); ``` ### Graph.translateTo(position, animation) 将图平移至指定位置(绝对平移)。 ```typescript translateTo(position: Point, animation?: ViewportAnimationEffectTiming): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------ | --------------------------------------------------------------- | ------ | ---- | | position | 目标位置坐标 | [Point](#point) | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | **示例** ```typescript // 平移到指定位置 graph.translateTo([100, 100]); // 带动画效果的平移 graph.translateTo([200, 200], { duration: 1000, easing: 'ease-in-out', }); ``` ### Graph.translateBy(offset, animation) 将图相对当前位置平移指定距离(相对平移)。 ```typescript translateBy(offset: Point, animation?: ViewportAnimationEffectTiming): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------- | --------------------------------------------------------------- | ------ | ---- | | offset | 平移偏移量 | [Point](#point) | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | **示例** ```typescript // 向右平移100像素,向下平移50像素 graph.translateBy([100, 50]); // 带动画效果的相对平移 graph.translateBy([-50, -50], { duration: 500, }); ``` ### Graph.rotateTo(angle, animation, origin) 旋转画布至指定角度(绝对旋转)。 ```typescript rotateTo(angle: number, animation?: ViewportAnimationEffectTiming, origin?: Point): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------- | --------------------------------------------------------------- | ------ | ---- | | angle | 目标旋转角度(弧度制) | number | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | | origin | 旋转中心点(视口坐标) | [Point](#point) | - | | **示例** ```typescript // 旋转到45度 graph.rotateTo(Math.PI / 4); // 带动画效果的旋转到90度 graph.rotateTo(Math.PI / 2, { duration: 1000, }); ``` ### Graph.rotateBy(angle, animation, origin) 基于当前角度进行旋转(相对旋转)。 ```typescript rotateBy(angle: number, animation?: ViewportAnimationEffectTiming, origin?: Point): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------- | --------------------------------------------------------------- | ------ | ---- | | angle | 旋转角度增量(弧度制) | number | - | ✓ | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | | origin | 旋转中心点(视口坐标) | [Point](#point) | - | | **示例** ```typescript // 相对当前角度顺时针旋转30度 graph.rotateBy(Math.PI / 6); // 带动画效果的相对旋转 graph.rotateBy(-Math.PI / 4, { duration: 500, easing: 'ease-out', }); ``` ### Graph.fitView(options, animation) 将图缩放至合适大小并平移至视口中心。 ```typescript fitView(options?: FitViewOptions, animation?: ViewportAnimationEffectTiming): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------- | --------------------------------------------------------------- | ------ | ---- | | options | 适配选项 | FitViewOptions | - | | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | **FitViewOptions 类型说明** | 属性 | 类型 | 默认值 | 描述 | | --------- | ---------------------- | ---------- | ---------------------------- | | when | 'overflow' \| 'always' | 'overflow' | 适配时机:仅溢出时或始终适配 | | direction | 'x' \| 'y' \| 'both' | 'both' | 适配方向:x轴、y轴或两个方向 | **示例** ```typescript // 基本使用 graph.fitView(); // 配置适配选项 graph.fitView( { when: 'always', // 始终进行适配 direction: 'both', // 在两个方向上适配 }, { duration: 1000, // 带动画效果 }, ); // 仅在内容溢出时适配x方向 graph.fitView({ when: 'overflow', direction: 'x', }); ``` ### Graph.fitCenter(animation) 将图平移至视口中心。 ```typescript fitCenter(animation?: ViewportAnimationEffectTiming): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------- | --------------------------------------------------------------- | ------ | ---- | | animation | 动画配置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | - | | **示例** ```typescript // 居中显示 graph.fitCenter(); // 带动画效果的居中 graph.fitCenter({ duration: 500, easing: 'ease-in', }); ``` ### Graph.getZoom() 获取当前缩放比例。 ```typescript getZoom(): number; ``` **示例** ```typescript const currentZoom = graph.getZoom(); console.log('当前缩放比例:', currentZoom); ``` ### Graph.getPosition() 获取图的位置(画布原点在视口坐标系下的位置)。 ```typescript getPosition(): Point; ``` **示例** ```typescript const position = graph.getPosition(); console.log('当前位置:', position); ``` ### Graph.getRotation() 获取当前旋转角度。 ```typescript getRotation(): number; ``` **示例** ```typescript const rotation = graph.getRotation(); console.log('当前旋转角度(弧度):', rotation); console.log('当前旋转角度(度):', (rotation * 180) / Math.PI); ``` ### Graph.getCanvasCenter() 获取视口中心的视口坐标。 ```typescript getCanvasCenter(): Point; ``` **示例** ```typescript const center = graph.getCanvasCenter(); console.log('视口中心坐标:', center); ``` ### Graph.getViewportCenter() 获取视口中心的画布坐标。 ```typescript getViewportCenter(): Point; ``` **示例** ```typescript const viewportCenter = graph.getViewportCenter(); console.log('视口中心的画布坐标:', viewportCenter); ``` ### Graph.setZoomRange(zoomRange) 设置当前图的缩放区间。 ```typescript setZoomRange(zoomRange: [number, number]): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------- | ----------------------------- | ------ | ---- | | zoomRange | 缩放区间 | [number, number] \| undefined | - | ✓ | **示例** ```typescript // 限制缩放范围在0.5到2倍之间 graph.setZoomRange([0.5, 2]); // 移除缩放限制 graph.setZoomRange(undefined); ``` ### Graph.getZoomRange() 获取当前图的缩放区间。 ```typescript getZoomRange(): GraphOptions['zoomRange']; ``` **示例** ```typescript const range = graph.getZoomRange(); console.log('当前缩放区间:', range); ``` ### Graph.resize() 调整画布大小为图容器大小。 ```typescript resize(): void; ``` ### Graph.resize(width, height) 调整画布大小为指定宽高。 ```typescript resize(width: number, height: number): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------- | ------ | ------ | ---- | | width | 目标宽度 | number | - | ✓ | | height | 目标高度 | number | - | ✓ | **示例** ```typescript // 设置画布大小为800x600 graph.resize(800, 600); ``` ## 类型定义 ### ViewportAnimationEffectTiming 视口动画配置类型。 ```typescript type ViewportAnimationEffectTiming = | boolean // 是否启用动画 | { easing?: string; // 缓动函数 duration?: number; // 动画持续时间(ms) }; ``` ### Point 坐标点类型。 ```typescript type Point = [number, number] | [number, number, number] | Float32Array; ``` ### FitViewOptions 视图适配选项。 ```typescript interface FitViewOptions { when?: 'overflow' | 'always'; // 适配时机 direction?: 'x' | 'y' | 'both'; // 适配方向 } ``` #### 布局 - Canonical page: https://g6.antv.antgroup.com/zh/api/layout/ - Markdown source: https://g6.antv.antgroup.com/zh/api/layout.md - Description: 布局 --- title: "布局" description: "布局" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/layout/" version: "5.1.1" --- ## 布局概述 [布局](/zh/manual/layout/overview/) 是图可视化中至关重要的一环,它决定了节点在画布上的位置排布。G6 提供了多种布局算法,以满足不同数据结构和可视化需求。通过布局 API,你可以: - 设置和更新图的布局配置 - 执行或停止布局计算 - 组合多种布局策略 - 自定义布局算法 合适的布局可以清晰地展示节点间的关系模式,提高图的可读性和美观度。 ## API 参考 ### Graph.setLayout(layout) 设置图的布局算法及配置。 ⚠️ **注意**: 调用此函数不会自动重新布局,需要单独调用 `graph.layout()`。 ```typescript setLayout(layout: LayoutOptions | ((prev: LayoutOptions) => LayoutOptions)): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------------------------------------------------- | --------------------------------------------------------------------------- | ------ | ---- | | layout | 布局配置对象,或者一个基于之前配置返回新配置的函数 | [LayoutOptions](#layoutoptions) \| ((prev: LayoutOptions) => LayoutOptions) | - | ✓ | **示例 1**: 设置力导向布局 ```typescript // 设置简单的力导向布局 graph.setLayout({ type: 'force', preventOverlap: true, // 防止节点重叠 nodeStrength: -50, // 节点间斥力,负值为斥力 edgeStrength: 0.5, // 边的强度,会影响边的长度 }); ``` **示例 2**: 使用函数式更新布局 ```typescript // 基于当前布局配置进行更新 graph.setLayout((prevLayout) => { // 如果之前是力导向布局,调整其参数 if (prevLayout.type === 'force') { return { ...prevLayout, preventOverlap: true, nodeStrength: -100, // 增加斥力 alphaDecay: 0.01, // 降低衰减率,让布局有更多迭代时间 }; } // 否则切换到放射状布局 return { type: 'radial', unitRadius: 100, preventOverlap: true, }; }); ``` **示例 3**: 设置组合布局 ```typescript // 设置组合布局 - 不同的节点使用不同的布局算法 graph.setLayout([ { type: 'grid', // 过滤函数:只有type为'main'的节点参与布局 nodeFilter: (node) => node.data.type === 'main', rows: 1, }, { type: 'circle', nodeFilter: (node) => node.data.type === 'sub', radius: 100, }, ]); ``` ### Graph.getLayout() 获取当前的布局配置。 ```typescript getLayout(): LayoutOptions; ``` **返回值** - **类型**: [LayoutOptions](#layoutoptions) - **描述**: 当前的布局配置对象 **示例** ```typescript // 获取当前布局配置 const currentLayout = graph.getLayout(); console.log('当前布局类型:', currentLayout.type); ``` ### Graph.layout(layoutOptions) 执行布局计算。当图数据发生变化后,调用此方法可触发布局算法重新计算节点位置。 ```typescript layout(layoutOptions?: LayoutOptions): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------------- | ------------ | --------------------------------------------------------------------------- | ------ | ---- | | layoutOptions | 布局配置对象 | [LayoutOptions](#layoutoptions) \| ((prev: LayoutOptions) => LayoutOptions) | - | | 如果传入 `layoutOptions`,则优先考虑传入的布局配置,否则使用图的当前布局配置进行布局。 **说明** 布局计算是一个异步过程,特别是对于复杂的布局算法(如力导向布局)。此方法返回一个 Promise,可以用于在布局完成后执行后续操作。 **示例 1**: 基础用法 ```typescript // 执行布局 await graph.layout(); console.log('布局计算完成'); ``` **示例 2**: 添加数据后重新布局 ```typescript // 添加新节点和边 graph.addData({ nodes: [{ id: 'newNode1' }, { id: 'newNode2' }], edges: [{ id: 'newEdge', source: 'existingNode', target: 'newNode1' }], }); // 绘制新节点和边 await graph.draw(); // 重新计算布局 await graph.layout(); ``` **示例 3**: 监听布局事件 ```typescript import { GraphEvent } from '@antv/g6'; // 布局开始前 graph.on(GraphEvent.BEFORE_LAYOUT, () => { console.log('布局计算开始...'); }); // 布局完成后 graph.on(GraphEvent.AFTER_LAYOUT, () => { console.log('布局计算完成'); }); // 执行布局 graph.layout(); ``` ### Graph.stopLayout() 停止正在进行中的布局计算。主要用于停止迭代类型的布局算法,如力导向布局。 ```typescript stopLayout(): void; ``` **说明** 适用于带有迭代动画的布局,目前有 `force` 属于此类布局。当布局计算时间过长时,可以手动停止迭代。 **示例 1**: 基本使用 ```typescript // 5秒后停止布局 setTimeout(() => { graph.stopLayout(); console.log('布局已手动停止'); }, 5000); ``` **示例 2**: 结合用户交互停止布局 ```typescript // 当用户点击画布时停止布局 import { CanvasEvent } from '@antv/g6'; graph.on(CanvasEvent.CLICK, () => { graph.stopLayout(); console.log('用户点击画布,布局已停止'); }); ``` ## 类型定义 ### LayoutOptions 布局配置类型,可以是单一布局配置或布局配置数组。 ```typescript type LayoutOptions = SingleLayoutOptions | SingleLayoutOptions[]; ``` ### SingleLayoutOptions 单一布局配置,可以是内置布局配置或自定义基础布局配置。 ```typescript type SingleLayoutOptions = BuiltInLayoutOptions | BaseLayoutOptions; ``` ### BaseLayoutOptions 所有布局类型共有的基础配置项。 ```typescript interface BaseLayoutOptions { // 布局类型 type: string; // 参与该布局的节点过滤函数 nodeFilter?: (node: NodeData) => boolean; // 是否在初始化元素前计算布局 preLayout?: boolean; // 不可见节点是否参与布局(当 preLayout 为 true 时生效) isLayoutInvisibleNodes?: boolean; // 启用布局动画,对于迭代布局,会在两次迭代之间进行动画过渡 animation?: boolean; // 是否在 WebWorker 中运行布局 enableWorker?: boolean; // 迭代布局的迭代次数 iterations?: number; // 其他特定布局的配置项 [key: string]: any; } ``` ### BuiltInLayoutOptions G6 内置的布局类型配置,具体请查看 [API - 内置布局](/zh/manual/layout/AntvDagreLayout/)。 #### 图配置项 - Canonical page: https://g6.antv.antgroup.com/zh/api/option/ - Markdown source: https://g6.antv.antgroup.com/zh/api/option.md - Description: 图配置项 --- title: "图配置项" description: "图配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/option/" version: "5.1.1" --- ## 图配置项概述 G6 图实例的 [配置项](/zh/manual/graph/option/) 控制着图的各个方面,包括画布设置、视口属性、数据、布局、样式、交互行为、插件等。通过合理配置这些选项,可以灵活定制图的外观和行为。 配置项可以在图实例创建时指定,也可以通过 API 在运行时动态修改。某些基础配置(如 devicePixelRatio、container)修改后需要销毁并重新创建图实例才能生效。 ## API 参考 ### Graph.getOptions() 获取当前图表的所有配置项。 ```typescript getOptions(): GraphOptions; ``` **返回值** - **类型**: [GraphOptions](/zh/manual/graph/option/) - **描述**: 当前图表的完整配置项 **示例** ```typescript // 获取当前图表的配置项 const options = graph.getOptions(); console.log('当前图表配置:', options); // 获取特定配置 console.log('当前画布宽度:', options.width); console.log('当前布局配置:', options.layout); ``` ### Graph.setOptions(options) 更新图表的配置项。 ```typescript setOptions(options: GraphOptions): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------- | ---------- | ------------------------------------ | ------ | ---- | | options | 新的配置项 | [GraphOptions](/zh/manual/graph/option/) | - | ✓ | **说明** ⚠️ **注意**: 要更新 devicePixelRatio、container 等基础属性,需要销毁当前图实例后重新创建。其他大部分配置可以动态更新。 **示例 1**: 基本用法 ```typescript // 更新图表配置 graph.setOptions({ width: 1000, // 更新宽度 height: 800, // 更新高度 autoFit: 'view', // 开启自适应 animation: true, // 启用动画 }); ``` **示例 2**: 更新主题 ```typescript // 更新图表主题配置 graph.setOptions({ theme: { type: 'dark', // 切换到暗色主题 // 自定义主题配置 node: { palette: ['#1AAF8B', '#F8E71C', '#8B572A', '#7ED321'], }, edge: { palette: ['#F5A623', '#F8E71C', '#8B572A', '#7ED321'], }, }, }); ``` **示例 3**: 更新布局配置 ```typescript // 更新布局配置 graph.setOptions({ layout: { type: 'force', // 切换到力导向布局 preventOverlap: true, nodeStrength: -50, edgeStrength: 0.7, }, }); ``` **示例 4**: 更新节点和边的默认配置 ```typescript // 更新节点和边的默认样式配置 graph.setOptions({ node: { style: { fill: '#91d5ff', stroke: '#40a9ff', lineWidth: 1, radius: 10, }, }, edge: { style: { stroke: '#91d5ff', lineWidth: 2, endArrow: true, }, }, }); ``` #### 交互 - Canonical page: https://g6.antv.antgroup.com/zh/api/behavior/ - Markdown source: https://g6.antv.antgroup.com/zh/api/behavior.md - Description: 交互 --- title: "交互" description: "交互" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/behavior/" version: "5.1.1" --- ## 交互概述 交互(Behavior)是 G6 的核心构建模块,它精确定义了用户与图之间的互动行为。每个 Behavior 插件都是一个高度封装的功能单元,内部集成了特定场景下的事件监听、状态管理和响应处理逻辑。 G6 的内置 Behavior 涵盖了大多数常见交互需求,同时提供了灵活的扩展机制,支持开发者根据业务场景构建定制化交互体验。 有关完整的交互行为类型、配置选项及开发示例,请参阅 [交互总览](/zh/manual/behavior/overview/) 章节。 ## API 参考 ### Graph.getBehaviors() 获取当前图表中所有已配置的交互行为。 ```typescript getBehaviors(): BehaviorOptions; ``` **返回值** - **类型**: [BehaviorOptions](#behavioroptions) - **描述**: 当前图表中已配置的所有交互行为 **示例** ```typescript // 获取当前所有交互行为 const behaviors = graph.getBehaviors(); console.log('当前图表的交互行为:', behaviors); ``` ### Graph.setBehaviors(behaviors) 设置图表的交互行为,将替换所有现有的交互行为。 ```typescript setBehaviors(behaviors: BehaviorOptions | ((prev: BehaviorOptions) => BehaviorOptions)): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------------------------------------------- | --------------------------------------------------------------------------------- | ------ | ---- | | behaviors | 新的交互行为配置,或一个基于当前配置返回新配置的函数 | [BehaviorOptions](#behavioroptions) \| (prev: BehaviorOptions) => BehaviorOptions | - | ✓ | **说明** 设置的交互会全量替换原有的交互,如果需要新增交互可以使用函数式更新: ```typescript graph.setBehaviors((behaviors) => [...behaviors, { type: 'zoom-canvas' }]); ``` **示例 1**: 设置基本交互 ```typescript // 设置基本交互 graph.setBehaviors([ 'drag-canvas', // 拖拽画布 'zoom-canvas', // 缩放画布 'drag-element', // 拖拽元素 ]); ``` **示例 2**: 设置带配置的交互 ```typescript graph.setBehaviors([ // 字符串形式(使用默认配置) 'drag-canvas', // 对象形式(自定义配置) { type: 'zoom-canvas', key: 'my-zoom', // 指定唯一标识,用于后续更新 sensitivity: 1.5, // 缩放灵敏度 }, // 只有节点上启用拖拽 { type: 'drag-element', key: 'drag-node-only', enable: (event) => event.targetType === 'node', // 仅在节点上启用拖拽 }, ]); ``` **示例 3**: 使用函数式更新 ```typescript // 添加新的交互行为 graph.setBehaviors((currentBehaviors) => [ ...currentBehaviors, { type: 'brush-select', key: 'selection-brush', }, ]); // 替换特定交互行为 graph.setBehaviors((currentBehaviors) => { // 过滤掉现有的缩放交互 const filteredBehaviors = currentBehaviors.filter((behavior) => { if (typeof behavior === 'string') return behavior !== 'zoom-canvas'; return behavior.type !== 'zoom-canvas'; }); // 添加新的缩放交互配置 return [ ...filteredBehaviors, { type: 'zoom-canvas', key: 'new-zoom', enableOptimize: true, }, ]; }); ``` ### Graph.updateBehavior(behavior) 更新指定的交互行为配置,需要通过 `key` 标识要更新的交互。 ```typescript updateBehavior(behavior: UpdateBehaviorOption): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | -------- | ------------------ | --------------------------------------------- | ------ | ---- | | behavior | 更新的交互行为配置 | [UpdateBehaviorOption](#updatebehavioroption) | - | ✓ | **说明** 如果要更新一个交互,必须在原始交互配置中指定 `key` 字段,以便能够准确找到并更新该交互。 **示例 1**: 更新交互配置 ```typescript // 初始设置交互时指定 key graph.setBehaviors([ { type: 'zoom-canvas', key: 'my-zoom-canvas', sensitivity: 1.0, }, ]); // 更新交互配置 graph.updateBehavior({ key: 'my-zoom-canvas', // 指定要更新的交互 sensitivity: 2.0, // 新的缩放灵敏度 enableOptimize: true, // 添加新配置 }); ``` **示例 2**: 禁用/启用交互 ```typescript // 设置带 key 的行为 graph.setBehaviors([ { type: 'drag-canvas', key: 'main-drag', }, { type: 'zoom-canvas', key: 'main-zoom', }, ]); // 禁用拖拽功能 graph.updateBehavior({ key: 'main-drag', enable: false, }); // 稍后重新启用 setTimeout(() => { graph.updateBehavior({ key: 'main-drag', enable: true, }); }, 5000); ``` ## 类型定义 ### BehaviorOptions ```typescript type BehaviorOptions = (string | CustomBehaviorOption | ((this: Graph) => CustomBehaviorOption))[]; type CustomBehaviorOption = { // 交互类型 type: string; // 交互 key,即唯一标识,用于标识交互,从而进一步操作此交互 key?: string; // 针对不同类型的交互,还可能有其他配置项 [configKey: string]: any; }; ``` ### UpdateBehaviorOption ```typescript type UpdateBehaviorOption = { // 要更新的交互的唯一标识 key: string; // 其他要更新的配置项 [configKey: string]: unknown; }; ``` #### 插件 - Canonical page: https://g6.antv.antgroup.com/zh/api/plugin/ - Markdown source: https://g6.antv.antgroup.com/zh/api/plugin.md - Description: 插件 --- title: "插件" description: "插件" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/plugin/" version: "5.1.1" --- ## 插件概述 [插件](/zh/manual/plugin/overview/)(Plugin)是 G6 中扩展功能的重要机制,用于增强图表的功能和交互体验。插件通常提供一些独立的功能模块,如缩略图、工具栏、上下文菜单等,它们可以与图表主体良好集成,同时又保持代码的模块化和可维护性。 插件系统设计遵循"即插即用"的原则,可以根据需要动态添加或移除。 ## API 参考 ### Graph.getPluginInstance(key) 获取指定 key 的插件实例,用于访问和操作插件提供的方法。 ```typescript getPluginInstance(key: string): T; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---- | ---------------- | ------ | ------ | ---- | | key | 插件的唯一标识符 | string | - | ✓ | **返回值** - **类型**: 插件实例 - **描述**: 指定 key 对应的插件实例 **说明** 许多插件提供了特定的API方法,通过获取插件实例可以直接调用这些方法。例如,全屏插件提供了 `request()` 和 `exit()` 方法来控制全屏状态。 **示例**: 操作全屏插件 ```typescript // 获取全屏插件实例 const fullscreen = graph.getPluginInstance('fullscreen'); // 请求进入全屏 fullscreen.request(); // 稍后退出全屏 setTimeout(() => { fullscreen.exit(); }, 5000); ``` ### Graph.getPlugins() 获取当前图表中所有已配置的插件。 ```typescript getPlugins(): PluginOptions; ``` **返回值** - **类型**: [PluginOptions](#pluginoptions) - **描述**: 当前图表中已配置的所有插件 **示例** ```typescript // 获取所有插件配置 const plugins = graph.getPlugins(); // 查看当前激活的插件 console.log('当前图表的插件配置:', plugins); ``` ### Graph.setPlugins(plugins) 设置图表的插件,将替换所有现有的插件配置。 ```typescript setPlugins(plugins: PluginOptions | ((prev: PluginOptions) => PluginOptions)): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------- | ------------------------------------------------ | --------------------------------------------------------------------------- | ------ | ---- | | plugins | 新的插件配置,或一个基于当前配置返回新配置的函数 | [PluginOptions](#pluginoptions) \| ((prev: PluginOptions) => PluginOptions) | - | ✓ | **说明** 设置的插件会全量替换原有的插件配置。如果需要在现有插件基础上添加新插件,可以使用函数式更新方式: ```typescript graph.setPlugins((plugins) => [...plugins, { type: 'grid', key: 'grid-line' }]); ``` **示例 1**: 设置基本插件 ```typescript // 设置多个基本插件 graph.setPlugins([ // 字符串形式(使用默认配置) 'minimap', // 对象形式(自定义配置) { type: 'grid', key: 'grid-line', }, { type: 'toolbar', key: 'graph-toolbar', position: 'top-right', }, ]); ``` **示例 2**: 使用函数式更新 ```typescript // 添加新插件到现有配置 graph.setPlugins((currentPlugins) => [ ...currentPlugins, { type: 'grid', key: 'grid-line', }, ]); // 替换特定插件 graph.setPlugins((currentPlugins) => { // 过滤掉现有的网格插件 const filteredPlugins = currentPlugins.filter((plugin) => { if (typeof plugin === 'string') return plugin !== 'grid'; if (typeof plugin === 'function') return true; return plugin.type !== 'grid'; }); // 添加新的网格插件配置 return [ ...filteredPlugins, { type: 'grid', key: 'new-grid', follow: true, }, ]; }); ``` ### Graph.updatePlugin(plugin) 更新指定的插件配置,需要通过 `key` 标识要更新的插件。 ```typescript updatePlugin(plugin: UpdatePluginOption): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------------- | ----------------------------------------- | ------ | ---- | | plugin | 更新的插件配置 | [UpdatePluginOption](#updatepluginoption) | - | ✓ | **说明** 如果要更新一个插件,必须在原始插件配置中指定 `key` 字段,以便能够准确找到并更新该插件。 **示例 1**: 更新插件配置 ```typescript // 初始设置插件时指定 key graph.setPlugins([ { type: 'grid', key: 'main-grid', follow: true, }, ]); // 更新网格插件配置 graph.updatePlugin({ key: 'main-grid', follow: false, }); ``` ## 类型定义 ### PluginOptions 插件配置类型,表示一组插件配置的数组。 ```typescript type PluginOptions = (string | CustomPluginOption | ((this: Graph) => CustomPluginOption))[]; ``` ### CustomPluginOption 自定义插件配置接口,用于配置插件参数。 ```typescript type CustomPluginOption = { // 插件类型 type: string; // 插件 key,即唯一标识 // 用于标识插件,从而进一步操作此插件 key?: string; // 针对不同类型的插件,还可能有其他配置项 [configKey: string]: any; }; ``` ### UpdatePluginOption 更新插件的配置接口,用于动态修改插件参数。 ```typescript type UpdatePluginOption = { // 要更新的插件的唯一标识 key: string; // 其他要更新的配置项 [configKey: string]: unknown; }; ``` #### 主题 - Canonical page: https://g6.antv.antgroup.com/zh/api/theme/ - Markdown source: https://g6.antv.antgroup.com/zh/api/theme.md - Description: 主题 --- title: "主题" description: "主题" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/theme/" version: "5.1.1" --- ## API 参考 ### Graph.getTheme() 获取主题 ```typescript getTheme(): ThemeOptions; ```
相关参数 **返回值**: - **类型:** false \| 'light' \| 'dark' \| string - **描述:** 当前主题
### Graph.setTheme(theme) 设置主题 ```typescript setTheme(theme: ThemeOptions | ((prev: ThemeOptions) => ThemeOptions)): void; ``` **示例** ```ts graph.setTheme('dark'); ```
相关参数
参数 类型 描述
theme false \| 'light' \| 'dark' \| string \| ((prev: false \| 'light' \| 'dark' \| string) => false \| 'light' \| 'dark' \| string) 主题名
**返回值**: - **类型:** void
#### 数据处理 - Canonical page: https://g6.antv.antgroup.com/zh/api/transform/ - Markdown source: https://g6.antv.antgroup.com/zh/api/transform.md - Description: 数据处理 --- title: "数据处理" description: "数据处理" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/transform/" version: "5.1.1" --- ## 数据处理概述 [数据处理](/zh/manual/transform/overview/)(Transform)是 G6 中一项强大的功能,允许在图渲染过程中对数据进行处理和转换。通过数据处理器,您可以实现各种数据处理需求,比如: - 数据过滤:根据条件筛选需要显示的节点和边 - 数据计算:基于原始数据生成新的属性,如根据节点连接数计算节点大小,但不污染原始数据 - 数据聚合:将大量节点聚合为少量节点,提高大规模图表的性能 数据处理发生在渲染流程的特定阶段,可以灵活地改变最终呈现的结果,而无需修改原始数据源。 ## API 参考 ### Graph.getTransforms() 获取当前图表中所有已配置的数据处理器。 ```typescript getTransforms(): TransformOptions; ``` **返回值** - **类型**: [TransformOptions](#transformoptions) - **描述**: 当前图表中已配置的所有数据处理器 **示例** ```typescript // 获取当前所有数据处理器 const transforms = graph.getTransforms(); console.log('当前图表的数据处理器:', transforms); ``` ### Graph.setTransforms(transforms) 设置图表的数据处理器,将替换所有现有的数据处理器。 ```typescript setTransforms(transforms: TransformOptions | ((prev: TransformOptions) => TransformOptions)): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ---------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------- | ------ | ---- | | transforms | 新的数据处理器配置,或一个基于当前配置返回新配置的函数 | [TransformOptions](#transformoptions) \| (prev: TransformOptions) => TransformOptions | - | ✓ | **说明** 数据处理器能够在图渲染过程的不同阶段对数据进行处理。设置的数据处理会全量替换原有的数据处理,如果需要在现有数据处理基础上添加新的数据处理,可以使用函数式更新方式。 **示例 1**: 设置基本数据处理 ```typescript graph.setTransforms(['process-parallel-edges', 'map-node-size']); ``` **示例 2**: 设置带配置的数据处理 ```typescript graph.setTransforms([ // 字符串形式(使用默认配置) 'process-parallel-edges', // 对象形式(自定义配置) { type: 'process-parallel-edges', key: 'my-process-parallel-edges', distance: 20, // 平行边之间的距离 }, ]); ``` **示例 3**: 使用函数式更新 ```typescript // 添加新的数据处理到现有配置 graph.setTransforms((currentTransforms) => [ ...currentTransforms, { type: 'map-node-size', key: 'my-map-node-size', maxSize: 100, minSize: 20, }, ]); ``` ### Graph.updateTransform(transform) 更新指定的数据处理器配置,需要通过 `key` 标识要更新的数据处理。 ```typescript updateTransform(transform: UpdateTransformOption): void; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------ | ----------------------------------------------- | ------ | ---- | | transform | 更新的数据处理配置 | [UpdateTransformOption](#updatetransformoption) | - | ✓ | **说明** 如果要更新一个数据处理器,必须在原始数据处理配置中指定 `key` 字段,以便能够准确找到并更新该数据处理。 **示例**: 更新数据处理配置 ```typescript // 初始设置数据处理时指定 key graph.setTransforms([ { type: 'process-parallel-edges', key: 'my-process-parallel-edges', distance: 20, }, ]); // 更新平行边距离 graph.updateTransform({ key: 'my-process-parallel-edges', distance: 30, }); ``` ## 类型定义 ### TransformOptions 数据处理器配置类型,表示一组数据处理配置的数组。 ```typescript type TransformOptions = (CustomTransformOption | ((this: Graph) => CustomTransformOption))[]; ``` ### CustomTransformOption 自定义数据处理配置接口,用于配置数据处理参数。 ```typescript type CustomTransformOption = { // 数据处理类型 type: string; // 数据处理唯一标识 key?: string; // 针对不同类型的数据处理,还可能有其他配置项 [configKey: string]: any; }; ``` ### UpdateTransformOption 更新数据处理的配置接口,用于动态修改数据处理参数。 ```typescript type UpdateTransformOption = { // 要更新的数据处理的唯一标识 key: string; // 其他要更新的配置项 [configKey: string]: unknown; }; ``` #### 事件监听 - Canonical page: https://g6.antv.antgroup.com/zh/api/event/ - Markdown source: https://g6.antv.antgroup.com/zh/api/event.md - Description: 事件监听 --- title: "事件监听" description: "事件监听" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/event/" version: "5.1.1" --- ## 事件系统概述 G6 提供了强大的事件机制,允许你响应图表中发生的各种交互行为。例如节点点击、边悬停、画布拖拽等。通过事件系统,你可以实现复杂的交互逻辑,提升用户体验。 ### 事件分类 G6 中的事件大致可分为以下几类: 1. **元素事件**:与节点、边、Combo 相关的事件,如 `node:click`, `edge:mouseenter` 2. **画布事件**:与整个画布相关的事件,如 `canvas:drag`, `canvas:wheel` 3. **生命周期事件**:与图表生命周期相关的事件,如 `beforerender`, `afterrender` ### 事件命名规则 G6 的事件命名遵循 `[对象]:[事件]` 的格式,例如: - `node:click` - 节点点击事件 - `edge:mouseenter` - 鼠标进入边的事件 - `canvas:drag` - 画布拖拽事件 ## 最佳实践:使用常量枚举 G6 提供了完整的事件常量枚举,**强烈建议**使用这些常量而非直接使用字符串事件名: ```typescript import { NodeEvent, EdgeEvent, CanvasEvent, GraphEvent } from '@antv/g6'; // 使用常量枚举监听事件 graph.on(NodeEvent.CLICK, handleNodeClick); graph.on(EdgeEvent.POINTER_OVER, handleEdgeHover); graph.on(CanvasEvent.DRAG, handleCanvasDrag); graph.on(GraphEvent.AFTER_RENDER, handleAfterRender); ``` **优势**: - 类型安全,避免字符串拼写错误 - 提供智能代码提示和自动完成 ## API 参考 ### Graph.on(eventName, callback, once) 监听指定的事件,当事件触发时执行回调函数。 ```typescript on(eventName: string, callback: (event: T) => void, once?: boolean): this; ``` #### 参数 | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------------ | ------------------ | ------ | ---- | | eventName | 要监听的事件名称 | string | - | ✓ | | callback | 事件触发时执行的回调函数 | (event: T) => void | - | ✓ | | once | 是否只监听一次 | boolean | - | | #### 返回值 - **类型:** this(Graph 实例) - **描述:** 返回图实例本身,支持链式调用 #### 示例 ```typescript import { NodeEvent, EdgeEvent, CanvasEvent } from '@antv/g6'; // 监听节点点击事件 graph.on(NodeEvent.CLICK, (evt) => { const { target } = evt; // 获取被点击节点的 ID console.log(`节点 ${target.id} 被点击了`); // 获取节点数据 const nodeData = graph.getNodeData(target.id); console.log('节点数据:', nodeData); // 修改节点状态 graph.setElementState(target.id, 'selected'); }); // 监听边的鼠标进入事件 graph.on(EdgeEvent.POINTER_OVER, (evt) => { const { target } = evt; graph.setElementState(target.id, 'highlight'); }); // 监听画布拖拽事件 graph.on(CanvasEvent.DRAG, (evt) => { console.log('画布正在被拖拽'); }); ``` ### Graph.once(eventName, callback) 一次性监听事件,事件触发一次后自动移除监听器。 ```typescript once(eventName: string, callback: (event: T) => void): this; ``` #### 参数 | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------------ | ------------------ | ------ | ---- | | eventName | 要监听的事件名称 | string | - | ✓ | | callback | 事件触发时执行的回调函数 | (event: T) => void | - | ✓ | #### 返回值 - **类型:** this(Graph 实例) - **描述:** 返回图实例本身,支持链式调用 #### 示例 ```typescript import { GraphEvent, NodeEvent } from '@antv/g6'; // 监听图表首次加载完成事件,仅执行一次 graph.once(GraphEvent.AFTER_RENDER, () => { console.log('图表首次渲染完成'); // 执行一次性的初始化操作 highlightImportantNodes(); }); // 等待用户第一次点击某个节点后执行操作 graph.once(NodeEvent.CLICK, (evt) => { console.log('用户首次点击了节点:', evt.target.id); showTutorialTip('您可以拖拽节点改变位置'); }); ``` ### Graph.off() 移除全部事件监听器。 ```typescript off(): this; ``` #### 返回值 - **类型:** this(Graph 实例) - **描述:** 返回图实例本身,支持链式调用 #### 示例 ```typescript // 移除所有事件监听器 graph.off(); console.log('已移除所有事件监听器'); ``` ### Graph.off(eventName) 移除指定事件类型的所有监听器。 ```typescript off(eventName: string): this; ``` #### 参数 | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------- | ------ | ------ | ---- | | eventName | 要移除的事件名称 | string | - | ✓ | #### 返回值 - **类型:** this(Graph 实例) - **描述:** 返回图实例本身,支持链式调用 #### 示例 ```typescript import { NodeEvent } from '@antv/g6'; // 移除所有节点点击事件的监听器 graph.off(NodeEvent.CLICK); console.log('已移除所有节点点击事件监听器'); // 在某个操作模式结束后,移除相关的临时事件监听 function exitEditMode() { // 移除编辑模式下的所有监听器 graph.off(NodeEvent.DRAG_END); graph.off(NodeEvent.DROP); console.log('已退出编辑模式'); } ``` ### Graph.off(eventName, callback) 移除特定事件的特定回调函数。 ```typescript off(eventName: string, callback: (...args: any[]) => void): this; ``` #### 参数 | 参数 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------- | ------------------------ | ------ | ---- | | eventName | 要移除的事件名称 | string | - | ✓ | | callback | 要移除的回调函数 | (...args: any[]) => void | - | ✓ | #### 返回值 - **类型:** this(Graph 实例) - **描述:** 返回图实例本身,支持链式调用 #### 示例 ```typescript import { NodeEvent } from '@antv/g6'; // 定义回调函数 const handleNodeClick = (evt) => { console.log('节点被点击:', evt.target.id); }; // 添加监听器 graph.on(NodeEvent.CLICK, handleNodeClick); // 之后在某个时机移除这个特定的监听器 graph.off(NodeEvent.CLICK, handleNodeClick); console.log('已移除特定的节点点击事件监听器'); ``` ## 事件常量枚举 G6 提供了多种事件常量枚举,便于开发者使用规范的事件名称。以下是所有事件常量的详细说明: ### 节点事件 (NodeEvent) | 常量名 | 事件名 | 描述 | | ------------- | ------------------- | ------------------------------------ | | CLICK | `node:click` | 点击节点时触发 | | DBLCLICK | `node:dblclick` | 双击节点时触发 | | POINTER_OVER | `node:pointerover` | 指针移入节点时触发 | | POINTER_LEAVE | `node:pointerleave` | 指针离开节点时触发 | | POINTER_ENTER | `node:pointerenter` | 指针进入节点或其子元素时触发(不冒泡) | | POINTER_MOVE | `node:pointermove` | 指针在节点上移动时触发 | | POINTER_OUT | `node:pointerout` | 指针离开节点时触发 | | POINTER_DOWN | `node:pointerdown` | 指针在节点上按下时触发 | | POINTER_UP | `node:pointerup` | 指针在节点上抬起时触发 | | CONTEXT_MENU | `node:contextmenu` | 节点上打开上下文菜单时触发 | | DRAG_START | `node:dragstart` | 开始拖拽节点时触发 | | DRAG | `node:drag` | 拖拽节点过程中触发 | | DRAG_END | `node:dragend` | 拖拽节点结束时触发 | | DRAG_ENTER | `node:dragenter` | 拖拽物进入节点时触发 | | DRAG_OVER | `node:dragover` | 拖拽物在节点上方时触发 | | DRAG_LEAVE | `node:dragleave` | 拖拽物离开节点时触发 | | DROP | `node:drop` | 在节点上放置拖拽物时触发 | ### 边事件 (EdgeEvent) | 常量名 | 事件名 | 描述 | | ------------- | ------------------- | ---------------------------------- | | CLICK | `edge:click` | 点击边时触发 | | DBLCLICK | `edge:dblclick` | 双击边时触发 | | POINTER_OVER | `edge:pointerover` | 指针移入边时触发 | | POINTER_LEAVE | `edge:pointerleave` | 指针离开边时触发 | | POINTER_ENTER | `edge:pointerenter` | 指针进入边或其子元素时触发(不冒泡) | | POINTER_MOVE | `edge:pointermove` | 指针在边上移动时触发 | | POINTER_OUT | `edge:pointerout` | 指针离开边时触发 | | POINTER_DOWN | `edge:pointerdown` | 指针在边上按下时触发 | | POINTER_UP | `edge:pointerup` | 指针在边上抬起时触发 | | CONTEXT_MENU | `edge:contextmenu` | 边上打开上下文菜单时触发 | | DRAG_ENTER | `edge:dragenter` | 拖拽物进入边时触发 | | DRAG_OVER | `edge:dragover` | 拖拽物在边上方时触发 | | DRAG_LEAVE | `edge:dragleave` | 拖拽物离开边时触发 | | DROP | `edge:drop` | 在边上放置拖拽物时触发 | ### Combo事件 (ComboEvent) | 常量名 | 事件名 | 描述 | | ------------- | -------------------- | ------------------------------------- | | CLICK | `combo:click` | 点击Combo时触发 | | DBLCLICK | `combo:dblclick` | 双击Combo时触发 | | POINTER_OVER | `combo:pointerover` | 指针移入Combo时触发 | | POINTER_LEAVE | `combo:pointerleave` | 指针离开Combo时触发 | | POINTER_ENTER | `combo:pointerenter` | 指针进入Combo或其子元素时触发(不冒泡) | | POINTER_MOVE | `combo:pointermove` | 指针在Combo上移动时触发 | | POINTER_OUT | `combo:pointerout` | 指针离开Combo时触发 | | POINTER_DOWN | `combo:pointerdown` | 指针在Combo上按下时触发 | | POINTER_UP | `combo:pointerup` | 指针在Combo上抬起时触发 | | CONTEXT_MENU | `combo:contextmenu` | Combo上打开上下文菜单时触发 | | DRAG_START | `combo:dragstart` | 开始拖拽Combo时触发 | | DRAG | `combo:drag` | 拖拽Combo过程中触发 | | DRAG_END | `combo:dragend` | 拖拽Combo结束时触发 | | DRAG_ENTER | `combo:dragenter` | 拖拽物进入Combo时触发 | | DRAG_OVER | `combo:dragover` | 拖拽物在Combo上方时触发 | | DRAG_LEAVE | `combo:dragleave` | 拖拽物离开Combo时触发 | | DROP | `combo:drop` | 在Combo上放置拖拽物时触发 | ### 画布事件 (CanvasEvent) | 常量名 | 事件名 | 描述 | | ------------- | --------------------- | ------------------------------------ | | CLICK | `canvas:click` | 点击画布空白处时触发 | | DBLCLICK | `canvas:dblclick` | 双击画布空白处时触发 | | POINTER_OVER | `canvas:pointerover` | 指针移入画布时触发 | | POINTER_LEAVE | `canvas:pointerleave` | 指针离开画布时触发 | | POINTER_ENTER | `canvas:pointerenter` | 指针进入画布或其子元素时触发(不冒泡) | | POINTER_MOVE | `canvas:pointermove` | 指针在画布上移动时触发 | | POINTER_OUT | `canvas:pointerout` | 指针离开画布时触发 | | POINTER_DOWN | `canvas:pointerdown` | 指针在画布上按下时触发 | | POINTER_UP | `canvas:pointerup` | 指针在画布上抬起时触发 | | CONTEXT_MENU | `canvas:contextmenu` | 画布上打开上下文菜单时触发 | | DRAG_START | `canvas:dragstart` | 开始拖拽画布时触发 | | DRAG | `canvas:drag` | 拖拽画布过程中触发 | | DRAG_END | `canvas:dragend` | 拖拽画布结束时触发 | | DRAG_ENTER | `canvas:dragenter` | 拖拽物进入画布时触发 | | DRAG_OVER | `canvas:dragover` | 拖拽物在画布上方时触发 | | DRAG_LEAVE | `canvas:dragleave` | 拖拽物离开画布时触发 | | DROP | `canvas:drop` | 在画布上放置拖拽物时触发 | | WHEEL | `canvas:wheel` | 在画布上滚动鼠标滚轮时触发 | ### 图表生命周期事件 (GraphEvent) | 常量名 | 事件名 | 描述 | | ------------------------ | ------------------------ | ---------------------------------- | | BEFORE_CANVAS_INIT | `beforecanvasinit` | 画布初始化之前触发 | | AFTER_CANVAS_INIT | `aftercanvasinit` | 画布初始化之后触发 | | BEFORE_SIZE_CHANGE | `beforesizechange` | 视口尺寸变更之前触发 | | AFTER_SIZE_CHANGE | `aftersizechange` | 视口尺寸变更之后触发 | | BEFORE_ELEMENT_CREATE | `beforeelementcreate` | 元素创建之前触发 | | AFTER_ELEMENT_CREATE | `afterelementcreate` | 元素创建之后触发 | | BEFORE_ELEMENT_UPDATE | `beforeelementupdate` | 元素更新之前触发 | | AFTER_ELEMENT_UPDATE | `afterelementupdate` | 元素更新之后触发 | | BEFORE_ELEMENT_DESTROY | `beforeelementdestroy` | 元素销毁之前触发 | | AFTER_ELEMENT_DESTROY | `afterelementdestroy` | 元素销毁之后触发 | | BEFORE_ELEMENT_TRANSLATE | `beforeelementtranslate` | 元素平移之前触发 | | AFTER_ELEMENT_TRANSLATE | `afterelementtranslate` | 元素平移之后触发 | | BEFORE_DRAW | `beforedraw` | 绘制开始之前触发 | | AFTER_DRAW | `afterdraw` | 绘制结束之后触发 | | BEFORE_RENDER | `beforerender` | 渲染开始之前触发 | | AFTER_RENDER | `afterrender` | 渲染完成之后触发 | | BEFORE_ANIMATE | `beforeanimate` | 动画开始之前触发 | | AFTER_ANIMATE | `afteranimate` | 动画结束之后触发 | | BEFORE_LAYOUT | `beforelayout` | 布局开始之前触发 | | AFTER_LAYOUT | `afterlayout` | 布局结束之后触发 | | BEFORE_STAGE_LAYOUT | `beforestagelayout` | 流水线布局过程中每个阶段开始前触发 | | AFTER_STAGE_LAYOUT | `afterstagelayout` | 流水线布局过程中每个阶段结束后触发 | | BEFORE_TRANSFORM | `beforetransform` | 可视区域变化之前触发 | | AFTER_TRANSFORM | `aftertransform` | 可视区域变化之后触发 | | BATCH_START | `batchstart` | 批处理操作开始时触发 | | BATCH_END | `batchend` | 批处理操作结束时触发 | | BEFORE_DESTROY | `beforedestroy` | 图表销毁前触发 | | AFTER_DESTROY | `afterdestroy` | 图表销毁后触发 | | BEFORE_RENDERER_CHANGE | `beforerendererchange` | 渲染器变更之前触发 | | AFTER_RENDERER_CHANGE | `afterrendererchange` | 渲染器变更之后触发 | ### 容器事件 (ContainerEvent) | 常量名 | 事件名 | 描述 | | -------- | --------- | ------------------ | | KEY_DOWN | `keydown` | 键盘按键按下时触发 | | KEY_UP | `keyup` | 键盘按键抬起时触发 | ### 通用事件 (CommonEvent) 这些是不带前缀的事件,可用于监听全局事件: | 常量名 | 事件名 | 描述 | | ------------- | -------------- | ---------------------------------------- | | CLICK | `click` | 点击任何元素时触发 | | DBLCLICK | `dblclick` | 双击任何元素时触发 | | POINTER_OVER | `pointerover` | 指针移入任何元素时触发 | | POINTER_LEAVE | `pointerleave` | 指针离开任何元素时触发 | | POINTER_ENTER | `pointerenter` | 指针进入任何元素或其子元素时触发(不冒泡) | | POINTER_MOVE | `pointermove` | 指针在任何元素上移动时触发 | | POINTER_OUT | `pointerout` | 指针离开任何元素时触发 | | POINTER_DOWN | `pointerdown` | 指针在任何元素上按下时触发 | | POINTER_UP | `pointerup` | 指针在任何元素上抬起时触发 | | CONTEXT_MENU | `contextmenu` | 任何元素上打开上下文菜单时触发 | | DRAG_START | `dragstart` | 开始拖拽任何元素时触发 | | DRAG | `drag` | 拖拽任何元素过程中触发 | | DRAG_END | `dragend` | 拖拽任何元素结束时触发 | | DRAG_ENTER | `dragenter` | 拖拽物进入任何元素时触发 | | DRAG_OVER | `dragover` | 拖拽物在任何元素上方时触发 | | DRAG_LEAVE | `dragleave` | 拖拽物离开任何元素时触发 | | DROP | `drop` | 在任何元素上放置拖拽物时触发 | | KEY_DOWN | `keydown` | 键盘按键按下时触发 | | KEY_UP | `keyup` | 键盘按键抬起时触发 | | WHEEL | `wheel` | 滚动鼠标滚轮时触发 | | PINCH | `pinch` | 多点触控屏幕上双指捏合或张开时触发 | ## 使用技巧 ### 链式调用 G6 的事件 API 支持链式调用,可以连续注册多个事件: ```typescript import { NodeEvent, EdgeEvent, CanvasEvent } from '@antv/g6'; // 使用常量枚举+链式调用 graph.on(NodeEvent.CLICK, handleNodeClick).on(EdgeEvent.CLICK, handleEdgeClick).on(CanvasEvent.WHEEL, handleCanvasZoom); ``` ### 事件代理 你可以利用事件冒泡机制,在父元素上监听所有子元素的事件: ```typescript import { CommonEvent } from '@antv/g6'; // 统一处理所有元素的点击事件 graph.on(CommonEvent.CLICK, (evt) => { const { targetType, target } = evt; if (targetType === 'node') { console.log('点击了节点:', target.id); } else if (targetType === 'edge') { console.log('点击了边:', target.id); } else { console.log('点击了画布空白处'); } }); ``` ### 事件对象属性 大多数事件的回调函数会接收一个事件对象,包含以下常用属性: - `target` - 触发事件的元素 - `targetType` - 触发事件的元素类型(node/edge/combo/canvas) - `originalTarget` - 原始的触发事件的图形 - `currentTarget` - 当前触发事件的对象 - `originalEvent` - 原始的浏览器事件对象 通过这些属性,你可以精确地控制交互行为。 #### 坐标转换 - Canonical page: https://g6.antv.antgroup.com/zh/api/coordinate/ - Markdown source: https://g6.antv.antgroup.com/zh/api/coordinate.md - Description: 坐标转换 --- title: "坐标转换" description: "坐标转换" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/coordinate/" version: "5.1.1" --- ## 坐标系概述 在图可视化中,理解不同的坐标系及其转换关系至关重要。G6 中涉及多种坐标系,它们各自用于不同的场景: - **Client 坐标系**:浏览器视口左上角为原点,单位为像素。通常用于处理浏览器事件。 - **Screen 坐标系**:屏幕左上角为原点,会受页面滚动影响。 - **Page 坐标系**:文档左上角为原点,考虑文档滚动。 - **Canvas 坐标系**:也称为世界坐标系,图形绘制和布局时使用的坐标系,画布元素左上角为原点。 - **Viewport 坐标系**:视口坐标系,当前可见的画布区域,视口左上角为原点。视口通过平移、缩放等操作,可以观察不同的 Canvas 区域。 在这个[示例](https://g.antv.antgroup.com/zh/examples/canvas/canvas-basic#coordinates)中,移动鼠标可以看到鼠标所在位置在各个坐标系下的值: ![坐标系关系图](https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*kPfcTKwZG90AAAAAAAAAAAAAARQnAQ) 当画布没有发生平移和缩放时,Viewport 坐标系与 Canvas 坐标系重合。随着用户的交互(如拖拽画布、缩放),两个坐标系会出现偏移。 G6 提供了一系列 API 用于在不同坐标系之间进行转换,下面将详细介绍这些 API。 ## API 参考 ### Graph.getCanvasByClient(point) 将浏览器坐标(客户端坐标)转换为画布坐标。 ```typescript getCanvasByClient(point: Point): Point; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----- | ------------ | -------------------------------------------- | ------ | ---- | | point | 浏览器坐标点 | [number, number] \| [number, number, number] | - | ✓ | **返回值** - **类型**: [number, number] \| [number, number, number] - **描述**: 画布坐标系下的坐标点 ### Graph.getCanvasByViewport(point) 将视口坐标转换为画布坐标。 ```typescript getCanvasByViewport(point: Point): Point; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----- | ---------- | -------------------------------------------- | ------ | ---- | | point | 视口坐标点 | [number, number] \| [number, number, number] | - | ✓ | **返回值** - **类型**: [number, number] \| [number, number, number] - **描述**: 画布坐标系下的坐标点 ### Graph.getClientByCanvas(point) 将画布坐标转换为浏览器客户端坐标。 ```typescript getClientByCanvas(point: Point): Point; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----- | ---------- | -------------------------------------------- | ------ | ---- | | point | 画布坐标点 | [number, number] \| [number, number, number] | - | ✓ | **返回值** - **类型**: [number, number] \| [number, number, number] - **描述**: 浏览器客户端坐标系下的坐标点 ### Graph.getViewportByCanvas(point) 将画布坐标转换为视口坐标。 ```typescript getViewportByCanvas(point: Point): Point; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ----- | ---------- | -------------------------------------------- | ------ | ---- | | point | 画布坐标点 | [number, number] \| [number, number, number] | - | ✓ | **返回值** - **类型**: [number, number] \| [number, number, number] - **描述**: 视口坐标系下的坐标点 #### 导出图片 - Canonical page: https://g6.antv.antgroup.com/zh/api/export-image/ - Markdown source: https://g6.antv.antgroup.com/zh/api/export-image.md - Description: 导出图片 --- title: "导出图片" description: "导出图片" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/api/export-image/" version: "5.1.1" --- ## 图片导出概述 G6 提供了将图导出为图片的功能,可以将当前画布内容导出为 DataURL 格式,方便保存、分享或进一步处理。导出的图片会保留画布上的所有可见元素,包括节点、边、组合以及其他自定义图形。 ## API 参考 ### Graph.toDataURL(options) 将当前画布导出为 DataURL 格式的图片。 ```typescript toDataURL(options?: Partial): Promise; ``` **参数** | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------- | ------------ | ------------------------- | ------ | ---- | | options | 导出图片配置 | Partial\ | - | | **返回值** 返回一个 Promise,解析为表示图片的 DataURL 字符串。 **DataURLOptions 类型定义** | 参数 | 类型 | 必选 | 描述 | | -------------- | ------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------ | | mode | 'viewport' \| 'overall' | 否 | 导出模式
- viewport: 导出视口内容
- overall: 导出整个画布 | | type | 'image/png' \| 'image/jpeg' \| 'image/webp' | 否 | 图片类型
- image/png: PNG 格式
- image/jpeg: JPEG 格式
- image/webp: WebP 格式 | | encoderOptions | number | 否 | 图片质量,仅对 image/jpeg 和 image/webp 有效,取值范围 0 ~ 1 | ## 下载图片 G6 5.0 仅提供导出画布为 Base64 图片的 API([toDataURL](#graphtodataurloptions)),如果需要下载图片,可以使用以下方法: ```typescript async function downloadImage() { const dataURL = await graph.toDataURL(); const [head, content] = dataURL.split(','); const contentType = head.match(/:(.*?);/)![1]; const bstr = atob(content); let length = bstr.length; const u8arr = new Uint8Array(length); while (length--) { u8arr[length] = bstr.charCodeAt(length); } const blob = new Blob([u8arr], { type: contentType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'graph.png'; a.click(); } ```
:::warning{title=注意} 导出的图片内容可能不会包含完整的画布内容,导出范围仅包含 Graph 画布中的内容。部分插件使用了自定义的容器、画布等,这部分内容不会出现在导出的图片中。 ::: ### backup #### CameraSetting 相机设置 - Canonical page: https://g6.antv.antgroup.com/zh/backup/CameraSetting/ - Markdown source: https://g6.antv.antgroup.com/zh/backup/CameraSetting.md - Description: CameraSetting 相机设置 --- title: "CameraSetting 相机设置" description: "CameraSetting 相机设置" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/backup/CameraSetting/" version: "5.1.1" --- ## 配置项 ### **Required** type > _`camera-setting` \| string_ ⚠️ **注意**: - 相机设置插件必须在 3D 场景下使用 - 此插件在使用前需要自行注册: ```javascript import { register, CameraSetting, ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.PLUGIN, 'camera-setting', CameraSetting); // type: 'camera-setting' ``` ### aspect > _number \| `'auto'`_ 相机视口宽高比,仅在透视相机下有效 - number : 具体的宽高比 - `'auto'` : 自动设置为画布的宽高比 ### azimuth > _number_ 方位角 ### cameraType > _'orbiting' \| 'exploring' \| 'tracking'_ 相机类型 - `'orbiting'`: 固定视点,改变相机位置 - `'exploring'`: 类似 orbiting,但允许相机在北极和南极之间旋转 - `'tracking'`: 固定相机位置,改变视点 ### distance > _number_ **Default:** `500` 相机距离目标的距离 ### elevation > _number_ 仰角 ### far > _number_ 远平面位置 ### fov > _number_ 相机视角,仅在透视相机下有效 ### maxDistance > _number_ 最大视距 ### minDistance > _number_ 最小视距 ### near > _number_ 近平面位置 ### projectionMode > _'perspective' \| 'orthographic'_ 投影模式,透视投影仅在 3D 场景下有效 - `'perspective'` : 透视投影 - `'orthographic'` : 正交投影 ### roll > _number_ 滚转角 ## API ### manual #### 交互总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/overview.md - Description: 交互总览 --- title: "交互总览" description: "交互总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/overview/" version: "5.1.1" --- ## 什么是交互 交互(Behavior)是指用户与图表元素之间的互动操作,如拖拽画布、选择节点、缩放视图等。良好的交互设计能让用户更直观地探索和理解图数据。**合理配置交互是构建高效可用图表的关键环节**。 ### G6 5.0 交互系统变化 G6 5.0 移除了 "交互模式"(Mode) 概念,直接在 `behaviors` 中列出需要的交互行为,简化了配置方式。这使得交互配置更加直观,上手更加简单。 ```javascript {4} import { Graph } from '@antv/g6'; const graph = new Graph({ behaviors: ['drag-canvas', 'zoom-canvas', 'click-select'], }); ``` ## 内置交互 G6 提供了多种开箱即用的内置交互,**无需注册,直接配置即可使用**: | 分类 | 交互名称 | 注册类型 | 功能描述 | | -------- | ------------------------------------------------------------ | ----------------------------- | -------------------------- | | 导航 | | | | | | [拖拽画布](/zh/manual/behavior/DragCanvas/) | `drag-canvas` | 拖动整个画布视图 | | | [缩放画布](/zh/manual/behavior/ZoomCanvas/) | `zoom-canvas` | 缩放画布视图 | | | [滚动画布](/zh/manual/behavior/ScrollCanvas/) | `scroll-canvas` | 使用滚轮滚动画布 | | | [优化视口变换](/zh/manual/behavior/OptimizeViewportTransform/) | `optimize-viewport-transform` | 优化视图变换性能 | | 选择 | | | | | | [点击选择](/zh/manual/behavior/ClickSelect/) | `click-select` | 点击选择图元素 | | | [框选](/zh/manual/behavior/BrushSelect/) | `brush-select` | 通过拖拽矩形区域选择元素 | | | [套索选择](/zh/manual/behavior/LassoSelect/) | `lasso-select` | 自由绘制区域选择元素 | | 编辑 | | | | | | [创建边](/zh/manual/behavior/CreateEdge/) | `create-edge` | 交互式创建新的边 | | | [拖拽元素](/zh/manual/behavior/DragElement/) | `drag-element` | 拖动节点或组合 | | | [力导向拖拽](/zh/manual/behavior/DragElementForce/) | `drag-element-force` | 力导向布局中拖动节点 | | 数据探索 | | | | | | [折叠/展开](/zh/manual/behavior/CollapseExpand/) | `collapse-expand` | 展开或收起子树节点 | | | [聚焦元素](/zh/manual/behavior/FocusElement/) | `focus-element` | 聚焦特定元素,自动调整视图 | | | [悬停激活](/zh/manual/behavior/HoverActivate/) | `hover-activate` | 鼠标悬停时高亮元素 | | 视觉优化 | | | | | | [固定元素大小](/zh/manual/behavior/FixElementSize/) | `fix-element-size` | 将元素大小固定为指定值 | | | [自适应标签](/zh/manual/behavior/AutoAdaptLabel/) | `auto-adapt-label` | 自动调整标签位置 | 各交互的详细配置可参考 [内置交互文档](/zh/manual/behavior/DragCanvas/)。 :::warning{title=交互兼容性} 某些交互在触发机制上可能存在重叠,如 `brush-select` 和 `drag-canvas` 都使用鼠标拖拽。这种情况下可以通过修改触发按键(如按住 `Shift` 拖拽选择)来避免冲突。 ::: ## 自定义交互 当内置交互无法满足需求时,G6 提供了强大的自定义能力: - 继承内置交互进行扩展 - 创建全新的交互行为 与内置交互不同,**自定义交互需要先注册后使用**。详细教程请参考 [自定义交互](/zh/manual/behavior/custom-behavior/) 文档。 ## 配置和使用 ### 基本配置 最简单的方式是在图实例初始化时,通过 `behaviors` 数组直接指定需要的交互: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-canvas', 'zoom-canvas', 'click-select'], }); ``` ### 配置交互参数 对于需要自定义参数的交互,可以使用 `object` 的形式配置属性: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ 'drag-canvas', { type: 'zoom-canvas', sensitivity: 1.5, // 配置灵敏度 key: 'zoom-behavior', // 为交互指定key,便于后续更新 }, ], }); ``` ### 动态更新交互 G6 支持在图实例运行期间动态管理交互行为,满足复杂交互需求: 可以通过 [setBehaviors](/zh/api/behavior/#graphsetbehaviorsbehaviors) 方法调整交互: ```javascript // 添加新交互 graph.setBehaviors((behaviors) => [...behaviors, 'lasso-select']); // 移除交互 graph.setBehaviors((behaviors) => behaviors.filter((b) => b !== 'click-select')); ``` 可以使用 [updateBehavior](/zh/api/behavior/#graphupdatebehaviorbehavior) 方法更新交互的配置: ```javascript // 更新单个交互 graph.updateBehavior({ key: 'zoom-behavior', sensitivity: 2, enable: false, // 禁用该交互 }); ``` :::warning{title=注意} 使用`updateBehavior`方法时,需要在初始化时为交互指定唯一的`key`。 ::: ### 卸载交互 使用 [setBehaviors](/zh/api/behavior/#graphsetbehaviorsbehaviors) 方法同样可以卸载交互,将交互配置列表置为空即可: ```javascript graph.setBehaviors([]); ``` 更多与交互相关的 API 请参考 [交互 API 文档](/zh/api/behavior/)。 ## 交互与事件 交互本质上是通过事件监听和响应来实现的。虽然内置交互已经封装了常见的交互行为,但你也可以通过事件 API 直接实现自定义交互逻辑。 ### 事件监听示例 ```javascript // 使用事件常量(推荐) import { NodeEvent, EdgeEvent } from '@antv/g6'; // 监听节点点击 graph.on(NodeEvent.CLICK, (evt) => { const { target } = evt; graph.setElementState(target.id, 'selected'); }); // 监听边悬停 graph.on(EdgeEvent.POINTER_OVER, (evt) => { const { target } = evt; graph.setElementState(target.id, 'highlight'); }); ``` 事件系统是实现交互的基础,掌握事件 API 对于理解和扩展交互行为至关重要。更多事件相关信息,请参考 [事件文档](/zh/api/event/)。 #### 缩放画布 ZoomCanvas - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/ZoomCanvas/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/ZoomCanvas.md - Description: 缩放画布 ZoomCanvas --- title: "缩放画布 ZoomCanvas" description: "缩放画布 ZoomCanvas" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/ZoomCanvas/" version: "5.1.1" --- ## 概述 ZoomCanvas 是 G6 中用于实现画布缩放功能的内置交互,支持通过鼠标滚轮或键盘快捷键调整画布缩放比例。这是图可视化中最常用的交互之一,能帮助用户查看图的整体结构和局部细节。 ## 使用场景 这一交互主要用于: - 浏览大规模图数据,在整体与细节之间自由切换 - 聚焦到特定区域进行详细分析 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node-1' }] }, layout: { type: 'force' }, behaviors: [ { type: 'zoom-canvas', key: 'zoom-canvas', }, ], node: { style: { fill: '#873bf4' } }, edge: { style: { stroke: '#8b9baf' } }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'zoom-canvas', type: 'zoom-canvas', animation: true, enable: true, sensitivity: 1, trigger: 'Use wheel by default', }; const optionFolder = gui.addFolder('ZoomCanvas Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'sensitivity', 0, 10, 1); optionFolder.add(options, 'trigger', { 'Use wheel by default': [], 'Control+Wheel': ['Control'], 'zoomIn:Ctrl+1 zoomOut:Ctrl+2 reset:Ctrl+0': { zoomIn: ['Control', '1'], zoomOut: ['Control', '2'], reset: ['Control', '0'], }, }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'zoom-canvas', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['zoom-canvas'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'zoom-canvas', key: 'zoom-canvas-1', // 为交互指定标识符,方便动态更新 sensitivity: 1.5, // 设置灵敏度 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | -------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------- | ---- | | type | 交互类型名称 | string | `zoom-canvas` | ✓ | | animation | 缩放动画效果设置 | [ViewportAnimationEffectTiming](/zh/manual/graph/option/#viewportanimationeffecttiming) | `{ duration: 200 }` | | | enable | 是否启用该交互 | boolean \| ((event: Event) => boolean) | true | | | origin | 缩放中心点(视口坐标) | [Point](/zh/api/viewport/#point) | - | | | onFinish | 缩放完成时的回调函数 | () => void | - | | | preventDefault | 是否阻止浏览器默认事件 | boolean | true | | | sensitivity | 缩放灵敏度,值越大缩放速度越快 | number | 1 | | | trigger | 触发缩放的方式,支持滚轮和键盘快捷键,[配置项](#trigger) | string[] \| object | - | | ### Trigger `trigger`有两种使用方式,分别适用于不同场景: #### 方式一:与滚轮结合的修饰键 当你希望只有在按下某些键的同时滚动滚轮才触发缩放时,可以这样配置: ```javascript { trigger: ['Control']; // 按住 Control 键同时滚动鼠标滚轮才能缩放 } ``` 常见的修饰键有: - `Control` - `Shift` - `Alt` > 不知道键盘按键对应什么值?请参考 [MDN Key Values](https://developer.mozilla.org/zh-CN/docs/Web/API/UI_Events/Keyboard_event_key_values)。 #### 方式二:纯键盘快捷键 当你希望完全使用键盘控制缩放操作时,可以设置组合键: ```javascript { trigger: { zoomIn: ['Control', '+'], // 放大快捷键 zoomOut: ['Control', '-'], // 缩小快捷键 reset: ['Control', '0'] // 重置缩放比例快捷键 } } ``` ## 代码示例 ### 基础缩放功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['zoom-canvas'], }); ``` ### 自定义缩放中心 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ function () { return { type: 'zoom-canvas', origin: this.getCanvasCenter(), // 以视口中心为原点进行缩放 }; }, ], }); ``` ### 自定义缩放灵敏度 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'zoom-canvas', sensitivity: 0.8, // 降低灵敏度,缩放变化更平缓 }, ], }); ``` ### 使用Shift+滚轮进行缩放 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'zoom-canvas', trigger: ['Shift'], // 按住 Shift 键同时滚动才能缩放 }, ], }); ``` ### 使用键盘快捷键控制缩放 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'zoom-canvas', trigger: { zoomIn: ['Control', '='], // Ctrl + = 放大 zoomOut: ['Control', '-'], // Ctrl + - 缩小 reset: ['Control', '0'], // Ctrl + 0 重置 }, }, ], }); ``` ### 支持移动端双指缩放 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'zoom-canvas', // PC 端其他配置... }, function () { return { type: 'zoom-canvas', trigger: ['pinch'], sensitivity: 0.8, // 降低灵敏度,缩放变化更平缓 origin: this.getCanvasCenter(), // 以视口中心为原点进行缩放 }; }, ], }); ``` ## 常见问题 ### 1. 画布缩放超出了预期范围怎么办? 为避免缩放过大或过小,可以设置缩放限制: ```javascript const graph = new Graph({ // 其他配置... zoomRange: [0.5, 3], // 允许缩小到50%和放大到300% behaviors: ['zoom-canvas'], }); ``` ### 2. 如何与其他交互结合使用? 缩放与拖拽是常见的组合,实现完整的导航体验: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-canvas', 'zoom-canvas'], }); ``` ### 3. 触控板双指操作下,与 scroll-canvas 同时使用时的冲突 在触控板上,双指滑动(用于滚动)和双指捏合(用于缩放)手势通常都会被解析为 `wheel` 事件。 由于 `zoom-canvas` 和 `scroll-canvas` 默认都会响应 `wheel` 事件,当它们同时使用时会产生冲突,例如一个手势会同时触发滚动和缩放。 你可以通过检查 `event.ctrlKey` 属性来解决这个问题。在多数平台上,捏合手势会使 `event.ctrlKey` 为 `true`,而滑动则不会。这允许你有条件地仅为捏合手势启用 `zoom-canvas`。 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }], }, behaviors: [ 'scroll-canvas', { key: 'custom-zoom-canvas', type: 'zoom-canvas', enable: (event) => { return event.ctrlKey; // ctrlKey 为 true 时,是双指捏合或扩张操作,false 时是双指滑动操作 }, }, ], }); graph.render(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, behaviors: ['zoom-canvas'], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 组合总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/combo/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/combo/overview.md - Description: 组合总览 --- title: "组合总览" description: "组合总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/combo/overview/" version: "5.1.1" --- ## 什么是组合 组合(Combo) 全称为 Combination,是 G6 中的一种特殊的图元素,它可以包含节点和子组合,类似“群组”或“容器”的概念。它通常用于表示集合关系,例如一个部门包含多个员工,一个城市包含多个区域等。 :::warning\{title=注意\} 不推荐在**树图**中使用 Combo。因为树图的布局与 Combo 的布局机制不兼容,容易导致节点错位或样式混乱。 ::: G6 的内置 Combo 包括 `circle`(圆形组合)和 `rect` (矩形组合) 两种类型,分别如下图所示: ## 数据结构 定义 Combo 时,需要在图的数据对象中添加 `combos` 字段,每个 Combo 是一个对象,结构如下: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | ----------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 组合的唯一标识符 | string | - | ✓ | | type | 组合类型,内置组合类型名称或者自定义组合名称,比如 `circle` 或者 `rect` | string | - | | | data | 组合数据,用于存储组合的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 组合样式 | object | - | | | states | 组合初始状态 | string[] | - | | | combo | 组合的父组合 ID。如果没有父组合,则为 null | string \| null | - | | `combos` 数组中一个数据项的示例: ```json { "id": "combo1", "type": "circle", "data": { "groupName": "Group A" }, "style": { "fill": "lightblue", "stroke": "blue", "collapsed": true }, "states": [], "combo": null } ``` 要将节点归属到某个 Combo,可以在节点数据中添加 `combo` 字段: ```json { "nodes": [{ "id": "node1", "combo": "comboA" }], // node1 属于 comboA "combos": [{ "id": "comboA" }] // 定义 comboA } ``` ## 配置方法 配置 Combo 的方式有三种,按优先级从高到低如下: - 使用 `graph.setCombo()` 动态配置 - 实例化图时全局配置 - 在数据中动态属性 这几个配置方法可以同时使用。有相同的配置项时,优先级高的方式将会覆盖优先级低的。 ### 使用 `graph.setCombo()` 可在图实例创建后,使用 `graph.setCombo()` 动态设置 Combo 的样式映射逻辑。 该方法需要在 `graph.render()` 之前调用才会生效,并拥有最高优先级。 ```js graph.setCombo({ style: { type: 'circle', style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, }); graph.render(); ``` ### 实例化图时全局配置 在实例化图时可以通过 `combo` 配置 Combo 样式映射,这里的配置是全局的配置,将会在所有 Combo 上生效。 ```js import { Graph } from '@antv/g6'; const graph = new Graph({ // 在组合配置中指定组合类型以及组合样式类型 combo: { type: 'circle', style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, }); ``` ### 在数据中动态配置 如果需要为不同 Combo 进行不同的配置,可以将配置写入到 Combo 数据中。这种配置方式可以通过下面代码的形式直接写入数据: ```typescript // 在数据中指定组合类型以及组合样式类型 const data = { combos: [ { id: 'combo-1', type: 'circle', style: { size: 100, stroke: 'orange' }, }, ], }; ``` ### 调整优先级 如果你想让数据中配置的优先级高于全局配置,你可以采取以下方式: ```js const data = { combos: [ { id: 'combo-1', type: 'circle', style: { size: 100, stroke: 'orange' }, }, ], }; const graph = new Graph({ combo: { type: (d) => d.type || 'rect', style: { stroke: (d) => d.style.stroke || 'blue', }, }, }); ``` ## 示例 ```ts import { Graph, register, Rect, ExtensionCategory } from '@antv/g6'; const data = { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 245, y: 200 }, }, { id: 'node2', combo: 'combo1', style: { x: 210, y: 250 }, }, { id: 'node3', combo: 'combo1', style: { x: 280, y: 245 }, }, { id: 'node4', combo: 'combo2', style: { x: 400, y: 165 }, }, { id: 'node5', combo: 'combo2', style: { x: 450, y: 162 }, }, { id: 'node6', combo: 'combo3', style: { x: 425, y: 300 }, }, { id: 'node7', combo: 'combo3', style: { x: 360, y: 332 }, }, ], edges: [], combos: [ { id: 'combo1', combo: 'combo3', data: { label: 'Combo A' }, }, { id: 'combo2', combo: 'combo3', data: { label: 'Combo B' }, }, { id: 'combo3', data: { label: 'Combo C' }, }, { id: 'combo4', data: { label: 'Combo D' }, style: { x: 58, y: 248 }, }, ], }; const graph = new Graph({ container: 'container', height: 450, data, node: { style: { labelText: (d) => d.id, labelPlacement: 'center', labelFill: '#fff', labelFontSize: 10, }, }, combo: { type: 'circle', style: { padding: 2, labelText: (d) => d.data.label, labelPlacement: 'top', }, }, behaviors: [ 'collapse-expand', { type: 'drag-element', dropEffect: 'link', }, ], }); graph.render(); ``` ## Combo 交互 只是简单地将 Combo 渲染出来,并没有多大的实用价值,只有支持一系列的交互操作后,才能最大程度地体现 Combo 的价值。 在 G6 中,我们内置了 `drag-element`、`collapse-expand` 三个交互。 #### drag-element 支持拖动节点和 Combo。拖动 Combo 过程中,会动态改变 Combo 中节点和边的位置,在拖拽完成以后,保持 Combo 和节点的相对位置不变。还可以通过设置 `dropEffect: 'link'` 在拖拽时改变 Combo 的从属关系。 #### collapse-expand 支持双击 Combo 收起和展开 Combo ,收起 Combo 以后,隐藏 Combo 中的所有节点,外部节点和 Combo 中节点有连线的情况下,所有连接会连接到 Combo 上面。 ## 自定义组合 当内置组合无法满足需求时,G6 提供了强大的自定义能力: - 继承内置组合进行扩展 - 创建全新的组合类型 与组合不同,自定义组合需要先注册后使用。详细教程请参考 [自定义组合](/zh/manual/element/combo/custom-combo/) 文档。 #### 边总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/overview.md - Description: 边总览 --- title: "边总览" description: "边总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/overview/" version: "5.1.1" --- ## 什么是边 边(Edge)是图中的基本元素之一,用于连接两个节点或组合,表示它们之间的关系。在 G6 中,边具有方向性,从 `source` 指向 `target`,也可以通过配置隐藏箭头以表示无方向连接。 你可以在任意两个节点、组合,或节点与组合之间创建边,还可以通过创建多条边来表达不同的关系类型。 G6 提供了以下内置边: - `line` 直线边 - `polyline` 折线边 - `quadratic` 二次贝塞尔曲线边 - `cubic` 三次贝塞尔曲线边 - `cubicVertical` 垂直三次贝塞尔曲线边 - `cubicHorizontal` 水平三次贝塞尔曲线边 ### 数据结构 定义边时,需要在图的数据对象中添加 `edges` 字段。每条边是一个对象,结构如下: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | --------------------------------------------------------------------- | -------- | ------ | ---- | | source | 边起始节点 ID | string | - | ✓ | | target | 边目标节点 ID | string | - | ✓ | | id | 边的唯一标识符 | string | - | | | type | 边类型,内置边类型名称或者自定义边的名称,比如 `line` 或者 `polyline` | string | - | | | data | 边数据,用于存储边的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 边样式,包括线条颜色、宽度、箭头等视觉属性 | object | - | | | states | 边初始状态 | string[] | - | | `edges` 数组中一个数据项的示例: ```json { "source": "alice", "target": "bob", "type": "line", "data": { "relationship": "friend", "strength": 5 }, "style": { "stroke": "green", "lineWidth": 2 }, "states": ["hover"] } ``` ### 配置方法 配置边的方式有三种,按优先级从高到低如下: - 使用 `graph.setEdge()` 动态配置 - 实例化图时全局配置 - 在数据中动态属性 这几个配置方法可以同时使用。有相同的配置项时,优先级高的方式将会覆盖优先级低的。 ### 使用 `graph.setEdge()` 可在图实例创建后,使用 `graph.setEdge()` 动态设置边的样式映射逻辑。 该方法需要在 `graph.render()` 之前调用才会生效,并拥有最高优先级。 ```js graph.setEdge({ style: { type: 'line', style: { stroke: '#5CACEE', lineWidth: 2 }, }, }); graph.render(); ``` ### 实例化图时全局配置 在实例化图时可以通过 `edge` 配置边样式映射,这里的配置是全局的配置,将会在所有边上生效。 ```js import { Graph } from '@antv/g6'; const graph = new Graph({ edge: { type: 'line', style: { stroke: '#5CACEE', lineWidth: 2 }, }, }); ``` ### 在数据中动态配置 如果需要为不同边进行不同的配置,可以将配置写入到边数据中。这种配置方式可以通过下面代码的形式直接写入数据: ```typescript const data = { edges: [ { source: 'node-1', target: 'node-2', type: 'line', style: { stroke: 'orange' }, }, ], }; ``` ### 调整优先级 如果你想让数据中配置的优先级高于全局配置,你可以采取以下方式: ```js const data = { edges: [ { source: 'node-1', target: 'node-2', type: 'line', style: { stroke: 'orange' }, }, ], }; const graph = new Graph({ edge: { type: 'line', style: { stroke: (d) => d.style.stroke || '#5CACEE', lineWidth: 2, }, }, }); ``` ## 自定义边 当内置边无法满足需求时,G6 提供了强大的自定义能力: - 继承内置边进行扩展 - 创建全新的边类型 与组合不同,自定义边需要先注册后使用。详细教程请参考 [自定义边](/zh/manual/element/edge/custom-edge/) 文档。 #### 节点总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/overview.md - Description: 节点总览 --- title: "节点总览" description: "节点总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/overview/" version: "5.1.1" --- ## 什么是节点 节点(Node)是图中的基本元素之一,表示图中的实体或者抽象概念,例如一个人、一个地点、一个组织等,节点可以包含一些属性,例如节点的 ID、名称、类型等。在 G6 中,节点可以具有多种形状和样式,并支持丰富的交互和自定义功能。 你可以在图中创建任意数量的节点,并通过边连接它们以表示关系。 ## 节点体系 G6 的节点体系包括三大类:内置节点、扩展节点和自定义节点。**大多数场景下,内置节点即可满足需求**。 ### 内置节点 G6 提供了丰富的内置节点类型,**无需注册,直接配置即可使用**: | 节点类型 | 注册名称 | 描述 | | ---------- | ---------- | ------------------------ | | 圆形节点 | `circle` | 常用于表示普通实体 | | 矩形节点 | `rect` | 适合展示更多文本和细节 | | 椭圆节点 | `ellipse` | 类似圆形的变体 | | 菱形节点 | `diamond` | 常用于决策点或特殊节点 | | 三角形节点 | `triangle` | 可用于指示方向或特殊标记 | | 六边形节点 | `hexagon` | 适合网格布局和蜂窝图 | | 星形节点 | `star` | 突出显示重要节点 | | 甜甜圈节点 | `donut` | 可展示比例或进度信息 | | 图片节点 | `image` | 使用图片作为节点主体 | | HTML节点 | `html` | 支持自定义HTML内容 | ### 3D 节点 `@antv/g6-extension-3d` 提供了 3D 节点: - `Capsule` - 胶囊型节点 - `Cone` - 圆锥型节点 - `Cube` - 立方体节点 - `Cylinder` - 圆柱型节点 - `Plane` - 平面节点 - `Sphere` - 球体节点 - `Torus` - 圆环节点 ### React 节点 `@antv/g6-extension-react` 提供了 React 节点,支持使用 React 组件作为节点的主体,详细教程请查看 [使用 React 定义节点](/zh/manual/element/node/react-node/) 文档。 ### 自定义节点 当内置节点和扩展节点无法满足需求时,G6提供了强大的自定义能力: - 继承内置节点进行扩展 - 创建全新的节点类型 与内置节点不同,**自定义节点需要先注册后使用**。详细教程请参考 [自定义节点](/zh/manual/element/node/custom-node/) 文档。 ## 数据结构 定义节点时,需要在图的数据对象中添加 `nodes` 字段。每个节点是一个对象,结构如下: | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------- | -------------------------------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 节点的唯一标识符,用于区分不同的节点 | string | - | ✓ | | type | 节点类型,内置节点类型名称或者自定义节点的名称 | string | - | | | data | 节点数据,用于存储节点的自定义数据,例如节点的名称、描述等。可以在样式映射中通过回调函数获取 | object | - | | | style | 节点样式,包括位置、大小、颜色等视觉属性 | object | - | | | states | 节点初始状态,如选中、激活、悬停等 | string[] | - | | | combo | 所属的组合 ID,用于组织节点的层级关系,如果没有则为 null | string \| null | - | | | children | 子节点 ID 集合,仅在树图场景下使用 | string[] | - | | `nodes` 数组中一个数据项的示例: ```json { "id": "node-1", "type": "circle", "data": { "name": "alice", "role": "Admin" }, "style": { "x": 100, "y": 200, "size": 32, "fill": "violet" }, "states": ["selected"], "combo": null } ``` ## 配置方法 配置节点的方式有三种,按优先级从高到低如下: - 使用 `graph.setNode()` 动态配置 - 实例化图时全局配置 - 在数据中动态属性 这几个配置方法可以同时使用。有相同的配置项时,优先级高的方式将会覆盖优先级低的。 ### 使用 `graph.setNode()` 可在图实例创建后,使用 `graph.setNode()` 动态设置节点的样式映射逻辑。 该方法需要在 `graph.render()` 之前调用才会生效,并拥有最高优先级。 ```js graph.setNode({ style: { type: 'circle', style: { size: 60, fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, }); graph.render(); ``` ### 实例化图时全局配置 在实例化图时可以通过 `node` 配置节点样式映射,这里的配置是全局的配置,将会在所有节点上生效。 ```js import { Graph } from '@antv/g6'; const graph = new Graph({ node: { type: 'circle', style: { size: 60, fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, }); ``` ### 在数据中动态配置 如果需要为不同节点进行不同的配置,可以将配置写入到节点数据中。这种配置方式可以通过下面代码的形式直接写入数据: ```typescript const data = { nodes: [ { id: 'node-1', type: 'circle', style: { size: 60, fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, ], }; ``` ### 调整优先级 如果你想让数据中配置的优先级高于全局配置,你可以采取以下方式: ```js const data = { nodes: [ { id: 'node-1', type: 'circle', style: { size: 60, fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2 }, }, ], }; const graph = new Graph({ node: { type: 'circle', style: { stroke: (d) => d.style.stroke || '#5CACEE', lineWidth: 2, }, }, }); ``` ### 动态更新节点 G6 支持在运行时动态更新节点的样式和状态: ```typescript // 更新单个节点样式 graph.updateNodeData([ { id: 'node-1', style: { fill: 'red', size: 80, }, }, ]); graph.draw(); // 设置节点状态 graph.setElementState('node-1', ['selected']); ``` :::warning{title=注意} 更新节点时,只有指定的属性会被更新,未指定的属性保持不变。 ::: 更多与节点相关的 API 请参考 [API - 元素操作](/zh/api/element/)。 ## 节点状态 节点可以拥有不同的状态,例如选中、高亮、禁用等。可以通过配置状态样式来定义节点在不同状态下的显示效果: ```typescript const graph = new Graph({ node: { style: { // 默认样式 fill: '#C6E5FF', }, // 状态样式 state: { selected: { fill: '#ffa940', stroke: '#ff7a00', haloStroke: '#ff7a00', }, highlight: { stroke: '#1890ff', lineWidth: 3, }, }, }, }); ``` 状态系统是实现节点交互效果的基础,更多状态的介绍,请参考 [元素状态](/zh/manual/element/state/)。 #### 事件 - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/event/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/event.md - Description: 事件 --- title: "事件" description: "事件" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/event/" version: "5.1.1" --- ## 概述 G6 中的事件系统是在 [G](https://g.antv.antgroup.com/api/event/intro) 的事件系统基础上进行了封装,提供了更多的事件类型,以及更加方便的事件绑定和解绑方法。 ## 事件类型 G6 中的事件类型主要分为以下几类: 1. 图(Graph)事件 2. 画布(Canvas)事件 3. 元素(Element)事件 ### 图事件 图事件是指与整个图实例相关的事件,例如图的渲染完成事件、图的更新事件等。图事件的完整列表见[GraphEvent](/zh/api/event/#图表生命周期事件-graphevent)。 #### 监听图事件 图事件的监听与默认的事件监听方式一致,例如监听图的渲染完成事件: ```typescript import { Graph, GraphEvent } from '@antv/g6'; const graph = new Graph({ // ... }); graph.on(GraphEvent.AFTER_RENDER, () => { // event handler }); ``` ### 画布事件 画布事件是指与画布相关的事件,例如画布的点击事件、画布的拖拽事件等。画布事件的完整列表见[CanvasEvent](/zh/api/event/#画布事件-canvasevent)。 #### 监听画布事件 例如监听画布的点击事件: ```typescript import { Graph, CanvasEvent } from '@antv/g6'; const graph = new Graph({ // ... }); graph.on(CanvasEvent.CLICK, (event) => { // event handler }); ``` ### 元素事件 元素事件主要指在元素对象上触发的事件,例如节点的拖拽事件、边的点击事件等。元素分为节点(`node`)、边(`edge`)、组合(`combo`)三类,对应的事件完整列表分别见:[NodeEvent](/zh/api/event/#节点事件-nodeevent) 、[EdgeEvent](/zh/api/event/#边事件-edgeevent)、[ComboEvent](/zh/api/event/#combo事件-comboevent)。 #### 监听元素事件 与画布事件类似,例如监听节点的拖拽和边的点击事件: ```ts import { Graph, NodeEvent, EdgeEvent, ComboEvent } from '@antv/g6'; const graph = new Graph({ // ... }); graph.on(NodeEvent.DRAG, (event) => { // event handler }); graph.on(EdgeEvent.CLICK, (event) => { // event handler }); graph.on(ComboEvent.CLICK, (event) => { // event handler }); ``` ## 事件监听与解除 G6 提供以下 API 用于事件监听和解除: ### on 添加事件监听 ```typescript const handler = (event) => { // event handler }; graph.on('event_name', handler); ``` ### off 移除事件监听 ```typescript graph.off('event_name', handler); ``` 当不传入任何参数时,会移除所有事件监听: ```typescript graph.off(); ``` ### once 添加一次性事件监听,即事件触发后会自动移除事件监听 ```typescript graph.once('event_name', handler); ``` ### emit 如果你想手动触发一个事件,可以使用 `emit` 方法: ```typescript graph.emit('event_name', { // event data }); ``` #### 在 React 中使用 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/react/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/react.md - Description: 在 React 中使用 --- title: "在 React 中使用" description: "在 React 中使用" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/integration/react/" version: "5.1.1" --- :::info{title=建议} 如果你需要更完善的 React 与 G6 集成解决方案,可以使用 AntV 官方封装库 [`@antv/graphin`](https://github.com/antvis/graphin)。 ::: ## 非严格模式 参考下面的示例,你可以在 React 中使用 G6,也可以查看 [在线示例](https://stackblitz.com/edit/g6-in-react?file=src/App.tsx) 。 ```jsx import { Graph } from '@antv/g6'; import { useEffect, useRef } from 'react'; export default () => { const containerRef = useRef(null); useEffect(() => { const graph = new Graph({ container: containerRef.current!, width: 500, height: 500, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 100 }, }, { id: 'node-2', style: { x: 150, y: 100 }, }, ], edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2' }], }, }); graph.render(); }, []); return
; }; ``` ## 严格模式 在严格模式下,React 会在开发环境中有意执行挂载、卸载、再挂载。请把 Graph 实例放在 effect 里创建,用 ref 保存,并在清理函数中销毁,这样第一次开发态挂载不会留下旧实例。下面的完整示例同时演示了如何注册和渲染 React 节点。 ```tsx import { ExtensionCategory, Graph as G6Graph, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; import { useEffect, useRef } from 'react'; register(ExtensionCategory.NODE, 'react-node', ReactNode); const SelectableNode = (props: { selected: boolean; onToggle: () => void }) => { const { selected, onToggle } = props; return ( ); }; export default function App() { const containerRef = useRef(null); const graphRef = useRef(null); useEffect(() => { if (!containerRef.current) return; const handleToggle = (id: string, selected: boolean) => { const graph = graphRef.current; if (!graph) return; graph.updateNodeData([{ id, data: { selected: !selected } }]); graph.draw(); }; const graph = new G6Graph({ container: containerRef.current, width: 500, height: 300, data: { nodes: [{ id: 'node-1', style: { x: 250, y: 150 }, data: { selected: false } }], }, node: { type: 'react-node', style: { size: [160, 50], component: (data) => ( handleToggle(data.id, Boolean(data.data?.selected))} /> ), }, }, }); graphRef.current = graph; graph.render(); return () => { graph.destroy(); graphRef.current = null; }; }, []); return
; } ``` #### 快速开始 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/quick-start/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/quick-start.md - Description: 快速开始 --- title: "快速开始" description: "快速开始" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/quick-start/" version: "5.1.1" --- ## 在线体验 G6 访问 [图表示例](/zh/examples/) 无需任何环境配置即可在线体验 G6。 ## 创建一个简单的图 在本例子中,我们将基于 HTML 页面使用 G6 创建一个简单的图。 将下面的代码复制到一个 HTML 文件中,然后在浏览器中打开这个文件: ```html
``` 会得到如下所示的图: ```ts import { createGraph } from '/demo-runtime.ts'; fetch('https://assets.antv.antgroup.com/g6/graph.json') .then((res) => res.json()) .then((data) => createGraph( { data, autoFit: 'view', animation: false, node: { style: { size: 10, }, palette: { field: 'group', color: 'tableau', }, }, layout: { type: 'd3-force', animation: false, manyBody: {}, x: {}, y: {}, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }, { width: 500, height: 500 }, ), ); ``` 下面分析一下这段代码: 1. 首先我们创建一个 `div` 元素作为图的容器: ```html
``` 2. 然后引入 G6 的 JS 文件: ```html ``` 3. 使用 `fetch` 方法获取图的数据: ```js fetch('https://assets.antv.antgroup.com/g6/graph.json').then((res) => res.json()); ``` 4. 最后创建一个图实例,传入配置对象,并调用 `render` 方法渲染图: ```js const { Graph } = G6; const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { size: 10, }, palette: { field: 'group', color: 'tableau', }, }, layout: { type: 'd3-force', manyBody: {}, x: {}, y: {}, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }); graph.render(); ``` 如果你使用 React、Vue、Angular 等框架,可以查看: - [在 React 中使用 G6](/zh/manual/getting-started/integration/react/) - [在 Vue 中使用 G6](/zh/manual/getting-started/integration/vue/) - [在 Angular 中使用 G6](/zh/manual/getting-started/integration/angular/) ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### Graph - 图 - Canonical page: https://g6.antv.antgroup.com/zh/manual/graph/graph/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/graph/graph.md - Description: Graph - 图 --- title: "Graph - 图" description: "Graph - 图" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/graph/graph/" version: "5.1.1" --- ## 什么是 Graph 中文字“图”在大家的传统认知里指的是图画、图像,而图论与可视化中的“图”—— Graph 则有着更精确的定位:主体(objects)与关系(relationships)的组成。它甚至不局限于视觉,主体与关系的数据也可以称为图。 > —— 摘自 [AntV 专栏](https://zhuanlan.zhihu.com/aiux-antv) 文章:[Graph Visualization · 知多少 之 《HelloWorld 图可视化》](https://zhuanlan.zhihu.com/p/83685690)。 在 G6 中,Graph 对象是图的载体,它包含了图上的所有元素(节点、边等),同时挂载了图的相关操作(如交互监听、元素操作、渲染等)。 Graph 对象的完整生命周期包括: 1. **创建**: 通过 `new Graph(options)` 实例化 2. **初始化**: 在创建时进行内部初始化 3. **渲染**: 调用 `graph.render()` 进行首次渲染 4. **更新**: 通过各种 API 更新图的数据和配置 5. **销毁**: 调用 `graph.destroy()` 销毁实例并释放资源 ## 使用 G6 Graph 要使用 G6 创建 Graph,首先需要引入 `@antv/g6` 库,然后实例化 Graph 类。 > 安装教程参考:[开始使用 - 安装](/zh/manual/getting-started/installation/) Graph 类接收一个实例化参数对象,称之为**配置项**(Options,在可视化理论中将其称为:`Specification`),用于配置图的数据、元素样式、布局、交互等。 ```typescript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', // 通过 DOM ID 指定容器 width: 800, // 画布宽高(若容器已设尺寸可省略) height: 600, data: { // 初始数据 nodes: [{ id: 'start', data: { label: 'Hello G6!' } }], }, }); ``` :::warning\{title=注意\} 实例化过程仅是配置图的基本信息,要将图渲染到页面上,还需要调用 `render` 方法 ::: ## 图配置项 通过下表速查图的配置项,更多类型定义说明和详细用法请参考 [API - 图配置项](/zh/manual/graph/option/)。 | 属性 | 类型 | 默认值 | 描述 | | ---------------- | ---------------------------------- | ----------- | ------------------------------------------------------------- | | container | string \| HTMLElement \| Canvas | - | 图容器,可以是 DOM 元素 ID、DOM 元素实例或 Canvas 实例 | | width | number | 容器宽度 | 画布宽度(像素) | | height | number | 容器高度 | 画布高度(像素) | | autoFit | 'view' \| 'center' \| object | - | 自动适配策略,'view'(适应视图)或'center'(居中) | | autoResize | boolean | false | 是否在窗口大小变化时自动调整画布大小 | | background | string | - | 画布背景色,也作为导出图片时的背景色 | | canvas | CanvasConfig | - | 画布配置 | | cursor | Cursor | `'default'` | 指针样式 | | devicePixelRatio | number | 2 | 设备像素比 | | padding | number \| number[] | - | 画布内边距,在自适应时会根据内边距进行适配 | | renderer | (layer: string) => IRenderer | - | 手动指定渲染器 | | rotation | number | 0 | 旋转角度(弧度) | | zoom | number | 1 | 缩放比例 | | zoomRange | [number, number] | [0.01, 10] | 缩放比例的限制范围 | | x | number | - | 视口 x 坐标 | | y | number | - | 视口 y 坐标 | | data | GraphData | - | 图数据,详见 [数据](/zh/manual/data/) | | node | NodeOptions | - | 节点全局配置,详见 [节点](/zh/manual/element/node/overview/) | | edge | EdgeOptions | - | 边全局配置,详见 [边](/zh/manual/element/edge/overview/) | | combo | ComboOptions | - | 组合全局配置,详见 [组合](/zh/manual/element/combo/overview/) | | animation | boolean \| AnimationEffectTiming | - | 全局动画配置,详见 [动画](/zh/manual/animation/animation/) | | theme | string \| false | `'light'` | 主题配置,支持 `'light'`、`'dark'` 或自定义主题名 | | layout | LayoutOptions \| LayoutOptions[] | - | 布局配置,详见 [布局](/zh/manual/layout/overview/) | | behaviors | (string \| CustomBehaviorOption)[] | - | 交互行为配置,详见 [交互](/zh/manual/behavior/overview/) | | plugins | (string \| CustomPluginOption)[] | - | 插件配置,详见 [插件](/zh/manual/plugin/overview/) | | transforms | TransformOptions | - | 数据转换器配置,详见 [数据转换器](/zh/manual/transform/overview/) | ## 图属性 图实例提供了一些只读属性,用于获取图的状态信息: | 属性 | 类型 | 描述 | | --------- | ------- | ------------------------ | | destroyed | boolean | 当前图实例是否已被销毁 | | rendered | boolean | 当前图实例是否已完成渲染 | ## 参考示例 ### 完整的创建和配置示例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 200, width: 300, height: 200, padding: 30, autoResize: true, // 视口配置 zoom: 0.8, autoFit: 'view', padding: 20, // 主题配置 theme: 'dark', // 节点配置 node: { style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, }, }, // 边配置 edge: { style: { stroke: '#A4D3EE', lineWidth: 1.5, endArrow: true, }, }, // 布局配置 layout: { type: 'force', preventOverlap: true, linkDistance: 100, }, // 交互行为 behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], // 初始数据 data: { nodes: [ { id: 'node1', data: { label: '节点1' } }, { id: 'node2', data: { label: '节点2' } }, ], edges: [{ source: 'node1', target: 'node2', data: { label: '关系' } }], }, }); graph.render(); ``` ```typescript import { Graph } from '@antv/g6'; // 创建图实例 const graph = new Graph({ // 基础配置 container: 'container', width: 300, height: 200, padding: 30, autoResize: true, // 视口配置 zoom: 0.8, autoFit: 'view', padding: 20, // 主题配置 theme: 'dark', // 节点配置 node: { style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, }, }, // 边配置 edge: { style: { stroke: '#A4D3EE', lineWidth: 1.5, endArrow: true, }, }, // 布局配置 layout: { type: 'force', preventOverlap: true, linkDistance: 100, }, // 交互行为 behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], // 初始数据 data: { nodes: [ { id: 'node1', data: { label: '节点1' } }, { id: 'node2', data: { label: '节点2' } }, ], edges: [{ source: 'node1', target: 'node2', data: { label: '关系' } }], }, }); // 渲染图 graph.render(); ``` - 要了解如何快速创建一个图,请参考[快速上手](/zh/manual/getting-started/quick-start/)。 - 要深入了解配置项中个部分的概念,请阅读本章节的其他内容。 #### Options 配置项 - Canonical page: https://g6.antv.antgroup.com/zh/manual/graph/option/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/graph/option.md - Description: Options 配置项 --- title: "Options 配置项" description: "Options 配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/graph/option/" version: "5.1.1" --- ## autoFit > _{ type: 'view'; options?: [FitViewOptions](#fitviewoptions); animation?: [ViewportAnimationEffectTiming](#viewportanimationeffecttiming); } \| { type: 'center'; animation?: [ViewportAnimationEffectTiming](#viewportanimationeffecttiming); } \| 'view' \| 'center'_ 是否自动适应画布。⚠️ **注意**:每次执行 `render` 时,都会根据 `autoFit` 进行自适应。 两种基本自适应模式: - `'view'` - 自动缩放,确保所有内容都在视图内可见 - `'center'` - 内容居中显示,但不改变缩放比例 还可通过对象形式实现更精细的自适应控制: ```javascript const graph = new Graph({ autoFit: { type: 'view', // 自适应类型:'view' 或 'center' options: { // 仅适用于 'view' 类型 when: 'overflow', // 何时适配:'overflow'(仅当内容溢出时) 或 'always'(总是适配) direction: 'x', // 适配方向:'x'、'y' 或 'both' }, animation: { // 自适应动画效果 duration: 1000, // 动画持续时间(毫秒) easing: 'ease-in-out', // 动画缓动函数 }, }, }); ``` #### FitViewOptions | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------------------------------------------------------------------------- | -------------------------- | ---------- | ---- | | when | 在以下情况下进行适配
- `'overflow'` 仅当图内容超出视口时进行适配
- `'always'` 总是进行适配 | `'overflow`' \| `'always'` | `'always'` | | | direction | 仅对指定方向进行适配
- `'x'` 仅适配 x 方向
- `'y'` 仅适配 y 方向
- `'both'` 适配 x 和 y 方向 | `'x`' \| `'y`' \| `'both'` | `'both'` | | #### ViewportAnimationEffectTiming ```typescript type ViewportAnimationEffectTiming = | boolean // true 启用默认动画,false 禁用动画 | { easing?: string; // 动画缓动函数:'ease-in-out'、'ease-in'、'ease-out'、'linear' duration?: number; // 动画持续时间(毫秒) }; ``` ## autoResize > _boolean_ **默认值:** `false` 是否自动调整画布大小。 基于 `window.onresize` 事件实现。当浏览器窗口大小变化时,画布将自动调整大小以适应容器。 ## background > _string_ 画布背景色。 该颜色作为导出图片时的背景色。可以使用任何有效的 CSS 颜色值,如十六进制、RGB、RGBA 等。 ## canvas > [CanvasConfig](#canvasconfig) 画布配置。GraphOptions 下相关配置项(如 `container`、`width`、`height`、`devicePixelRatio`、`background`、`cursor`)为快捷配置项,会被转换为 canvas 配置项。 #### CanvasConfig | 属性 | 描述 | 类型 | 默认值 | 必填 | | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------ | ------ | ---- | | container | 画布容器 | string \| HTMLElement | - | | | devicePixelRatio | 设备像素比 | number | - | | | width | 画布宽度 | number | - | | | height | 画布高度 | number | - | | | cursor | 指针样式,与 [GraphOptions.cursor](#cursor) 配置相同 | string | - | | | background | 画布背景色 | string | - | | | renderer | 渲染器,与 [GraphOptions.renderer](#renderer) 配置相同 | (layer: `'background'` \| `'main'` \| `'label'` \| `'transient'`) => IRenderer | - | | | enableMultiLayer | 是否启用多图层。非动态参数,仅在初始化时生效 | boolean | - | | ## container > _string \|_ _HTMLElement_ _\|_ Canvas 画布容器,可以是以下三种赋值之一: - DOM 元素的 ID 字符串,如 `'container'` - HTML 元素对象,如 `document.getElementById('container')` - Canvas 实例,如 `new Canvas(options)`,其中 `options` 为 [CanvasConfig](#canvasconfig) 类型。 ## cursor > string 指针样式,控制鼠标悬停在画布上时的光标形状。可以使用任何有效的 CSS cursor 值。 支持的值有: `'auto'`、`'default'`、`'none'`、`'context-menu'`、`'help'`、`'pointer'`、`'progress'`、`'wait'`、`'cell'`、`'crosshair'`、`'text'`、`'vertical-text'`、`'alias'`、`'copy'`、`'move'`、`'no-drop'`、`'not-allowed'`、`'grab'`、`'grabbing'`、`'all-scroll'`、`'col-resize'`、`'row-resize'`、`'n-resize'`、`'e-resize'`、`'s-resize'`、`'w-resize'`、`'ne-resize'`、`'nw-resize'`、`'se-resize'`、`'sw-resize'`、`'ew-resize'`、`'ns-resize'`、`'nesw-resize'`、`'nwse-resize'`、`'zoom-in'`、`'zoom-out'`。 这里的 Cursor 值参考 [MDN - cursor](https://developer.mozilla.org/zh-CN/docs/Web/CSS/cursor)。 ## devicePixelRatio > _number_ 设备像素比。 用于高清屏的设备像素比,默认为 [window.devicePixelRatio](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/devicePixelRatio)。 ## width > _number_ 画布宽度。如果未设置,则会自动获取容器宽度。 ## height > _number_ 画布高度。如果未设置,则会自动获取容器高度。 ## renderer > _(layer: 'background' \| 'main' \| 'label' \| 'transient') =>_ _IRenderer_ 手动指定渲染器 G6 采用了分层渲染的方式,分为 `background`、`main`、`label`、`transient` 四层,用户可以通过该配置项分别设置每层画布的渲染器。 **示例**: 使用 SVG 渲染器进行渲染 ```javascript import { Renderer as SVGRenderer } from '@antv/g-svg'; import { Graph } from '@antv/g6'; const graph = new Graph({ renderer: () => new SVGRenderer(), }); ``` ## padding > _number \| number[]_ 画布内边距 通常在自适应时,会根据内边距进行适配。可以是单个数值(四边相同)或者数组形式(按顺序指定上、右、下、左的内边距)。 **示例:** ```javascript // 单个数值 const graph1 = new Graph({ padding: 20, // 四边均为 20 像素的内边距 }); // 数组形式 const graph2 = new Graph({ padding: [20, 40, 20, 40], // 上、右、下、左的内边距 }); ``` ## rotation > _number_ **默认值:** `0` 旋转角度(以弧度为单位) ## x > _number_ 视口 x 坐标,设置视口的初始水平位置。 ## y > _number_ 视口 y 坐标,设置视口的初始垂直位置。 ## zoom > _number_ **默认值:** `1` 设置视口的初始缩放级别,1 表示 100%(原始大小)。 ## zoomRange > _[number, number]_ **默认值:** `[0.01, 10]` 缩放范围,限制用户可以缩放的最小和最大比例。 ## animation > _boolean \| [AnimationEffectTiming](#animationeffecttiming)_ 启用或关闭全局动画 为动画配置项时,会启用动画,并将该动画配置作为全局动画的基础配置。 #### AnimationEffectTiming | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------- | -------------------- | ------------------------------------------------------------------- | ----------- | ---- | | delay | 动画延迟时间 | number | - | | | direction | 动画方向 | `'alternate'` \| `'alternate-reverse'` \| `'normal'` \| `'reverse'` | `'forward'` | | | duration | 动画持续时间 | number | - | | | easing | 动画缓动函数 | string | - | | | fill | 动画结束后的填充模式 | `'auto'` \| `'backwards'` \| `'both'` \| `'forwards'` \| `'none'` | `'none'` | | | iterations | 动画迭代次数 | number | - | | **示例:** ```javascript // 简单启用 const graph1 = new Graph({ animation: true, }); // 详细配置 const graph2 = new Graph({ animation: { duration: 500, // 动画持续时间(毫秒) easing: 'ease-in-out', // 缓动函数 }, }); ``` ## data > [GraphData](#graphdata) 数据。 #### GraphData | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------- | ------------------------- | ------ | ---- | | nodes | 节点数据 | [NodeData](#nodedata)[] | - | ✓ | | edges | 边数据 | [EdgeData](#edgedata)[] | - | ✓ | | combos | 组合数据 | [ComboData](#combodata)[] | - | ✓ | #### NodeData | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------- | -------------------------------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 节点的唯一标识符,用于区分不同的节点 | string | - | ✓ | | type | 节点类型,内置节点类型名称或者自定义节点的名称 | string | - | | | data | 节点数据,用于存储节点的自定义数据,例如节点的名称、描述等。可以在样式映射中通过回调函数获取 | object | - | | | style | 节点样式,包括位置、大小、颜色等视觉属性 | object | - | | | states | 节点初始状态,如选中、激活、悬停等 | string[] | - | | | combo | 所属的组合 ID,用于组织节点的层级关系,如果没有则为 null | string \| null | - | | | children | 子节点 ID 集合,仅在树图场景下使用 | string[] | - | | #### EdgeData | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | ---------------------------------------------------------------- | -------- | ------ | ---- | | source | 边起始节点 ID | string | - | ✓ | | target | 边目标节点 ID | string | - | ✓ | | id | 边的唯一标识符 | string | - | | | type | 边类型,内置边类型名称或者自定义边的名称 | string | - | | | data | 边数据,用于存储边的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 边样式,包括线条颜色、宽度、箭头等视觉属性 | object | - | | | states | 边初始状态 | string[] | - | | #### ComboData | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 组合的唯一标识符 | string | - | ✓ | | type | 组合类型,内置组合类型名称或者自定义组合名称 | string | - | | | data | 组合数据,用于存储组合的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 组合样式 | object | - | | | states | 组合初始状态 | string[] | - | | | combo | 组合的父组合 ID。如果没有父组合,则为 null | string \| null | - | | **示例:** ```javascript const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 } }, { id: 'node2', style: { x: 200, y: 200 } }, ], edges: [{ id: 'edge1', source: 'node1', target: 'node2' }], combos: [{ id: 'combo1', style: { x: 150, y: 150 } }], }, }); ``` - 阅读 [数据](/zh/manual/data/) 深入了解图数据,包括不限于数据格式、如何操作数据等。 ## node > [NodeOptions](#nodeoptions) 节点配置项。 #### NodeOptions | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------- | ----------------------------------------------------- | -------- | ---- | | type | 节点类型,内置节点类型名称或自定义节点的名称 | [Type](/zh/manual/element/node/BaseNode/#type) | `circle` | | | style | 节点样式,包括颜色、大小等 | [Style](/zh/manual/element/node/BaseNode/#style) | - | | | state | 定义节点在不同状态下的样式 | [State](/zh/manual/element/node/BaseNode/#state) | - | | | palette | 定义节点的色板,用于根据不同数据映射颜色 | [Palette](/zh/manual/element/node/BaseNode/#palette) | - | | | animation | 定义节点的动画效果 | [Animation](/zh/manual/element/node/BaseNode/#animation) | - | | 详见 [Node](/zh/manual/element/node/BaseNode/) **示例:** ```javascript const graph = new Graph({ node: { type: 'circle', // 节点类型 style: { fill: '#e6f7ff', // 填充色 stroke: '#91d5ff', // 边框色 lineWidth: 1, // 边框宽度 r: 20, // 半径 labelText: (d) => d.id, // 标签文本 }, // 节点状态样式 state: { hover: { lineWidth: 2, stroke: '#69c0ff', }, selected: { fill: '#bae7ff', stroke: '#1890ff', lineWidth: 2, }, }, }, }); ``` ## edge > [EdgeOptions](#edgeoptions) 边配置项 #### EdgeOptions | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------- | ----------------------------------------------------- | ------ | ---- | | type | 边类型,内置边类型名称或自定义边的名称 | [Type](/zh/manual/element/edge/BaseEdge/#type) | `line` | | | style | 边样式,包括颜色、大小等 | [Style](/zh/manual/element/edge/BaseEdge/#style) | - | | | state | 定义边在不同状态下的样式 | [State](/zh/manual/element/edge/BaseEdge/#state) | - | | | palette | 定义边的色板,用于根据不同数据映射颜色 | [Palette](/zh/manual/element/edge/BaseEdge/#palette) | - | | | animation | 定义边的动画效果 | [Animation](/zh/manual/element/edge/BaseEdge/#animation) | - | | 详见 [Edge](/zh/manual/element/edge/BaseEdge/) **示例:** ```javascript const graph = new Graph({ edge: { type: 'polyline', // 边类型 style: { stroke: '#91d5ff', // 边的颜色 lineWidth: 2, // 边的宽度 endArrow: true, // 是否有箭头 }, // 边的状态样式 state: { selected: { stroke: '#1890ff', lineWidth: 3, }, }, }, }); ``` ## combo > [ComboOptions](#combooptions) 组合配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------- | ------------------------------------------------------- | -------- | ---- | | type | 组合类型,内置组合类型名称或自定义组合的名称 | [Type](/zh/manual/element/combo/BaseCombo/#type) | `circle` | | | style | 组合样式,包括颜色、大小等 | [Style](/zh/manual/element/combo/BaseCombo/#style) | - | | | state | 定义组合在不同状态下的样式 | [State](/zh/manual/element/combo/BaseCombo/#state) | - | | | palette | 定义组合的色板,用于根据不同数据映射颜色 | [Palette](/zh/manual/element/combo/BaseCombo/#palette) | - | | | animation | 定义组合的动画效果 | [Animation](/zh/manual/element/combo/BaseCombo/#animation) | - | | 详见 [Combo](/zh/manual/element/combo/BaseCombo/) **示例:** ```javascript const graph = new Graph({ combo: { type: 'circle', // 组合类型 style: { fill: '#f0f0f0', // 背景色 stroke: '#d9d9d9', // 边框色 lineWidth: 1, // 边框宽度 }, // 组合状态样式 state: { selected: { stroke: '#1890ff', lineWidth: 2, }, }, }, }); ``` ## layout > _CustomLayoutOptions \| CustomLayoutOptions[]_ 布局配置项,可以是对象(普通布局)或数组(流水线布局)。 **示例**: ```javascript const graph = new Graph({ container: 'container', layout: { type: 'force', // 力导向布局 preventOverlap: true, // 防止节点重叠 nodeStrength: -50, // 节点之间的斥力 edgeStrength: 0.5, // 边的弹性系数 iterations: 200, // 迭代次数 animation: true, // 启用布局动画 }, }); ``` ## theme > _false \| 'light' \| 'dark' \| string_ 设置图表的主题,可以是内置的 `'light'`、`'dark'` 主题,也可以是自定义主题的名称。设为 `false` 则不使用任何主题。 ## behaviors > _(string \| [CustomExtensionOptions](#customextensionoptions) \| ((this:Graph) =>CustomExtensionOptions))[]_ 配置图表的交互行为,可以是字符串(使用默认配置)、对象(自定义配置)或函数(动态配置、函数内可访问图实例)。 **示例:** ```javascript const graph = new Graph({ behaviors: [ 'drag-canvas', // 使用默认配置启用画布拖拽 'zoom-canvas', // 使用默认配置启用画布缩放 { type: 'drag-element', // 自定义配置拖拽元素 key: 'drag-node-only', enable: (event) => event.targetType === 'node', // 只允许拖拽节点 }, function () { console.log(this); // 输出 graph 实例 return { type: 'hover-activate', }; }, ], }); ``` - 查看 [交互总览](/zh/manual/behavior/overview/) 深入了解交互原理 - 浏览 [内置交互](/zh/manual/behavior/AutoAdaptLabel/) 获取所有内置交互列表及其配置选项 ## plugins > _(string \| [CustomExtensionOptions](#customextensionoptions) \| ((this:Graph) =>CustomExtensionOptions))[]_ 设置图表的插件,可以是字符串(使用默认配置)、对象(自定义配置)或函数(动态配置、函数内可访问图实例)。 **示例:** ```javascript const graph = new Graph({ container: 'container', plugins: [ 'minimap', // 启用小地图,使用默认配置 { type: 'grid', // 启用网格背景 key: 'grid-plugin', line: { stroke: '#d9d9d9', lineWidth: 1, }, }, { type: 'toolbar', // 启用工具栏 key: 'graph-toolbar', position: 'top-right', // 位置 }, ], }); ``` - 查看 [插件总览](/zh/manual/plugin/overview/) 深入了解插件原理 - 浏览 [内置插件](/zh/manual/plugin/Background/) 获取所有内置插件列表及其配置项 ## transforms > _(string \| [CustomExtensionOptions](#customextensionoptions) \| ((this:Graph) =>CustomExtensionOptions))[]_ 配置数据处理,用于在渲染前对数据进行处理,不会影响原始数据。可以是字符串(使用默认配置)、对象(自定义配置)或函数(动态配置、函数内可访问图实例)。 **示例:** ```javascript const graph = new Graph({ transforms: [ 'process-parallel-edges', // 处理平行边,使用默认配置 { type: 'map-node-size', // 根据节点数据映射节点大小 field: 'value', // 使用 value 字段的值 max: 50, // 最大半径 min: 20, // 最小半径 }, ], }); ``` - 查看 [数据处理总览](/zh/manual/transform/overview/) 深入了解数据处理原理 - 浏览 [内置数据处理](/zh/manual/transform/MapNodeSize/) 获取所有内置数据处理列表及其配置项 #### CustomExtensionOptions ```typescript interface CustomExtensionOption extends Record { /** 拓展类型 */ type: string; /** 拓展 key,即唯一标识 */ key?: string; } ``` #### 简介 - Canonical page: https://g6.antv.antgroup.com/zh/manual/introduction/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/introduction.md - Description: 简介 --- title: "简介" description: "简介" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/introduction/" version: "5.1.1" --- ![](https://user-images.githubusercontent.com/6113694/45008751-ea465300-b036-11e8-8e2a-166cbb338ce2.png) [![Build Status](https://github.com/antvis/g6/workflows/build/badge.svg?branch=v5)](https://github.com/antvis//actions) [![Coverage Status](https://img.shields.io/coveralls/github/antvis/G6/v5.svg)](https://coveralls.io/github/antvis/G6?branch=v5) ![typescript](https://img.shields.io/badge/language-typescript-red.svg) ![MIT](https://img.shields.io/badge/license-MIT-000000.svg) [![npm package](https://img.shields.io/npm/v/@antv/g6.svg)](https://www.npmjs.com/package/@antv/g6) [![NPM downloads](http://img.shields.io/npm/dm/@antv/g6.svg)](https://npmjs.org/package/@antv/g6) [![Percentage of issues still open](http://isitmaintained.com/badge/open/antvis/g6.svg)](http://isitmaintained.com/project/antvis/g6 'Percentage of issues still open')

AntV G6

G6 是一个图可视化引擎。它提供了图的绘制、布局、分析、交互、动画等图可视化能力。旨在为开发者提供一套简单易用、专业可靠、可高度定制的图可视化开发工具

丰富元素

内置 10+ 元素,满足常规场景需求

灵活交互

内置 10+ 交互,并可根据不同场景自由组合

高性能布局算法

高性能布局,内置 10+ 常用的图布局,支持 WebGPU、 WASM 计算加速

多色主题,适用多种场景

3D 场景

支持 3D 元素、布局,打造沉浸式的图可视化场景

高可定制性

元素、布局、交互、插件统统可定制,实现你的每一个创意

仅需 3 分钟,开启 G6 之旅

点击进入👉 快速开始

#### 布局总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/overview.md - Description: 布局总览 --- title: "布局总览" description: "布局总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/overview/" version: "5.1.1" --- ## 概述 图布局是指将图中的元素按照一定的规则进行排列的过程,例如基于电荷弹性模型的力导向布局、逐次排布的网格布局、基于层次结构的树布局等。 ## 布局类型 G6 提供了多种布局算法,用户可以根据自己的需求选择合适的布局算法: - [AntVDagreLayout](/zh/manual/layout/AntvDagreLayout/):基于 dagre 定制的布局 - [CircularLayout](/zh/manual/layout/CircularLayout/):环形布局 - [ComboCombinedLayout](/zh/manual/layout/ComboCombinedLayout/):适用于存在组合的布局 - [ConcentricLayout](/zh/manual/layout/ConcentricLayout/):同心圆布局 - [D3Force3DLayout](/zh/manual/layout/D3Force3DLayout/):[3D 力导向](https://github.com/vasturiano/d3-force-3d)布局 - [D3ForceLayout](/zh/manual/layout/D3ForceLayout/):基于 [D3](https://d3js.org/d3-force) 的力导向布局 - [DagreLayout](/zh/manual/layout/DagreLayout/):[dagre](https://github.com/dagrejs/dagre) 布局 - [FishboneLayout](/zh/manual/layout/Fishbone/):鱼骨布局 - [ForceAtlas2Layout](/zh/manual/layout/ForceAtlas2Layout/):[ForceAtlas2](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0098679) 布局 - [ForceLayout](/zh/manual/layout/ForceLayout/):力导向布局 - [FruchtermanLayout](/zh/manual/layout/FruchtermanLayout/):[Fruchterman](https://www.sciencedirect.com/topics/computer-science/reingold-layout) 布局 - [GridLayout](/zh/manual/layout/GridLayout/):网格布局 - [MDSLayout](/zh/manual/layout/MdsLayout/):高维数据降维算法布局 - [RadialLayout](/zh/manual/layout/RadialLayout/):径向布局 - [RandomLayout](/zh/manual/layout/RandomLayout/):随机布局 - [SnakeLayout](/zh/manual/layout/Snake/):蛇形布局 - [CompactBoxLayout](/zh/manual/layout/CompactBoxLayout/): 紧凑树布局 - [DendrogramLayout](/zh/manual/layout/DendrogramLayout/): 树状布局 - [MindmapLayout](/zh/manual/layout/MindmapLayout/): 思维导图布局 - [IndentedLayout](/zh/manual/layout/IndentedLayout/): 缩进树布局 其中 `CompactBox Layout`、`Dendrogram Layout`、`Mindmap Layout`、`Indented Layout` 是树布局的一种,适用于树状结构的图。 ## 注册布局 你可以直接使用内置布局,如果想要使用其他布局,需要先进行注册: ```typescript import { register, ExtensionCategory } from '@antv/g6'; import { CustomLayout } from 'package-name/or/path-to-your-custom-layout'; register(ExtensionCategory.LAYOUT, 'custom-layout', CustomLayout); ``` ## 配置布局 通过 `layout` 配置项可以指定图的布局算法,例如: ```typescript { layout: { // 指定要使用的布局算法 type: 'force', // 布局算法的配置项 gravity: 10 // ... } } ``` 也可在图实例化之后使用 `graph.setLayout` 来更新布局配置。 5.1 开始,布局文档中的通用字段已与 `@antvis/layout` 对齐。除了各布局自己的算法参数外,也建议同时关注 `width`、`height`、`center`、`enableWorker`、`node`、`edge` 等公共配置。 ## 布局加速 G6 对一些布局算法提供了加速版本,包括:在 Web Worker 中执行布局算法、提供 [WASM](https://webassembly.org/) 版本的布局算法、GPU 加速的布局算法等。可按照下列方式使用: ### 在 Web Worker 中执行布局算法 除树布局外,G6 的所有内置布局算法都支持在 Web Worker 中执行。只需将 `enableWorker` 设置为 `true` 即可: ```typescript { layout: { type: 'force', enableWorker: true, // ... } } ``` ### 使用 WASM 版本布局算法 目前支持 WASM 版本的布局算法有:`Fruchterman Layout` `ForceAtlas Layout` `Force Layout` `Dagre Layout`。 首先安装 `@antv/layout-wasm`: ```bash npm install @antv/layout-wasm --save ``` 引入并注册布局算法: ```typescript import { register, Graph, ExtensionCategory } from '@antv/g6'; import { FruchtermanLayout, initThreads, supportsThreads } from '@antv/layout-wasm'; register(ExtensionCategory.LAYOUT, 'fruchterman-wasm', FruchtermanLayout); ``` 初始化线程: ```typescript const supported = await supportsThreads(); const threads = await initThreads(supported); ``` 初始化图并传入布局配置: ```typescript const graph = new Graph({ // ... 其他配置 layout: { type: 'fruchterman-wasm', threads, // ... 其他配置 }, }); ``` ### 使用 GPU 加速布局 目前支持 GPU 加速的布局算法有:`Fruchterman Layout` `GForce Layout`。 首先安装 `@antv/layout-gpu`: ```bash npm install @antv/layout-gpu --save ``` 引入并注册布局算法: ```typescript import { register, Graph, ExtensionCategory } from '@antv/g6'; import { FruchtermanLayout } from '@antv/layout-gpu'; register(ExtensionCategory.LAYOUT, 'fruchterman-gpu', FruchtermanLayout); ``` 初始化图并传入布局配置: ```typescript const graph = new Graph({ // ... 其他配置 layout: { type: 'fruchterman-gpu', // ... 其他配置 }, }); ``` ## 执行布局 通常,在调用 `graph.render()` 后,G6 会自动执行布局算法。 如果需要手动执行布局算法,G6 提供了以下 API: - [layout](/zh/api/layout/#graphlayoutlayoutoptions):执行布局算法 - [setLayout](/zh/api/layout/#graphsetlayoutlayout):设置布局算法 - [stopLayout](/zh/api/layout/#graphstoplayout):停止布局算法 ## 自定义布局 如果内置布局算法无法满足需求,可以自定义布局算法,具体请参考[自定义布局](/zh/manual/layout/custom-layout/)。 如果你正在从 G6 `5.0` 的布局配置迁移到 `5.1`,可继续阅读 [从 5.0 升级到 5.1(布局)](/zh/manual/whats-new/upgrade-to-5-1/)。 #### 插件总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/overview.md - Description: 插件总览 --- title: "插件总览" description: "插件总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/overview/" version: "5.1.1" --- ## 什么是插件 插件(Plugin)是 G6 中最灵活的扩展机制,用户可以通过插件来扩展 G6 的功能,例如在画布中额外挂载图形组件、实现撤销重做等功能。 绝大多数的定制需求都可以通过插件来实现,G6 内置了一些常用的插件,例如:[Tooltip](/zh/manual/plugin/Tooltip/)、[Grid](/zh/manual/plugin/GridLine/)、[History](/zh/manual/plugin/History/)。 ## 内置插件 G6 提供了丰富的内置插件,涵盖多种常见功能场景: | 分类 | 插件名称 | 注册类型 | 功能描述 | | ---------------- | ------------------------------------------------------------------------------------------ | ------------------ | -------------------------------------- | | **视觉样式增强** | | | | | | [网格线](/zh/manual/plugin/GridLine/) | `grid-line` | 在画布上显示网格参考线 | | | [背景](/zh/manual/plugin/Background/) | `background` | 为画布添加背景图片或颜色 | | | [水印](/zh/manual/plugin/Watermark/) | `watermark` | 为画布添加水印,保护版权 | | | [轮廓包围](/zh/manual/plugin/Hull/) | `hull` | 为指定节点集合创建轮廓 | | | [气泡集](/zh/manual/plugin/BubbleSets/) | `bubble-sets` | 创建平滑气泡状的元素集合轮廓 | | | [对齐线](/zh/manual/plugin/Snapline/) | `snapline` | 拖动元素时显示对齐参考线 | | **导航与概览** | | | | | | [缩略图](/zh/manual/plugin/Minimap/) | `minimap` | 显示图的缩略预览,支持导航 | | | [全屏](/zh/manual/plugin/Fullscreen/) | `fullscreen` | 支持图表全屏显示和退出 | | | [时间轴](/zh/manual/plugin/Timebar/) | `timebar` | 提供时序数据的筛选和播放控制 | | **交互控件** | | | | | | [工具栏](/zh/manual/plugin/Toolbar/) | `toolbar` | 提供常用操作按钮集合 | | | [上下文菜单](/zh/manual/plugin/Contextmenu/) | `contextmenu` | 右键点击时显示可选操作菜单 | | | [提示框](/zh/manual/plugin/Tooltip/) | `tooltip` | 悬停时显示元素详细信息 | | | [图例](/zh/manual/plugin/Legend/) | `legend` | 显示图表数据的类别和对应样式说明 | | **数据探索** | | | | | | [鱼眼放大镜](/zh/manual/plugin/Fisheye/) | `fisheye` | 提供焦点+上下文的探索体验 | | | [边过滤镜](/zh/manual/plugin/EdgeFilterLens/) | `edge-filter-lens` | 在指定区域内筛选显示边 | | | [边绑定](/zh/manual/plugin/EdgeBundling/) | `edge-bundling` | 将相似路径的边捆绑在一起,减少视觉混乱 | | **高级功能** | | | | | | [历史记录](/zh/manual/plugin/History/) | `history` | 支持撤销/重做操作 | | | [相机设置](https://github.com/antvis/G6/blob/v5/packages/g6/src/plugins/camera-setting.ts) | `camera-setting` | 配置3D场景下的相机参数 | 各插件的详细配置可参考 [内置插件文档](/zh/manual/plugin/GridLine/)。 ## 配置方式 ### 基本配置 在图实例初始化时,通过 `plugins` 数组指定需要的插件: ```javascript {}5 import { Graph } from '@antv/g6'; const graph = new Graph({ // 其他配置... plugins: ['grid', 'minimap', 'tooltip'], }); ``` ### 配置插件参数 对于需要自定义参数的插件,可以使用 `object` 形式配置属性: ```javascript {5-9} const graph = new Graph({ // 其他配置... plugins: [ 'grid', { type: 'tooltip', key: 'my-tooltip', // 为插件指定key,便于后续更新 getContent: (e) => `
节点:${e.target.id}
`, }, ], }); ``` ### 动态更新插件 G6 支持在图实例运行期间动态管理插件,满足复杂交互需求: 通过 [getPlugins](/zh/api/plugin/#graphgetplugins) 方法获取当前插件列表: ```javascript // 获取插件列表 const plugins = graph.getPlugins(); // console.log(plugins) 👉 ['minimap', 'grid'] ``` 可以通过 [setPlugins](/zh/api/plugin/#graphsetpluginsplugins) 方法调整插件: ```javascript // 添加新插件 graph.setPlugins((plugins) => [...plugins, 'minimap']); // 移除插件 graph.setPlugins((plugins) => plugins.filter((p) => p !== 'grid')); ``` 可以通过 [updatePlugin](/zh/api/plugin/#graphupdatepluginplugin) 方法更新插件的配置: ```javascript {6,14} const graph = new Graph({ // 其他配置... plugins: [ { type: 'tooltip', key: 'my-tooltip', getContent: (e) => `
节点:${e.target.id}
`, }, ], }); // 更新单个插件 graph.updatePlugin({ key: 'my-tooltip', getContent: (e) => `
更新的内容:${e.target.id}
`, }); ``` :::warning{title=注意} 使用 `updatePlugin` 方法时,需要在初始化时为插件指定唯一的 `key`。 ::: ### 卸载插件 使用 [setPlugins](/zh/api/plugin/#graphsetpluginsplugins) 方法同样可以卸载插件,将插件配置列表置为空即可: ```javascript // 卸载所有插件 graph.setPlugins([]); ``` ### 调用插件方法 一些插件提供了可供用户调用的 API 方法,例如 `history` 插件提供了 `undo` 和 `redo` 方法,用户可以通过调用这些方法来实现撤销和重做操作。 要调用这些方法,需要先获取到插件实例,可通过 [getPluginInstance](/zh/api/plugin/#graphgetplugininstancekey) 方法获取: ```javascript // 配置插件 const graph = new Graph({ plugins: [{ type: 'history', key: 'my-history' }], }); // 获取插件实例 const history = graph.getPluginInstance('my-history'); // 调用插件方法 history.undo(); history.redo(); ``` :::warning{title=注意} `graph.getPluginInstance` 方法接收插件 key 值作为参数,因此如果需要获取插件实例,需要将对应插件配置为 `object` 的形式,并传入 `key` 值。 ::: 更多与插件相关的 API 请参考 [插件 API 文档](/zh/api/plugin/)。 ## 自定义插件 当内置插件无法满足需求时,你可以: - 继承和扩展现有插件 - 创建全新的自定义插件 自定义插件需要先注册后使用。详细教程请参考 [自定义插件](/zh/manual/plugin/custom-plugin/) 文档。 ```javascript import { register, ExtensionCategory } from '@antv/g6'; import { MyCustomPlugin } from './my-custom-plugin'; // 注册自定义插件 register(ExtensionCategory.PLUGIN, 'my-custom-plugin', MyCustomPlugin); // 使用自定义插件 const graph = new Graph({ plugins: ['my-custom-plugin'], }); ``` 通过合理组合和配置插件,你可以构建出功能丰富、交互体验出色的图可视化应用。 #### 数据处理总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/transform/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/transform/overview.md - Description: 数据处理总览 --- title: "数据处理总览" description: "数据处理总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/transform/overview/" version: "5.1.1" --- ## 什么是数据处理 数据处理( `transform` ),也叫数据转换器,是 G6 提供的支持在 **渲染前( `beforeDraw` )** 或者 **布局后( `afterLayout` )** 对绘制数据进行转化处理的机制,用户可以通过数据处理很方便地对数据处理逻辑进行封装解耦。 ## 实现原理 ### 基类 所有的数据处理器都是基于 [BaseTransform](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/base-transform.ts) 这个基类进行实现,里面定义了两个基类方法 `beforeDraw` 和 `afterLayout` : ```typescript export abstract class BaseTransform extends BaseExtension { public beforeDraw(data: DrawData, context: DrawContext): DrawData { return data; } public afterLayout(type: 'pre', data: DrawData): void; public afterLayout(type: 'post', data?: undefined): void; public afterLayout(type: 'pre' | 'post', data?: DrawData) {} } ``` 以下是这两个方法里核心的参数类型说明: - **DrawData** ```typescript type ProcedureData = { nodes: Map; edges: Map; combos: Map; }; type DrawData = { add: ProcedureData; // 本次渲染需要新增的元素 update: ProcedureData; // 本次渲染需要更新的元素 remove: ProcedureData; // 本次渲染需要移除的元素 }; ``` - **pre | post** pre:绘制前进行的布局(只会在首次布局触发) post:完成绘制后进行的布局 ### 执行时机 - **beforeDraw** 下面是每次渲染时数据处理的执行流程/时机: **详细说明:** 1. G6 在每次渲染前计算出 `add`、`update`、`remove`,分别对应为需要新增、更新、移除的元素,以下简称为 `DrawData` 2. 此时数据处理介入,按配置顺序执行每个数据处理的 `beforeDraw` 方法,参数则为 `DrawData` 3. 数据处理器中,对 `DrawData` 里面的元素数据进行改动,即可以按需对 `add`、`update`、`remove` 里面的元素数据进行修改、移除或者插入元素数据等,最终把改动后的 `DrawData` 返回给渲染主体逻辑 4. 在执行数据处理后,执行对应的新增、更新、移除元素的操作,完成渲染 :::info{title=提示} 触发渲染的场景分为主动和被动,列举如下: - **主动:** 用户主动调用 `graph.render()` 、 `graph.draw()` 或者在自定义插件、交互等实例里面通过上下文拿到元素控制器( [ElementController](https://github.com/antvis/G6/blob/v5/packages/g6/src/runtime/element.ts) )实例调用 `this.context.element.draw()`,等( `graph.render()` 和 `graph.draw()` 也是调用元素控制器的 `draw` 方法) - **被动:** 部分内置交互和插件有触发渲染,布局执行后也有触发渲染更新元素位置,等 ::: - **afterLayout**:在执行完布局计算并开始更新节点位置后,执行数据处理 ## 内置数据处理 - **G6 提供给用户的内置数据处理如下:** 各数据处理详细配置可参考 [内置数据处理文档](/zh/manual/transform/MapNodeSize/)。 | 数据处理名称 | 注册类型 | 功能描述 | 执行时机 | | --------------------------------------------------- | ------------------------ | ---------------------------------------------------- | ---------- | | [动态调整节点大小](/zh/manual/transform/MapNodeSize/) | `map-node-size` | 根据节点中心性调整节点的大小 | beforeDraw | | [径向标签](/zh/manual/transform/PlaceRadialLabels/) | `place-radial-labels` | 根据径向布局自动调整节点标签样式,包括位置和旋转角度 | afterDraw | | [平行边](/zh/manual/transform/ProcessParallelEdges/) | `process-parallel-edges` | 处理平行边,即多条边共享同一源节点和目标节点 | beforeDraw | - **G6 内嵌的数据处理如下:** 除了提供给用户选用的数据处理外, G6 也封装并使用了以下数据处理机制来实现基础功能。以下数据处理不开放给用户配置使用,默认必带(列举出来供用户有需要时点击查看并参考源码): | 数据处理名称 | 注册类型 | 功能描述 | 执行时机 | | ----------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | [调整combo绘制顺序](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/arrange-draw-order.ts) | `arrange-draw-order` | combo 嵌套时,优先绘制子 combo | beforeDraw | | [处理组合的展开收起](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/collapse-expand-combo.ts) | `collapse-expand-combo` | 收起时,移除 combo 内部元素、销毁内部边,外部边则连到收起的 combo 上;
展开时,反之; | beforeDraw | | [处理(树图)节点的收起和展开](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/collapse-expand-node.ts) | `collapse-expand-node` | 绘制前,处理(树图)节点的收起和展开 | beforeDraw | | [获取边的实际端点](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/get-edge-actual-ends.ts) | `get-edge-actual-ends` | 配合`collapse-expand-combo`实现收起时,combo 外部连到内部节点的边改为连到收起的 combo 上(`collapse-expand-combo`只是在收起时判断并标记了这些边需要更新端点) | beforeDraw | | [更新节点、combo相关边](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/update-related-edge.ts) | `update-related-edges` | 如果更新了节点/combo,则把连接的边也一起更新了 | beforeDraw | :::warning{title=注意} 上面 G6 为实现自身基础功能使用的数据处理仅供参考,不可改动。如有需要在这些数据处理基础上做特殊处理,可通过 [自定义数据处理](#自定义数据处理) 实现。 ::: ## 配置方式 ### 基本配置 在图实例初始化时,通过 `transforms` 数组指定需要的数据处理: ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ // 其他配置... transforms: ['process-parallel-edges'], }); ``` ### 配置数据处理参数 对于需要自定义参数的数据处理,可以使用 `object` 形式配置属性: ```javascript const graph = new Graph({ // 其他配置... transforms: [ 'place-radial-labels', { type: 'process-parallel-edges', key: 'process-parallel-edges-1', mode: 'bundle', distance: 30, }, ], }); ``` ### 动态更新数据处理 G6 支持在图实例运行期间动态管理数据处理: - 可以通过 [setTransforms](/zh/api/transform/#graphsettransformstransforms) 方法调整数据处理器: ```javascript // 添加新的数据处理器 graph.setTransforms((transforms) => [...transforms, 'place-radial-labels']); // 移除数据处理器 graph.setTransforms((transforms) => transforms.filter((t) => t !== 'place-radial-labels')); ``` - 可以通过 [updateTransform](/zh/api/transform/#graphupdatetransformtransform) 方法更新数据处理的配置: ```javascript // 更新单个数据处理器 graph.updateTransform({ key: 'process-parallel-edges-1', distance: 100, }); ``` :::warning{title=注意} 使用`updateTransform`方法时,需要在初始化时为数据处理指定唯一的`key`。 ::: ### 卸载数据处理 使用 [setTransforms](/zh/api/transform/#graphsettransformstransforms) 方法同样可以卸载数据处理,将数据处理配置列表置为空即可: ```javascript // 卸载所有数据处理器 graph.setTransforms([]); ``` ## 自定义数据处理 当内置数据处理器无法满足需求时,你可以: - 继承和扩展现有数据处理 - 创建全新的自定义数据处理 自定义数据处理需要先注册后使用。详细教程请参考 [自定义数据处理](/zh/manual/transform/custom-transform/) 文档。 ```javascript import { register, ExtensionCategory } from '@antv/g6'; import { MyCustomTransform } from './my-custom-transform'; // 注册自定义数据处理器 register(ExtensionCategory.TRANSFORM, 'my-custom-transform', MyCustomTransform); // 使用自定义数据处理 const graph = new Graph({ transforms: ['my-custom-transform'], }); ``` #### 动画总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/animation/animation/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/animation/animation.md - Description: 动画总览 --- title: "动画总览" description: "动画总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/animation/animation/" version: "5.1.1" --- ## 概述 动画是指元素在一段时间内的状态变化,例如节点的位置、大小、颜色等。在 G6 中,动画通常用于增强用户体验,提升图更新过程的连贯性和流畅度。 G6 提供了一套动画范式来描述元素动画,并内置了一些常用的动画效果,用户可以通过配置动画参数来实现不同的动画效果。 一个动画范式的实现如下: ```typescript [ { fields: ['x', 'y'], }, ]; ``` 上述动画范式表示当元素的 `x` 和 `y` 属性发生变化时,会执行动画。 ## 配置动画 G6 中动画配置分为全局配置和局部配置,全局配置主要用于配置全局是否开启动画、动画时长等参数,局部配置主要用于配置元素的动画效果。 ### 关闭全局动画 若要关闭全局动画,可以在实例化 `Graph` 时传入 `animation` 配置项: ```typescript { animation: false, } ``` ### 配置全局动画 如果要启用动画且同时配置动画的默认播放时长,可以传入 `animation` 配置项: ```typescript { animation: { duration: 500, }, } ``` ### 配置元素动画 对于单个元素,可以配置其在不同阶段的动画。例如希望元素在进场和退场时具有淡入淡出效果,可以以如下方式配置: ```typescript { node: { animation: { enter: 'fade', exit: 'fade' } } } ``` 如果希望更新元素位置时是以平移过渡的方式,可以配置如下: ```typescript { node: { animation: { update: 'translate', } } } ``` 如果希望关闭元素的动画,可以配置如下: ```typescript { node: { animation: false, } } ``` ## 动画范式 上一节中提到的动画配置实际上使用了内置的动画范式,本节介绍如何自定义动画范式。 :::info\{title=提示\} 在编写动画范式之前需要了解元素的组成结构,具体请参考[元素](/zh/manual/element/overview/)一节 ::: [元素](/zh/manual/element/overview/)一节中提到:G6 中的元素是由一个或多个原子图形组合而成。因此元素的动画本质上是这些原子图形动画的组合。 因此动画范式是一个数组,用于描述元素中各原子图形的动画效果。对于元素本身来说,其也是一个特殊的复合图形,因此具有基本的图形属性,如 `x`、`y` 等。 因此可以直接为元素本身编写动画范式: ```typescript [ { fields: ['x', 'y'], }, ]; ``` ## 自定义动画 如果内置动画无法满足需求,可以自定义动画,具体请参考[自定义动画](/zh/manual/animation/custom-animation/)。 ## 动画优先级 动画优先级是指全局动画配置和元素动画配置之前的优先级,可以归纳如下: | 全局动画配置 | 局部动画配置 | 是否执行动画 | | ------------ | ------------ | ------------------------------------------------- | | ✅ true | ✅ true | ✅ 执行动画,以默认动画配置执行 | | ✅ true | ❌ false | ❌ 不执行该类元素动画 | | ✅ true | ✅ 配置动画 | ✅ 执行动画,以局部动画配置执行 | | ❌ false | ✅ true | ❌ 不执行任何动画 | | ❌ false | ❌ false | ❌ 不执行任何动画 | | ❌ false | ✅ 配置动画 | ❌ 不执行任何动画 | | ✅ 配置动画 | ✅ true | ✅ 执行动画,以全局动画配置执行 | | ✅ 配置动画 | ✅ 配置动画 | ✅ 执行动画,将局部动画配置覆盖全局动画配置后执行 | | ✅ 配置动画 | ❌ false | ❌ 不执行该类元素动画 | ## 持续动画 如果希望元素具有持续动画,例如节点的波动效果、边的蚂蚁线效果等,可以通过自定义元素方式实现,下面提供一个具有蚂蚁线(Ant Line)动画的边的实现: ```typescript import { Line } from '@antv/g6'; class AntLine extends Line { onCreate() { this.shapeMap.key.animate([{ lineDashOffset: -20 }, { lineDashOffset: 0 }], { duration: 500, iterations: Infinity, }); } } ``` 其中 `onCreate` 是一个生命周期钩子,用于在元素创建时执行动画。 在 options 中配置边样式: ```typescript { edge: { type: 'ant-line', style:{ lineDash: [10, 10] } } } ``` ```ts import { Graph, Line, register } from '@antv/g6'; class AntLine extends Line { onCreate() { this.shapeMap.key.animate([{ lineDashOffset: 20 }, { lineDashOffset: 0 }], { duration: 500, iterations: Infinity, }); } } register('edge', 'ant-line', AntLine); const graph = new Graph({ container: 'container', width: 200, height: 50, data: { nodes: [ { id: 'node-1', style: { x: 25, y: 25 } }, { id: 'node-2', style: { x: 175, y: 25 } }, ], edges: [{ source: 'node-1', target: 'node-2', style: { lineDash: [10, 10] } }], }, edge: { type: 'ant-line', }, }); graph.render(); ``` 其中 `lineDash` 是 `lineDashOffset` 的数组,通过不断变化 `lineDashOffset` 来实现飞线效果。 同样的,还可以实现节点的呼吸效果: ```typescript import { Circle } from '@antv/g6'; class BreathingCircle extends Circle { onCreate() {} } ``` 其中 `lineDashOffset` 是 `lineDash` 的偏移量,通过不断变化 `lineDashOffset` 来实现飞线效果。 同样的,还可以实现节点的呼吸效果: ```typescript import { Circle } from '@antv/g6'; class BreathingCircle extends Circle { onCreate() { this.shapeMap.halo.animate([{ lineWidth: 5 }, { lineWidth: 10 }], { duration: 1000, iterations: Infinity, direction: 'alternate', }); } } ``` 节点样式配置: ```typescript { node: { type: 'breathing-circle', style: { halo: true, haloLineWidth: 5, }, }, } ``` ```ts import { Circle, Graph, register } from '@antv/g6'; class BreathingCircle extends Circle { onCreate() { this.shapeMap.halo.animate([{ lineWidth: 5 }, { lineWidth: 10 }], { duration: 1000, iterations: Infinity, direction: 'alternate', }); } } register('node', 'breathing-circle', BreathingCircle); const graph = new Graph({ container: 'container', width: 50, height: 50, data: { nodes: [{ id: 'node-1', style: { x: 25, y: 25 } }], }, node: { type: 'breathing-circle', style: { halo: true, haloLineWidth: 5, }, }, }); graph.render(); ``` #### 标签自适应显示 AutoAdaptLabel - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/AutoAdaptLabel/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/AutoAdaptLabel.md - Description: 标签自适应显示 AutoAdaptLabel --- title: "标签自适应显示 AutoAdaptLabel" description: "标签自适应显示 AutoAdaptLabel" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/AutoAdaptLabel/" version: "5.1.1" --- ## 概述 标签自适应显示是一种动态标签管理策略,旨在根据当前可视范围的空间分配、节点重要性等因素,智能调整哪些标签应显示或隐藏。通过对可视区域的实时分析,确保用户在不同的交互场景下获得最相关最清晰的信息展示,同时避免视觉过载和信息冗余。 ## 使用场景 这一交互主要用于: - 节点尺寸变化 - 图形缩放 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', style: { x: 200, y: 100, labelText: '短标签' } }, { id: 'node2', style: { x: 360, y: 100, labelText: '中等长度的标签' } }, { id: 'node3', style: { x: 280, y: 220, labelText: '这是一个非常非常长的标签,需要自适应显示' } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node3' }, ], }, node: { style: { label: true, fill: '#7e3feb', labelFill: '#666', labelFontSize: 14, labelPlacement: 'bottom' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: ['zoom-canvas', 'drag-canvas', { key: 'auto-adapt-label', type: 'auto-adapt-label' }], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { const options = { key: 'auto-adapt-label', type: 'auto-adapt-label', animation: true, enable: true, throttle: 100, padding: 0, }; const optionFolder = gui.addFolder('CollapseExpand Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'throttle', 0, 900, 100); optionFolder.add(options, 'padding', 0, 20, 1); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'auto-adapt-label', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互 **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['auto-adapt-label'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'auto-adapt-label', throttle: 200, // 节流时间 padding: 10, // 检测重叠时的额外间距 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ---- | | type | 交互类型名称 | string | `auto-adapt-label` | √ | | enable | 是否启用该交互 | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | throttle | 标签更新节流时间(ms) | number | 100 | | | padding | 标签检测重叠时的额外间距 | number \| number[] | 0 | | | sort | 自定义排序函数,根据元素的重要性从高到低排序,重要性越高的元素其标签显示优先级越高。一般情况下 combo > node > edge | (a: ElementDatum, b: ElementDatum) => -1 \| 0 \| 1 | | | | sortNode | 根据节点的重要性从高到低排序,重要性越高的节点其标签显示优先级越高。内置几种[中心性算法](#nodecentralityoptions),也可以自定义排序函数。需要注意,如果设置了 `sort`,则 `sortNode` 不会生效 | [NodeCentralityOptions](#nodecentralityoptions) \| (nodeA: [NodeData](/zh/manual/data/#节点数据nodedata), nodeB: NodeData => -1 \| 0 \| 1) | `type: 'degree'` | | | sortEdge | 根据边的重要性从高到低排序,重要性越高的边其标签显示优先级越高。默认按照数据先后进行排序。需要注意,如果设置了 `sort`,则 `sortEdge` 不会生效 | (edgeA: [EdgeData](/zh/manual/data/#边数据edgedata), edgeB: EdgeData) => -1 \| 0 \| 1 | | | | sortCombo | 根据群组的重要性从高到低排序,重要性越高的群组其标签显示优先级越高。默认按照数据先后进行排序。需要注意,如果设置了 `sort`,则 `sortCombo` 不会生效 | (comboA: [ComboData](/zh/manual/data/#组合数据combodata), comboB: ComboData) => -1 \| 0 \| 1 | | | ### NodeCentralityOptions 节点中心性的度量方法 - `'degree'`:度中心性,通过节点的度数(连接的边的数量)来衡量其重要性。度中心性高的节点通常具有较多的直接连接,在网络中可能扮演着重要的角色 - `'betweenness'`:介数中心性,通过节点在所有最短路径中出现的次数来衡量其重要性。介数中心性高的节点通常在网络中起到桥梁作用,控制着信息的流动 - `'closeness'`:接近中心性,通过节点到其他所有节点的最短路径长度总和的倒数来衡量其重要性。接近中心性高的节点通常能够更快地到达网络中的其他节点 - `'eigenvector'`:特征向量中心性,通过节点与其他中心节点的连接程度来衡量其重要性。特征向量中心性高的节点通常连接着其他重要节点 - `'pagerank'`:PageRank 中心性,通过节点被其他节点引用的次数来衡量其重要性,常用于有向图。PageRank 中心性高的节点通常在网络中具有较高的影响力,类似于网页排名算法 ```typescript type NodeCentralityOptions = | { type: 'degree'; direction?: 'in' | 'out' | 'both' } | { type: 'betweenness'; directed?: boolean; weightPropertyName?: string } | { type: 'closeness'; directed?: boolean; weightPropertyName?: string } | { type: 'eigenvector'; directed?: boolean } | { type: 'pagerank'; epsilon?: number; linkProb?: number }; ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', style: { x: 200, y: 100, labelText: '短标签' } }, { id: 'node2', style: { x: 360, y: 100, labelText: '中等长度的标签' } }, { id: 'node3', style: { x: 280, y: 220, labelText: '这是一个非常非常长的标签,需要自适应显示' } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node3' }, ], }; const graph = new Graph({ container: 'container', data, behaviors: [ 'zoom-canvas', 'drag-canvas', { key: 'auto-adapt-label', type: 'auto-adapt-label', padding: 0, throttle: 200, }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 组合通用配置项 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/combo/BaseCombo/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/combo/BaseCombo.md - Description: 组合通用配置项 --- title: "组合通用配置项" description: "组合通用配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/combo/BaseCombo/" version: "5.1.1" --- 本文介绍内置组合通用属性配置。 ## ComboOptions ```js {5-9} import { Graph } from '@antv/g6'; const graph = new Graph({ combo: { type: 'circle', // 组合类型 style: {}, // 组合样式 state: {}, // 状态样式 palette: {}, // 色板配置 animation: {}, // 动画配置 }, }); ``` | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------- | ----------------------- | -------- | ---- | | type | 组合类型,内置组合类型名称或自定义组合的名称 | [Type](#type) | `circle` | | | style | 组合样式配置,包括颜色、大小等 | [Style](#style) | - | | | state | 不同状态下的样式配置 | [State](#state) | - | | | palette | 定义组合的色板,用于根据不同数据映射颜色 | [Palette](#palette) | - | | | animation | 定义组合的动画效果 | [Animation](#animation) | - | | ## Type 指定组合类型,内置组合类型名称或自定义组合的名称。默认为 `circle`(圆形)。**⚠️ 注意**:这里决定了主图形的形状。 ```js {3} const graph = new Graph({ combo: { type: 'circle', }, }); ``` **⚠️ 动态配置说明**:`type` 属性同样支持动态配置,可以根据组合数据动态选择组合类型: ```js const graph = new Graph({ combo: { // 静态配置 type: 'circle', // 动态配置 - 箭头函数形式 type: (datum) => datum.data.comboType || 'circle', // 动态配置 - 普通函数形式(可访问 graph 实例) type: function (datum) { console.log(this); // graph 实例 return datum.data.category === 'important' ? 'rect' : 'circle'; }, }, }); ``` 可选值有: - `circle`:[圆形组合](/zh/manual/element/combo/CircleCombo/) - `rect`:[矩形组合](/zh/manual/element/combo/RectCombo/) ## Style 定义组合的样式,包括颜色、大小等。 ```js {3} const graph = new Graph({ combo: { style: {}, }, }); ``` **⚠️ 动态配置说明**:以下所有样式属性都支持动态配置,即可以传入函数来根据组合数据动态计算属性值: ```js const graph = new Graph({ combo: { style: { // 静态配置 fill: '#1783FF', // 动态配置 - 箭头函数形式 stroke: (datum) => (datum.data.isActive ? '#FF0000' : '#000000'), // 动态配置 - 普通函数形式(可访问 graph 实例) lineWidth: function (datum) { console.log(this); // graph 实例 return datum.data.importance > 5 ? 3 : 1; }, // 嵌套属性也支持动态配置 labelText: (datum) => `组合: ${datum.id}`, badges: (datum) => datum.data.tags.map((tag) => ({ text: tag })), }, }, }); ``` 其中 `datum` 参数为组合数据对象 (`ComboData`),包含组合的所有数据信息。 一个完整的组合由以下几部分构成: - `key` :组合的主图形,表示组合的主要形状,例如圆形、矩形等; - `label` :文本标签,通常用于展示组合的名称或描述; - `halo` :主图形周围展示的光晕效果的图形; - `badge` :默认位于组合右上角的徽标; 以下样式配置将按原子图形依次说明: ### 主图形样式 主图形是组合的核心部分,定义了组合的基本形状和外观。以下是常见的配置场景: #### 基础样式配置 设置组合的基本外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { fill: '#5B8FF9', // 蓝色填充 stroke: '#1A1A1A', // 深色描边 lineWidth: 2, fillOpacity: 0.2, }, }, }); graph.render(); ``` #### 透明度和阴影效果 为组合添加透明度和阴影效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { fill: '#61DDAA', fillOpacity: 0.15, shadowColor: 'rgba(97, 221, 170, 0.4)', shadowBlur: 12, shadowOffsetX: 2, shadowOffsetY: 4, stroke: '#F0F0F0', lineWidth: 1, }, }, }); graph.render(); ``` #### 虚线边框样式 创建带虚线边框的组合: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { fill: '#FFF1F0', fillOpacity: 0.1, stroke: '#F5222D', lineWidth: 2, lineDash: [6, 4], lineCap: 'round', }, }, }); graph.render(); ``` 以下为完整的主图形样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------- | --------- | ---- | | collapsed | 当前组合是否折叠 | boolean | false | | | cursor | 组合鼠标移入样式,[配置项](#cursor) | string | default | | | fill | 组合填充色 | string | `#99ADD1` | | | fillOpacity | 组合填充色透明度 | number \| string | 0.04 | | | increasedLineWidthForHitTesting | 当 lineWidth 较小时,可交互区域也随之变小,有时我们想增大这个区域,让"细线"更容易被拾取到 | number | 0 | | | lineCap | 组合描边端点样式 | `round` \| `square` \| `butt` | `butt` | | | lineDash | 组合描边虚线样式 | number[] | - | | | lineDashOffset | 组合描边虚线偏移量 | number | - | | | lineJoin | 组合描边连接处样式 | `round` \| `bevel` \| `miter` | `miter` | | | lineWidth | 组合描边宽度 | number | 1 | | | opacity | 组合透明度 | number \| string | 1 | | | pointerEvents | 组合如何响应指针事件,[配置项](#pointerevents) | string | `auto` | | | shadowBlur | 组合阴影模糊度 | number | - | | | shadowColor | 组合阴影颜色 | string | - | | | shadowOffsetX | 组合阴影在 x 轴方向上的偏移量 | number \| string | - | | | shadowOffsetY | 组合阴影在 y 轴方向上的偏移量 | number \| string | - | | | shadowType | 组合阴影类型 | `inner` \| `outer` | `outer` | | | size | 组合大小,快捷设置组合宽高,[配置项](#size) | number \| number[] | - | | | stroke | 组合描边色 | string | `#99ADD1` | | | strokeOpacity | 组合描边色透明度 | number \| string | 1 | | | transform | transform 属性允许你旋转、缩放、倾斜或平移给定组合 | string | - | | | transformOrigin | 旋转与缩放中心,也称作变换中心 | string | - | | | visibility | 组合是否可见 | `visible` \| `hidden` | `visible` | | | x | 组合 x 坐标 | number | 0 | | | y | 组合 y 坐标 | number | 0 | | | z | 组合 z 坐标 | number | 0 | | | zIndex | 组合渲染层级 | number | 0 | | #### Size 组合大小,快捷设置组合宽高,支持三种配置方式: - number:表示组合宽高相同为指定值 - [number, number]:表示组合宽高分别为数组元素依次表示组合的宽度、高度 - [number, number, number]:表示组合宽高分别为数组元素依次表示组合的宽度、高度以及深度 #### PointerEvents `pointerEvents` 属性控制图形如何响应交互事件,可参考 [MDN 文档](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)。 可选值有:`visible` | `visiblepainted` | `visiblestroke` | `non-transparent-pixel` | `visiblefill` | `visible` | `painted` | `fill` | `stroke` | `all` | `none` | `auto` | `inherit` | `initial` | `unset` 简而言之,`fill`、`stroke` 和 `visibility` 都可以独立或组合影响拾取判定行为。目前支持以下关键词: - **`auto`**:默认值,等同于 `visiblepainted` - **`none`**:永远不会成为响应事件的目标 - **`visiblepainted`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充区域触发同时 `fill` 取非 `none` 的值;或者在图形描边区域触发同时 `stroke` 取非 `none` 的值 - **`visiblefill`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充区域触发,不受 `fill` 取值的影响 - **`visiblestroke`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形描边区域触发,不受 `stroke` 取值的影响 - **`visible`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充或者描边区域触发,不受 `fill` 和 `stroke` 取值的影响 - **`painted`**:满足以下条件才会响应事件: - 在图形填充区域触发同时 `fill` 取非 `none` 的值;或者在图形描边区域触发同时 `stroke` 取非 `none` 的值 - 不受 `visibility` 取值的影响 - **`fill`**:满足以下条件才会响应事件: - 在图形填充区域触发,不受 `fill` 取值的影响 - 不受 `visibility` 取值的影响 - **`stroke`**:满足以下条件才会响应事件: - 在图形描边区域触发,不受 `stroke` 取值的影响 - 不受 `visibility` 取值的影响 - **`all`**:只要进入图形的填充和描边区域就会响应事件,不会受 `fill`、`stroke`、`visibility` 的取值影响 **使用示例:** ```js // 示例1:只有描边区域响应事件 const graph = new Graph({ combo: { style: { fill: 'none', stroke: '#000', lineWidth: 2, pointerEvents: 'stroke', // 只有描边响应事件 }, }, }); // 示例2:完全不响应事件 const graph = new Graph({ combo: { style: { pointerEvents: 'none', // 组合不响应任何事件 }, }, }); ``` #### Cursor 可选值有:`auto` | `default` | `none` | `context-menu` | `help` | `pointer` | `progress` | `wait` | `cell` | `crosshair` | `text` | `vertical-text` | `alias` | `copy` | `move` | `no-drop` | `not-allowed` | `grab` | `grabbing` | `all-scroll` | `col-resize` | `row-resize` | `n-resize` | `e-resize` | `s-resize` | `w-resize` | `ne-resize` | `nw-resize` | `se-resize` | `sw-resize` | `ew-resize` | `ns-resize` | `nesw-resize` | `nwse-resize` | `zoom-in` | `zoom-out` ### 收起时样式 当组合处于收起状态时(`collapsed` 为 `true`),可以为其配置特殊的样式。收起时的样式属性以 `collapsed` 为前缀。 #### 基础收起样式 为收起状态的组合设置不同的外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [ { id: 'node1', combo: 'combo1' }, { id: 'node2', combo: 'combo1' }, ], combos: [{ id: 'combo1', style: { collapsed: true } }], }, combo: { style: { collapsedFill: '#1783FF', collapsedStroke: '#000', collapsedLineWidth: 2, collapsedSize: 40, collapsedMarkerFill: '#fff', collapsedMarkerFontSize: 12, }, }, }); graph.render(); ``` 以下为收起时样式的完整配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------- | ---- | | collapsedCursor | 组合收起时的鼠标移入样式,[配置项](#cursor) | string | 默认与展开时的 cursor 一致 | | | collapsedFill | 组合收起时的填充色 | string | 默认与展开时的 fill 一致 | | | collapsedFillOpacity | 组合收起时的填充色透明度 | number \| string | 1 | | | collapsedIncreasedLineWidthForHitTesting | 组合收起时,当 lineWidth 较小时,可交互区域也随之变小,有时我们想增大这个区域,让"细线"更容易被拾取到 | number | 0 | | | collapsedLineCap | 组合收起时的描边端点样式 | `round` \| `square` \| `butt` | 默认与展开时的 lineCap 一致 | | | collapsedLineDash | 组合收起时的描边虚线样式 | number[] | 默认与展开时的 lineDash 一致 | | | collapsedLineDashOffset | 组合收起时的描边虚线偏移量 | number | 默认与展开时的 lineDashOffset 一致 | | | collapsedLineJoin | 组合收起时的描边连接处样式 | `round` \| `bevel` \| `miter` | 默认与展开时的 lineJoin 一致 | | | collapsedLineWidth | 组合收起时的描边宽度 | number | 默认与展开时的 lineWidth 一致 | | | collapsedMarker | 组合收起时是否显示标记,[配置项](#收起时标记样式) | boolean | true | | | collapsedOpacity | 组合收起时的透明度 | number \| string | 默认与展开时的 opacity 一致 | | | collapsedShadowBlur | 组合收起时的阴影模糊度 | number | 默认与展开时的 shadowBlur 一致 | | | collapsedShadowColor | 组合收起时的阴影颜色 | string | 默认与展开时的 shadowColor 一致 | | | collapsedShadowOffsetX | 组合收起时的阴影在 x 轴方向上的偏移量 | number \| string | 默认与展开时的 shadowOffsetX 一致 | | | collapsedShadowOffsetY | 组合收起时的阴影在 y 轴方向上的偏移量 | number \| string | 默认与展开时的 shadowOffsetY 一致 | | | collapsedShadowType | 组合收起时的阴影类型 | `inner` \| `outer` | 默认与展开时的 shadowType 一致 | | | collapsedSize | 组合收起时的大小 | number \| [number, number] | 32 | | | collapsedStroke | 组合收起时的描边色 | string | 默认与展开时的 stroke 一致 | | | collapsedStrokeOpacity | 组合收起时的描边色透明度 | number \| string | 默认与展开时的 strokeOpacity 一致 | | | collapsedVisibility | 组合收起时是否可见 | `visible` \| `hidden` | 默认与展开时的 visibility 一致 | | ### 收起时标记样式 当 `collapsedMarker` 为 `true` 时显示的标记,用于显示收起组合内包含的元素数量。 #### 自定义标记内容 可以自定义收起标记显示的内容: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [ { id: 'node1', combo: 'combo1' }, { id: 'node2', combo: 'combo1' }, { id: 'node3', combo: 'combo1' }, ], combos: [{ id: 'combo1', style: { collapsed: true } }], }, combo: { style: { collapsedMarkerType: 'child-count', collapsedMarkerFill: '#1783FF', collapsedMarkerFontSize: 14, collapsedMarkerFontWeight: 'bold', }, }, }); graph.render(); ``` 以下为收起时标记样式的完整配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------- | ---- | | collapsedMarkerType | 组合收起时显示的标记类型
- `'child-count'`: 子元素数量(包括 Node 和 Combo)
- `'descendant-count'`: 后代元素数量(包括 Node 和 Combo)
- `'node-count'`: 后代元素数量(只包括 Node)
- `(children: NodeLikeData[]) => string`: 自定义处理逻辑 | `child-count` \| `descendant-count` \| `node-count` \| ((children: NodeData \| ComboData[]) => string) | `child-count` | | | collapsedMarkerFill | 标记文字颜色 | string | #fff | | | collapsedMarkerFillOpacity | 标记文字颜色透明度 | number | 1 | | | collapsedMarkerFontSize | 标记字体大小 | number | 12 | | | collapsedMarkerFontWeight | 标记字体粗细 | number \| string | `normal` | | | collapsedMarkerRadius | 标记圆角半径 | number | 0 | | | collapsedMarkerSrc | 图片来源。其优先级高于 `collapsedMarkerText` | string | - | | | collapsedMarkerText | 标记文字 | string | - | | | collapsedMarkerTextAlign | 标记文字水平对齐方式 | `center` \| `end` \| `left` \| `right` \| `start` | `center` | | | collapsedMarkerTextBaseline | 标记文字对齐基线 | `alphabetic` \| `bottom` \| `hanging` \| `ideographic` \| `middle` \| `top` | `middle` | | | collapsedMarkerWidth | 标记宽度 | number | - | | | collapsedMarkerHeight | 标记高度 | number | - | | | collapsedMarkerZIndex | 标记层级 | number | 1 | | ### 徽标样式 徽标是组合上显示的小标记,通常用于展示状态、数量或其他辅助信息。支持多个徽标同时显示,并可自定义位置。 #### 单个徽标 为组合添加一个简单的徽标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { badges: [ { text: 'NEW' }, // 默认显示在上方 ], }, }, }); graph.render(); ``` #### 多个徽标 为组合添加多个不同位置的徽标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { badge: true, // 是否显示徽标 badges: [ { text: 'A', placement: 'right-top' }, { text: 'Important', placement: 'right' }, { text: 'Notice', placement: 'right-bottom' }, ], badgePalette: ['#7E92B5', '#F4664A', '#FFBE3A'], // 徽标的背景色板 badgeFontSize: 7, // 徽标字体大小 }, }, }); graph.render(); ``` #### 自定义徽标样式 完全自定义徽标的外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { badges: [ { text: '99+', placement: 'right-top', backgroundFill: '#FF4D4F', // 红色背景 fill: '#fff', // 白色文字 fontSize: 10, padding: [2, 6], backgroundRadius: 8, }, ], }, }, }); graph.render(); ``` 以下为完整的徽标样式配置: | 属性 | 描述 | 类型 | 默认值 | | ------------ | ------------------ | ------------------------------------- | --------------------------------- | | badge | 组合是否显示徽标 | boolean | true | | badgePalette | 组合徽标的背景色板 | string[] | [`#7E92B5`, `#F4664A`, `#FFBE3A`] | | badges | 组合徽标设置 | [BadgeStyleProps](#badgestyleprops)[] | - | #### BadgeStyleProps | 属性 | 描述 | 类型 | 默认值 | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | | background | 组合徽标是否显示背景 | boolean | true | | backgroundCursor | 组合徽标背景鼠标移入样式,[配置项](#cursor) | string | `default` | | backgroundFill | 组合徽标背景填充色。若不指定,优先考虑 badgePalette 按顺序分配 | string | - | | backgroundFillOpacity | 组合徽标背景填充透明度 | number | 1 | | backgroundFilter | 组合徽标背景滤镜 | string | - | | backgroundHeight | 组合徽标背景高度 | number \| string | - | | backgroundLineDash | 组合徽标背景虚线配置 | number \| string \|(number \| string )[] | - | | backgroundLineDashOffset | 组合徽标背景虚线偏移量 | number | - | | backgroundLineWidth | 组合徽标背景描边线宽 | number | - | | backgroundRadius | 组合徽标背景圆角半径
- number: 统一设置四个圆角半径
- number[]: 分别设置四个圆角半径,会补足缺省的分量
- string: 与 [CSS padding](https://developer.mozilla.org/zh-CN/docs/Web/CSS/padding) 属性类似,使用空格分隔 | number \| number[] \| string | 0 | | backgroundShadowBlur | 组合徽标背景阴影模糊程度 | number | - | | backgroundShadowColor | 组合徽标背景阴影颜色 | string | - | | backgroundShadowOffsetX | 组合徽标背景阴影 X 方向偏移 | number | - | | backgroundShadowOffsetY | 组合徽标背景阴影 Y 方向偏移 | number | - | | backgroundStroke | 组合徽标背景描边颜色 | string | - | | backgroundStrokeOpacity | 组合徽标背景描边透明度 | number \| string | 1 | | backgroundVisibility | 组合徽标背景是否可见 | `visible` \| `hidden` | - | | fill | 组合徽标文字颜色 | string | - | | fontFamily | 组合徽标字体族 | string | - | | fontSize | 组合徽标字体大小 | number | 8 | | fontStyle | 组合徽标字体样式 | `normal` \| `italic` \| `oblique` | `normal` | | fontVariant | 组合徽标字体变种 | `normal` \| `small-caps` \| string | `normal` | | fontWeight | 组合徽标字体粗细 | number \| string | `normal` | | lineHeight | 组合徽标行高 | string \| number | - | | lineWidth | 组合徽标行宽 | string \| number | - | | maxLines | 组合徽标文本最大行数 | number | 1 | | offsetX | 组合徽标在 x 轴方向上的偏移量 | number | 0 | | offsetY | 组合徽标在 y 轴方向上的偏移量 | number | 0 | | padding | 组合徽标内边距 | number \| number[] | 0 | | placement | 组合徽标相对于组合主图形的位置。若不指定,默认从右上角顺时针依次排放 | `left` \| `right` \| `top` \| `bottom` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` | - | | text | 组合徽标文字内容 | string | - | | textAlign | 组合徽标文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | textBaseline | 组合徽标文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | `alphabetic` | | textDecorationColor | 组合徽标文本装饰线颜色 | string | - | | textDecorationLine | 组合徽标文本装饰线 | string | - | | textDecorationStyle | 组合徽标文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | `solid` | | textOverflow | 组合徽标文本溢出处理方式 | `clip` \| `ellipsis` \| string | `clip` | | visibility | 组合徽标是否可见 | `visible` \| `hidden` | - | | wordWrap | 组合徽标文本是否自动换行 | boolean | - | | zIndex | 组合徽标渲染层级 | number | 3 | ### 标签样式 标签用于显示组合的文本信息,支持丰富的文本样式配置和灵活的位置布局。 #### 基础标签配置 为组合添加基本的文本标签: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: '销售部门', // 标签文字内容 labelFill: '#1A1A1A', // 标签文字颜色 labelFontSize: 14, // 标签字体大小 labelPlacement: 'bottom', // 标签位置:底部 }, }, }); graph.render(); ``` #### 多行文本标签 配置支持多行显示的标签: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: '这是一个支持多行显示的组合标签文本内容', labelWordWrap: true, // 开启文本换行 labelMaxWidth: 100, // 最大宽度 100px labelMaxLines: 3, // 最多显示 3 行 labelTextAlign: 'center', // 文本居中对齐 labelFontSize: 12, }, }, }); graph.render(); ``` #### 自定义样式标签 创建具有特殊样式的标签: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: 'IMPORTANT', labelFill: '#FF4D4F', // 红色文字 labelFontSize: 16, labelFontWeight: 'bold', // 粗体 labelFontStyle: 'italic', // 斜体 labelTextDecorationLine: 'underline', // 下划线 labelLetterSpacing: 2, // 字间距 labelPlacement: 'top', }, }, }); graph.render(); ``` 以下为完整的标签样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------- | ---- | | label | 是否显示组合标签 | boolean | true | | | labelCursor | 鼠标移入组合标签时显示的样式,[配置项](#cursor) | string | `default` | | | labelFill | 组合标签文字颜色 | string | #000 | | | labelFillOpacity | 组合标签文字颜色的透明度 | number | 1 | | | labelFontFamily | 组合标签字体族 | string | - | | | labelFontSize | 组合标签字体大小 | number | 12 | | | labelFontStyle | 组合标签字体样式 | `normal` \| `italic` \| `oblique` | - | | | labelFontVariant | 组合标签字体变种 | `normal` \| `small-caps` \| string | - | | | labelFontWeight | 组合标签字体粗细 | `normal` \| `bold` \| `bolder` \| `lighter` \| number | 400 | | | labelLeading | 行间距 | number | 0 | | | labelLetterSpacing | 组合标签字间距 | number \| string | - | | | labelLineHeight | 组合标签行高 | number \| string | - | | | labelMaxLines | 组合标签最大行数 | number | 1 | | | labelMaxWidth | 组合标签最大宽度,[配置项](#labelmaxwidth) | number \| string | `200%` | | | labelOffsetX | 组合标签在 x 轴方向上的偏移量 | number | 0 | | | labelOffsetY | 组合标签在 y 轴方向上的偏移量 | number | 0 | | | labelPadding | 组合标签内边距 | number \| number[] | 0 | | | labelPlacement | 组合标签相对于组合主图形的位置,[配置项](#labelplacement) | string | `bottom` | | | labelText | 组合标签文字内容 | string | - | | | labelTextAlign | 组合标签文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | | labelTextBaseline | 组合标签文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | - | | | labelTextDecorationColor | 组合标签文本装饰线颜色 | string | - | | | labelTextDecorationLine | 组合标签文本装饰线 | string | - | | | labelTextDecorationStyle | 组合标签文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | - | | | labelTextOverflow | 组合标签文本溢出处理方式 | `clip` \| `ellipsis` \| string | - | | | labelTextPath | 组合标签文本路径 | Path | - | | | labelWordWrap | 组合标签是否开启自动折行。开启 labelWordWrap 后,超出 labelMaxWidth 的部分自动换行 | boolean | false | | | labelZIndex | 组合标签渲染层级 | number | 0 | | | `label{StyleProps}` | 更多标签样式配置,参考 [TextStyleProps](https://g.antv.antgroup.com/api/basic/text) 属性值。比如 labelOpacity 代表标签透明度 | [TextStyleProps](https://g.antv.antgroup.com/api/basic/text) | - | | #### LabelPlacement 标签相对于组合主图形的位置,可选值有: - `center`:标签位于组合中心 - `top`、`bottom`、`left`、`right`:标签位于组合的上、下、左、右方 - `top-left`、`top-right`、`bottom-left`、`bottom-right`:标签位于组合的四个角 - `left-top`、`left-bottom`、`right-top`、`right-bottom`:标签位于组合边的端点 #### LabelMaxWidth 开启自动折行 `labelWordWrap` 后,超出该宽度则换行: - string: 表示以相对于组合元素宽度的百分比形式定义最大宽度。例如 `50%` 表示标签宽度不超过组合宽度的一半 - number: 表示以像素值为单位定义最大宽度。例如 100 表示标签的最大宽度为 100 像素 比如,设置多行标签文字: ```json { "labelWordWrap": true, "labelMaxWidth": 200, "labelMaxLines": 3 } ``` ### 标签背景样式 标签背景为标签文字提供背景装饰,可以提升标签的可读性和视觉效果。 #### 基础背景样式 为标签添加简单的背景: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: '重要组合', labelFill: '#fff', // 白色文字 labelBackground: true, // 启用背景 labelBackgroundFill: '#1783FF', // 蓝色背景 labelBackgroundPadding: [4, 8], // 内边距:垂直4px,水平8px labelBackgroundRadius: 4, // 圆角半径 }, }, }); graph.render(); ``` #### 渐变背景效果 创建带渐变效果的标签背景: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: 'VIP组合', labelFill: '#fff', labelFontWeight: 'bold', labelBackground: true, labelBackgroundFill: 'linear-gradient(45deg, #FF6B6B, #4ECDC4)', // 渐变背景 labelBackgroundPadding: [6, 12], labelBackgroundRadius: 20, // 大圆角 labelBackgroundShadowColor: 'rgba(0,0,0,0.2)', labelBackgroundShadowBlur: 4, labelBackgroundShadowOffsetY: 2, }, }, }); graph.render(); ``` #### 描边背景样式 创建只有描边的标签背景: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { labelText: '边框标签', labelFill: '#1783FF', labelBackground: true, labelBackgroundFill: 'transparent', // 透明背景 labelBackgroundStroke: '#1783FF', // 蓝色描边 labelBackgroundLineWidth: 2, // 描边宽度 labelBackgroundPadding: [4, 8], labelBackgroundRadius: 8, }, }, }); graph.render(); ``` 以下为完整的标签背景样式配置: | 属性 | 描述 | 类型 | 默认值 | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------ | | labelBackground | 组合标签背景是否显示 | boolean | false | | labelBackgroundCursor | 组合标签背景鼠标移入样式,[配置项](#cursor) | string | `default` | | labelBackgroundFill | 组合标签背景填充色 | string | #000 | | labelBackgroundFillOpacity | 组合标签背景透明度 | number | 0.75 | | labelBackgroundHeight | 组合标签背景高度 | string \| number | - | | labelBackgroundLineDash | 组合标签背景虚线配置 | number \| string \|(number \| string )[] | - | | labelBackgroundLineDashOffset | 组合标签背景虚线偏移量 | number | - | | labelBackgroundLineWidth | 组合标签背景描边线宽 | number | - | | labelBackgroundPadding | 组合标签背景内间距 | number \| number[] | [2, 4, 2, 4] | | labelBackgroundRadius | 组合标签背景圆角半径
- number: 统一设置四个圆角半径
- number[]: 分别设置四个圆角半径,不足则自动补充 | number \| number[] | 0 | | labelBackgroundShadowBlur | 组合标签背景阴影模糊程度 | number | - | | labelBackgroundShadowColor | 组合标签背景阴影颜色 | string | - | | labelBackgroundShadowOffsetX | 组合标签背景阴影 X 方向偏移 | number | - | | labelBackgroundShadowOffsetY | 组合标签背景阴影 Y 方向偏移 | number | - | | labelBackgroundStroke | 组合标签背景描边颜色 | string | - | | labelBackgroundStrokeOpacity | 组合标签背景描边透明度 | number \| string | 1 | | labelBackgroundVisibility | 组合标签背景是否可见 | `visible` \| `hidden` | - | | labelBackgroundZIndex | 组合标签背景渲染层级 | number | 1 | | `labelBackground{StyleProps}` | 更多标签背景样式配置,参考 [RectStyleProps](https://g.antv.antgroup.com/api/basic/rect) 属性值。例如 labelBackgroundOpacity 代表标签背景透明度 | [RectStyleProps](https://g.antv.antgroup.com/api/basic/rect) | - | ### 光晕样式 光晕效果用于突出显示组合,通常在鼠标悬停、选中或激活状态下使用,为组合周围添加发光效果。 #### 基础光晕效果 为组合添加简单的光晕效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { halo: true, // 启用光晕 haloStroke: '#1783FF', // 蓝色光晕 haloLineWidth: 8, // 光晕宽度 haloStrokeOpacity: 0.3, // 光晕透明度 }, }, }); graph.render(); ``` #### 彩色光晕效果 创建彩色渐变的光晕效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { halo: true, haloStroke: '#FF4D4F', // 红色光晕 haloLineWidth: 12, // 较粗的光晕 haloStrokeOpacity: 0.5, haloFilter: 'blur(2px)', // 模糊滤镜效果 }, }, }); graph.render(); ``` #### 动态光晕效果 在状态切换时使用光晕效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1' }], }, combo: { style: { // 默认状态下不显示光晕 halo: false, }, state: { // 悬停状态显示橙色光晕 hover: { halo: true, haloStroke: '#FF7A00', haloLineWidth: 10, haloStrokeOpacity: 0.4, }, // 选中状态显示绿色光晕 selected: { halo: true, haloStroke: '#52C41A', haloLineWidth: 6, haloStrokeOpacity: 0.6, }, }, }, }); graph.render(); ``` 以下为完整的光晕样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------- | ---- | | halo | 是否显示组合光晕 | boolean | false | | | haloCursor | 组合光晕鼠标移入样式,[配置项](#cursor) | string | `default` | | | haloDraggable | 组合光晕是否允许拖拽 | boolean | true | | | haloDroppable | 组合光晕是否允许接收被拖拽的元素 | boolean | false | | | haloFill | 光晕填充色 | string | 与主图形的填充色 `fill` 一致 | | | haloFillRule | 组合光晕填充规则 | `nonzero` \| `evenodd` | - | | | haloFilter | 组合光晕滤镜效果,如 'blur(2px)' 可创建模糊效果 | string | - | | | haloLineWidth | 组合光晕描边宽度,控制光晕的粗细程度 | number | 12 | | | haloPointerEvents | 组合光晕效果是否响应指针事件,[配置项](#pointerevents) | string | `none` | | | haloStroke | 组合光晕描边色,**此属性用于设置组合周围光晕的颜色,帮助突出显示组合** | string | `#99add1` | | | haloStrokeOpacity | 组合光晕描边色透明度,建议使用 0.2-0.6 的值以获得自然的光晕效果 | number | 0.25 | | | haloVisibility | 组合光晕可见性 | `visible` \| `hidden` | `visible` | | | haloZIndex | 组合光晕渲染层级,通常设置为负值以确保光晕在组合主图形下方 | number | -1 | | | `halo{StyleProps}` | 更多光晕样式配置,参考 [DisplayObject](https://g.antv.antgroup.com/api/basic/display-object) 配置项。例如 haloFillOpacity 代表光晕填充色透明度 | [DisplayObject](https://g.antv.antgroup.com/api/basic/display-object) | - | | **光晕使用建议:** 1. **性能考虑**:光晕效果会增加渲染负担,建议在必要时才启用 2. **颜色搭配**:光晕颜色应与组合主色调协调,避免过于突兀 3. **透明度设置**:合理的透明度(0.2-0.6)可以创造自然的光晕效果 4. **状态应用**:光晕通常用于 hover、selected、active 等交互状态 ### 图标样式 图标用于在组合中显示文字或图片内容,通常位于组合的中心位置,可以用来表示组合的类型或功能。 #### 文字图标 使用文字作为组合的图标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { combos: [{ id: 'combo1' }], }, combo: { style: { iconText: 'A', // 显示字母 A iconFill: '#1783FF', // 蓝色文字 iconFontSize: 24, // 大字体 iconFontWeight: 'bold', // 粗体 }, }, }); graph.render(); ``` #### 图片图标 使用图片作为组合的图标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { combos: [{ id: 'combo1' }], }, combo: { style: { fill: '#1890FF', iconSrc: 'https://gw.alipayobjects.com/zos/basement_prod/012bcf4f-423b-4922-8c24-32a89f8c41ce.svg', iconWidth: 32, iconHeight: 32, }, }, }); graph.render(); ``` #### 彩色文字图标 创建带有特殊样式的文字图标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', data: { combos: [{ id: 'combo1' }], }, combo: { style: { iconText: '部门', iconFill: '#FF4D4F', // 红色文字 iconFontSize: 16, iconFontWeight: 'bold', iconFontStyle: 'italic', // 斜体 iconTextDecorationLine: 'underline', // 下划线 iconLetterSpacing: 1, // 字间距 }, }, }); graph.render(); ``` 以下为完整的图标样式配置: | 属性 | 描述 | 类型 | 默认值 | | ----------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ---------------- | | icon | 是否显示组合图标 | boolean | true | | iconCursor | 组合图标鼠标移入样式,[配置项](#cursor) | string | `default` | | iconFill | 组合图标文字颜色 | string | - | | iconFillOpacity | 组合图标文字颜色透明度 | number | 1 | | iconFontFamily | 组合图标字体族 | string | - | | iconFontSize | 组合图标字体大小 | number | 16 | | iconFontStyle | 组合图标字体样式 | `normal` \| `italic` \| `oblique` | `normal` | | iconFontVariant | 组合图标字体变种 | `normal` \| `small-caps` \| string | `normal` | | iconFontWeight | 组合图标字体粗细 | number \| string | `normal` | | iconHeight | 组合图标高度,当使用图片图标时用于控制图片尺寸 | number | 主图形高度的一半 | | iconLetterSpacing | 组合图标文本字间距 | number \| string | - | | iconLineHeight | 组合图标文本行高 | number \| string | - | | iconMaxLines | 组合图标文本最大行数 | number | 1 | | iconOffsetX | 组合图标在 x 轴方向上的偏移量 | number | 0 | | iconOffsetY | 组合图标在 y 轴方向上的偏移量 | number | 0 | | iconOpacity | 组合图标透明度 | number | 1 | | iconRadius | 组合图标圆角半径(仅对矩形图标有效) | number | 0 | | iconSrc | 组合图片来源。其优先级高于 iconText,支持本地图片和网络图片 | string | - | | iconText | 组合图标文字内容,支持文字、Unicode 字符等 | string | - | | iconTextAlign | 组合图标文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `center` | | iconTextBaseline | 组合图标文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | `middle` | | iconTextDecorationColor | 组合图标文本装饰线颜色 | string | - | | iconTextDecorationLine | 组合图标文本装饰线,如下划线、删除线等 | string | - | | iconTextDecorationStyle | 组合图标文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | `solid` | | iconTextOverflow | 组合图标文本溢出处理方式 | `clip` \| `ellipsis` \| string | `clip` | | iconVisibility | 组合图标是否可见 | `visible` \| `hidden` | `visible` | | iconWidth | 组合图标宽度,当使用图片图标时用于控制图片尺寸 | number | 主图形宽度的一半 | | iconWordWrap | 组合图标文本是否自动换行 | boolean | false | | iconZIndex | 组合图标渲染层级 | number | 1 | | `icon{StyleProps}` | 更多图标样式配置,参考图标的具体类型配置项。例如 iconStroke 代表图标描边颜色 | - | - | **图标使用建议:** 1. **优先级**:`iconSrc`(图片)的优先级高于 `iconText`(文字),如果同时设置,会优先显示图片 2. **尺寸控制**:建议根据组合大小合理设置图标尺寸,避免图标过大或过小影响视觉效果 3. **性能优化**:使用文字图标性能更好,图片图标需要额外的网络请求和渲染开销 4. **样式一致性**:在同一个图中的组合图标样式应保持一致,提升整体视觉效果 5. **可访问性**:确保图标颜色与背景有足够的对比度,便于用户识别 ## State 在一些交互行为中,比如点击选中一个组合或鼠标悬停激活一个边,仅仅是在该元素做了某些状态的标识。为了将这些状态反应到终端用户所见的视觉空间中,我们需要为不同的状态设置不同的图元素样式,以响应该图元素状态的变化。 G6 提供了几种内置的状态,包括选中(selected)、高亮(highlight)、激活(active)、不活跃(inactive)和禁用(disabled)。此外,它还支持自定义状态,以满足更特定的需求。对于每个状态,开发者可以定义一套样式规则,这些规则会覆盖元素的默认样式。 数据结构如下: ```typescript type ComboState = { [state: string]: ComboStyle; }; ``` 例如,当组合处于 `focus` 状态时,可以为其添加一个宽度为 3 且颜色为橙色的描边。 ```js {4-7} const graph = new Graph({ combo: { state: { focus: { lineWidth: 3, // 描边宽度 stroke: 'orange', // 描边颜色 }, }, }, }); ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', combo: 'combo1' }], combos: [{ id: 'combo1', states: ['focus'] }], }, combo: { state: { focus: { lineWidth: 3, stroke: 'orange', fill: 'orange', fillOpacity: 0.2, }, }, }, }); graph.render(); ``` ## Animation 定义组合的动画效果,支持下列两种配置方式: 1. 关闭组合全部动画 ```json { "combo": { "animation": false } } ``` 2. 配置阶段动画 阶段动画是指组合在进入画布、更新、离开画布时的动画效果。目前支持的阶段包括: - `enter`: 组合进入画布时的动画 - `update`: 组合更新时的动画 - `exit`: 组合离开画布时的动画 - `show`: 组合从隐藏状态显示时的动画 - `hide`: 组合隐藏时的动画 - `collapse`: 组合收起时的动画 - `expand`: 组合展开时的动画 你可以参考 [动画范式](/zh/manual/animation/animation/#动画范式) 使用动画语法来配置组合,如: ```json { "combo": { "animation": { "update": [ { "fields": ["x", "y"], // 更新时只对 x 和 y 属性进行动画 "duration": 1000, // 动画持续时间 "easing": "linear" // 缓动函数 } ], } } ``` 也可以使用内置的动画效果: ```json { "combo": { "animation": { "enter": "fade", // 使用渐变动画 "update": "translate", // 使用平移动画 "exit": "fade" // 使用渐变动画 } } } ``` 你可以传入 false 来关闭特定阶段的动画: ```json { "combo": { "animation": { "enter": false // 关闭组合入场动画 } } } ``` ## Palette 定义组合的色板,即预定义组合颜色池,并根据规则进行分配,将颜色映射到 `fill` 属性。 > 有关色板的定义,请参考 [色板](/zh/manual/theme/palette/)。 | 属性 | 描述 | 类型 | 默认值 | | ------ | ------------------------------------------------------------------- | --------------------------------- | ------- | | type | 指定当前色板类型。
- `group`: 离散色板
- `value`: 连续色板 | `group` | `value` | `group` | | field | 指定元素数据中的分组字段。若不指定,默认取 id 作为分组字段 | string | ((datum) => string) | `id` | | color | 色板颜色。如果色板注册过,可以直接指定其注册名,也接受一个颜色数组 | string | string[] | - | | invert | 是否反转色板 | boolean | false | 如将一组数据按 `category` 字段分配组合颜色,使得同类别的组合颜色相同: ```json { "combo": { "palette": { "type": "group", "field": "category", "color": ["#1783FF", "#F08F56", "#D580FF", "#00C9C9", "#7863FF"] } } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 100, data: { combos: new Array(8) .fill(0) .map((_, i) => ({ id: `combo-${i}`, data: { category: ['A', 'B', 'C', 'D', 'E'][i % 5] } })), }, layout: { type: 'grid', cols: 8 }, combo: { style: { fillOpacity: 0.4 }, palette: { type: 'group', field: 'category', color: ['#1783FF', '#F08F56', '#D580FF', '#00C9C9', '#7863FF'], }, }, }); graph.render(); ``` 也可以使用默认配置: ```json { "combo": { "palette": "tableau" // tableau 为色板名,默认根据 ID 分配颜色 } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 100, data: { combos: new Array(8) .fill(0) .map((_, i) => ({ id: `combo-${i}`, data: { category: ['A', 'B', 'C', 'D', 'E'][i % 5] } })), }, layout: { type: 'grid', cols: 8 }, combo: { style: { fillOpacity: 0.4 }, palette: 'tableau', }, }); graph.render(); ``` #### 边通用配置项 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/BaseEdge/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/BaseEdge.md - Description: 边通用配置项 --- title: "边通用配置项" description: "边通用配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/BaseEdge/" version: "5.1.1" --- 本文介绍内置边通用属性配置。 ## EdgeOptions ```js {5-9} import { Graph } from '@antv/g6'; const graph = new Graph({ edge: { type: 'line', // 边类型 style: {}, // 边样式 state: {}, // 状态样式 palette: {}, // 色板配置 animation: {}, // 动画配置 }, }); ``` | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------- | ----------------------- | ------ | ---- | | type | 边类型,内置边类型名称或自定义边的名称 | [Type](#type) | `line` | | | style | 边样式配置,包括颜色、粗细等 | [Style](#style) | - | | | state | 不同状态下的样式配置 | [State](#state) | - | | | palette | 定义边的色板,用于根据不同数据映射颜色 | [Palette](#palette) | - | | | animation | 定义边的动画效果 | [Animation](#animation) | - | | ## Type 指定边类型,内置边类型名称或自定义边的名称。默认为 `line`(直线边)。**⚠️ 注意**:这里决定了主图形的形状。 ```js {3} const graph = new Graph({ edge: { type: 'polyline', }, }); ``` **⚠️ 动态配置说明**:`type` 属性同样支持动态配置,可以根据边数据动态选择边类型: ```js const graph = new Graph({ edge: { // 静态配置 type: 'line', // 动态配置 - 箭头函数形式 type: (datum) => datum.data.edgeType || 'line', // 动态配置 - 普通函数形式(可访问 graph 实例) type: function (datum) { console.log(this); // graph 实例 return datum.data.importance > 5 ? 'polyline' : 'line'; }, }, }); ``` 可选值有: - `line`:[直线边](/zh/manual/element/edge/Line/) - `polyline`:[折线边](/zh/manual/element/edge/Polyline/) - `cubic`:[三次贝塞尔曲线边](/zh/manual/element/edge/Cubic/) - `cubic-horizontal`:[水平三次贝塞尔曲线边](/zh/manual/element/edge/CubicHorizontal/) - `cubic-vertical`:[垂直三次贝塞尔曲线边](/zh/manual/element/edge/CubicVertical/) - `quadratic`:[二次贝塞尔曲线边](/zh/manual/element/edge/Quadratic/) ## Style 定义边的样式,包括颜色、粗细等。 ```js {3} const graph = new Graph({ edge: { style: {}, }, }); ``` **⚠️ 动态配置说明**:以下所有样式属性都支持动态配置,即可以传入函数来根据边数据动态计算属性值: ```js const graph = new Graph({ edge: { style: { // 静态配置 stroke: '#1783FF', // 动态配置 - 箭头函数形式 lineWidth: (datum) => (datum.data.isImportant ? 3 : 1), // 动态配置 - 普通函数形式(可访问 graph 实例) lineDash: function (datum) { console.log(this); // graph 实例 return datum.data.type === 'dashed' ? [5, 5] : []; }, // 嵌套属性也支持动态配置 labelText: (datum) => `边: ${datum.id}`, endArrow: (datum) => datum.data.hasArrow, }, }, }); ``` 其中 `datum` 参数为边数据对象 (`EdgeData`),包含边的所有数据信息。 一个完整的边由以下几部分构成: - `key` :边的主图形,表示边的主要路径,例如直线、曲线等; - `label` :文本标签,通常用于展示边的名称或描述; - `badge` :边上的徽标; - `halo` :主图形周围展示的光晕效果的图形; - `startArrow` :边起始端的箭头; - `endArrow` :边结束端的箭头。 以下样式配置将按原子图形依次说明: ### 主图形样式 主图形是边的核心部分,定义了边的基本路径和外观。以下是常见的配置场景: #### 基础样式配置 设置边的基本外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 40 } }, { id: 'node2', style: { x: 180, y: 40 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#5B8FF9', // 蓝色边 lineWidth: 2, // 边宽度 }, }, }); graph.render(); ``` #### 虚线样式 创建带虚线样式的边: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 40 } }, { id: 'node2', style: { x: 180, y: 40 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#F5222D', lineWidth: 2, lineDash: [6, 4], // 虚线样式 lineDashOffset: 0, }, }, }); graph.render(); ``` #### 阴影效果 为边添加阴影效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 40 } }, { id: 'node2', style: { x: 180, y: 40 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#722ED1', lineWidth: 3, shadowColor: 'rgba(114, 46, 209, 0.3)', shadowBlur: 8, shadowOffsetX: 2, shadowOffsetY: 2, }, }, }); graph.render(); ``` 以下为完整的主图形样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------------- | ----------------------------------------------------------------------------------------- | --------------------- | --------- | ---- | | cursor | 边鼠标移入样式,[配置项](#cursor) | string | `default` | | | increasedLineWidthForHitTesting | 当 lineWidth 较小时,可交互区域也随之变小,有时我们想增大这个区域,让"细线"更容易被拾取到 | number | 0 | | | lineDash | 边虚线样式 | number[] | - | | | lineDashOffset | 边虚线偏移量 | number | 0 | | | lineWidth | 边宽度 | number | 1 | | | opacity | 边透明度 | number \| string | 1 | | | pointerEvents | 边如何响应指针事件,[配置项](#pointerevents) | string | `auto` | | | shadowBlur | 边阴影模糊度 | number | - | | | shadowColor | 边阴影颜色 | string | - | | | shadowOffsetX | 边阴影在 x 轴方向上的偏移量 | number \| string | - | | | shadowOffsetY | 边阴影在 y 轴方向上的偏移量 | number \| string | - | | | shadowType | 边阴影类型 | `inner` \| `outer` | `outer` | | | sourcePort | 边起始连接的连接桩 | string | - | | | stroke | 边颜色 | string | `#000` | | | strokeOpacity | 边颜色透明度 | number \| string | 1 | | | targetPort | 边终点连接的连接桩 | string | - | | | transform | transform 属性允许你旋转、缩放、倾斜或平移给定边 | string | - | | | transformOrigin | 旋转与缩放中心,也称作变换中心 | string | - | | | visibility | 边是否可见 | `visible` \| `hidden` | `visible` | | | zIndex | 边渲染层级 | number | 1 | | #### PointerEvents `pointerEvents` 属性控制图形如何响应交互事件,可参考 [MDN 文档](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)。 可选值有:`visible` | `visiblepainted` | `visiblestroke` | `non-transparent-pixel` | `visiblefill` | `visible` | `painted` | `fill` | `stroke` | `all` | `none` | `auto` | `inherit` | `initial` | `unset` 简而言之,`stroke` 和 `visibility` 都可以独立或组合影响拾取判定行为。目前支持以下关键词: - **`auto`**:默认值,等同于 `visiblepainted` - **`none`**:永远不会成为响应事件的目标 - **`visiblepainted`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形描边区域触发同时 `stroke` 取非 `none` 的值 - **`visiblestroke`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形描边区域触发,不受 `stroke` 取值的影响 - **`visible`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形描边区域触发,不受 `stroke` 取值的影响 - **`painted`**:满足以下条件才会响应事件: - 在图形描边区域触发同时 `stroke` 取非 `none` 的值 - 不受 `visibility` 取值的影响 - **`stroke`**:满足以下条件才会响应事件: - 在图形描边区域触发,不受 `stroke` 取值的影响 - 不受 `visibility` 取值的影响 - **`all`**:只要进入图形的描边区域就会响应事件,不会受 `stroke`、`visibility` 的取值影响 **使用示例:** ```js // 示例1:只有描边区域响应事件 const graph = new Graph({ edge: { style: { stroke: '#000', lineWidth: 2, pointerEvents: 'stroke', // 只有描边响应事件 }, }, }); // 示例2:完全不响应事件 const graph = new Graph({ edge: { style: { pointerEvents: 'none', // 边不响应任何事件 }, }, }); ``` #### Cursor 可选值有:`auto` | `default` | `none` | `context-menu` | `help` | `pointer` | `progress` | `wait` | `cell` | `crosshair` | `text` | `vertical-text` | `alias` | `copy` | `move` | `no-drop` | `not-allowed` | `grab` | `grabbing` | `all-scroll` | `col-resize` | `row-resize` | `n-resize` | `e-resize` | `s-resize` | `w-resize` | `ne-resize` | `nw-resize` | `se-resize` | `sw-resize` | `ew-resize` | `ns-resize` | `nesw-resize` | `nwse-resize` | `zoom-in` | `zoom-out` ### 标签样式 标签用于显示边的文本信息,支持多种样式配置和布局方式。以下是常见的使用场景: #### 基础文本标签 最简单的文本标签配置: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, data: { nodes: [ { id: 'node1', style: { x: 60, y: 60 } }, { id: 'node2', style: { x: 180, y: 60 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: '边标签', labelFill: '#262626', labelFontSize: 12, labelPlacement: 'center', }, }, }); graph.render(); ``` #### 多行文本标签 当文本较长时,可以设置自动换行: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, data: { nodes: [ { id: 'node1', style: { x: 60, y: 60 } }, { id: 'node2', style: { x: 180, y: 60 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: '这是一个很长的边标签需要换行显示', labelWordWrap: true, labelMaxWidth: '200%', labelMaxLines: 2, labelTextOverflow: 'ellipsis', labelFill: '#434343', labelPlacement: 'center', labelTextAlign: 'center', }, }, }); graph.render(); ``` #### 带背景的标签 为标签添加背景,提高可读性: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, data: { nodes: [ { id: 'node1', style: { x: 60, y: 60 } }, { id: 'node2', style: { x: 180, y: 60 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: '重要连接', labelBackground: true, labelBackgroundFill: 'rgba(250, 140, 22, 0.1)', labelBackgroundRadius: 6, labelPadding: [4, 8], labelFill: '#D4380D', labelFontWeight: 'bold', labelPlacement: 'center', }, }, }); graph.render(); ``` #### 自动旋转标签 标签可以自动旋转以保持与边方向一致: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, data: { nodes: [ { id: 'node1', style: { x: 60, y: 30 } }, { id: 'node2', style: { x: 180, y: 90 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: '自动旋转', labelAutoRotate: true, // 自动旋转 labelFill: '#1890FF', labelFontWeight: 'bold', labelPlacement: 'center', }, }, }); graph.render(); ``` 以下为完整的标签样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------ | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------- | ---- | | label | 边标签是否显示 | boolean | true | | | labelAutoRotate | 边标签是否自动旋转,保持与边的方向一致 | boolean | true | | | labelCursor | 鼠标移入边标签时显示的样式,[配置项](#cursor) | string | `default` | | | labelFill | 边标签文字颜色 | string | - | | | labelFontFamily | 边标签字体族 | string | - | | | labelFontSize | 边标签字体大小 | number | 12 | | | labelFontStyle | 边标签字体样式 | `normal` \| `italic` \| `oblique` | - | | | labelFontVariant | 边标签字体变种 | `normal` \| `small-caps` \| string | - | | | labelFontWeight | 边标签字体粗细 | `normal` \| `bold` \| `bolder` \| `lighter` \| number | - | | | labelLeading | 行间距 | number | 0 | | | labelLetterSpacing | 边标签字间距 | number \| string | - | | | labelLineHeight | 边标签行高 | number \| string | - | | | labelMaxLines | 边标签最大行数 | number | 1 | | | labelMaxWidth | 边标签最大宽度,[配置项](#labelmaxwidth) | number \| string | `200%` | | | labelOffsetX | 边标签在 x 轴方向上的偏移量 | number | 0 | | | labelOffsetY | 边标签在 y 轴方向上的偏移量 | number | 0 | | | labelPadding | 边标签内边距 | number \| number[] | 0 | | | labelPlacement | 边标签相对于边的位置,[配置项](#labelplacement) | string \| number | `center` | | | labelText | 边标签文字内容 | `string` \| `(datum) => string` | - | | | labelTextAlign | 边标签文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | | labelTextBaseline | 边标签文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | - | | | labelTextDecorationColor | 边标签文本装饰线颜色 | string | - | | | labelTextDecorationLine | 边标签文本装饰线 | string | - | | | labelTextDecorationStyle | 边标签文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | - | | | labelTextOverflow | 边标签文本溢出处理方式 | `clip` \| `ellipsis` \| string | - | | | labelTextPath | 边标签文本路径 | Path | - | | | labelWordWrap | 边标签是否开启自动折行。开启 labelWordWrap 后,超出 labelMaxWidth 的部分自动换行 | boolean | false | | | labelZIndex | 边标签渲染层级 | number | 0 | | #### LabelPlacement 边标签相对于边的位置,可以设置为: - `start`:标签位于边的起始位置 - `center`:标签位于边的中心位置(默认) - `end`:标签位于边的结束位置 - `number`:取值范围为 0-1,表示标签在边上的具体位置比例,0 为起始位置,1 为结束位置 #### LabelMaxWidth 开启自动折行 `labelWordWrap` 后,超出该宽度则换行: - string: 表示以相对于边长度的百分比形式定义最大宽度。例如 `50%` 表示标签宽度不超过边长度的一半 - number: 表示以像素值为单位定义最大宽度。例如 100 表示标签的最大宽度为 100 像素 比如,设置多行标签文字: ```json { "labelWordWrap": true, "labelMaxWidth": 200, "labelMaxLines": 3 } ``` ### 标签背景样式 标签背景用于显示边标签的背景: | 属性 | 描述 | 类型 | 默认值 | | ----------------------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------- | --------- | | labelBackground | 边标签背景是否显示 | boolean | false | | labelBackgroundCursor | 边标签背景鼠标移入样式,[配置项](#cursor) | string | `default` | | labelBackgroundFill | 边标签背景填充色 | string | - | | labelBackgroundFillOpacity | 边标签背景透明度 | number | 1 | | labelBackgroundHeight | 边标签背景高度 | string \| number | - | | labelBackgroundLineDash | 边标签背景虚线配置 | number \| string \|(number \| string )[] | - | | labelBackgroundLineDashOffset | 边标签背景虚线偏移量 | number | - | | labelBackgroundLineWidth | 边标签背景描边线宽 | number | - | | labelBackgroundRadius | 边标签背景圆角半径
- number: 统一设置四个圆角半径
- number[]: 分别设置四个圆角半径,不足则自动补充 | number \| number[] | 0 | | labelBackgroundShadowBlur | 边标签背景阴影模糊程度 | number | - | | labelBackgroundShadowColor | 边标签背景阴影颜色 | string | - | | labelBackgroundShadowOffsetX | 边标签背景阴影 X 方向偏移 | number | - | | labelBackgroundShadowOffsetY | 边标签背景阴影 Y 方向偏移 | number | - | | labelBackgroundStroke | 边标签背景描边颜色 | string | - | | labelBackgroundStrokeOpacity | 边标签背景描边透明度 | number \| string | 1 | | labelBackgroundVisibility | 边标签背景是否可见 | `visible` \| `hidden` | - | | labelBackgroundZIndex | 边标签背景渲染层级 | number | 1 | ### 光晕样式 光晕是围绕边主图形显示的效果,通常用于高亮显示或表示边的特殊状态。 #### 基础光晕效果 为边添加基本的光晕效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 50 } }, { id: 'node2', style: { x: 180, y: 50 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { lineWidth: 2, halo: true, haloStroke: '#1890FF', haloLineWidth: 6, haloStrokeOpacity: 0.3, }, }, }); graph.render(); ``` 以下为完整的光晕样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------------- | ---------------------------------------------------- | ---------------------- | ------------------------------ | ---- | | halo | 边光晕是否显示 | boolean | false | | | haloCursor | 边光晕鼠标移入样式,[配置项](#cursor) | string | `default` | | | haloDraggable | 边光晕是否允许拖拽 | boolean | true | | | haloDroppable | 边光晕是否允许接收被拖拽的元素 | boolean | true | | | haloFillRule | 边光晕填充规则 | `nonzero` \| `evenodd` | - | | | haloFilter | 边光晕滤镜 | string | - | | | haloLineWidth | 边光晕描边宽度 | number | 3 | | | haloPointerEvents | 边光晕效果是否响应指针事件,[配置项](#pointerevents) | string | `none` | | | haloStroke | 边光晕描边色,**此属性用于设置边周围光晕的颜色** | string | 与主图形的描边色 `stroke` 一致 | | | haloStrokeOpacity | 边光晕描边色透明度 | number | 0.25 | | | haloVisibility | 边光晕可见性 | `visible` \| `hidden` | `visible` | | | haloZIndex | 边光晕渲染层级 | number | -1 | | ### 箭头样式 边支持在起始端和结束端添加箭头,用于表示边的方向性。 #### 基础箭头 为边的结束端添加基本箭头: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 50 } }, { id: 'node2', style: { x: 180, y: 50 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#1890FF', lineWidth: 2, endArrow: true, // 结束端箭头 endArrowType: 'vee', // 箭头类型 endArrowSize: 10, // 箭头大小 }, }, }); graph.render(); ``` #### 双向箭头 为边的两端都添加箭头: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 50 } }, { id: 'node2', style: { x: 180, y: 50 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#52C41A', lineWidth: 2, startArrow: true, // 起始端箭头 startArrowType: 'circle', startArrowSize: 8, endArrow: true, // 结束端箭头 endArrowType: 'triangle', endArrowSize: 10, }, }, }); graph.render(); ``` #### 自定义箭头样式 自定义箭头的颜色和类型: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, data: { nodes: [ { id: 'node1', style: { x: 60, y: 50 } }, { id: 'node2', style: { x: 180, y: 50 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { stroke: '#722ED1', lineWidth: 3, endArrow: true, endArrowType: 'diamond', // 菱形箭头 endArrowSize: 12, endArrowFill: '#FF4D4F', // 红色箭头填充 endArrowStroke: '#722ED1', // 箭头描边颜色 endArrowStrokeOpacity: 0.8, }, }, }); graph.render(); ``` #### 起始箭头样式配置 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------ | ------------------ | ---- | | startArrow | 边起始箭头是否显示 | boolean | false | | | startArrowCursor | 边起始箭头鼠标移入样式,[配置项](#cursor) | string | `default` | | | startArrowFill | 边起始箭头填充颜色 | string | 默认与边的颜色一致 | | | startArrowFillOpacity | 边起始箭头填充透明度 | number | 1 | | | startArrowOffset | 边起始箭头的偏移量 | number | 0 | | | startArrowSize | 边起始箭头大小 | number \| [number, number] | 10 | | | startArrowStroke | 边起始箭头描边颜色 | string | 默认与边的颜色一致 | | | startArrowStrokeOpacity | 边起始箭头描边透明度 | number | 1 | | | startArrowType | 边起始箭头类型 | `triangle` \| `circle` \| `diamond` \| `vee` \| `rect` \| `triangleRect` \| `simple` | `vee` | | #### 结束箭头样式配置 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------ | ------------------ | ---- | | endArrow | 边结束箭头是否显示 | boolean | false | | | endArrowCursor | 边结束箭头鼠标移入样式,[配置项](#cursor) | string | `default` | | | endArrowFill | 边结束箭头填充颜色 | string | 默认与边的颜色一致 | | | endArrowFillOpacity | 边结束箭头填充透明度 | number | 1 | | | endArrowOffset | 边结束箭头的偏移量 | number | 0 | | | endArrowSize | 边结束箭头大小 | number \| [number, number] | 10 | | | endArrowStroke | 边结束箭头描边颜色 | string | 默认与边的颜色一致 | | | endArrowStrokeOpacity | 边结束箭头描边透明度 | number | 1 | | | endArrowType | 边结束箭头类型 | `triangle` \| `circle` \| `diamond` \| `vee` \| `rect` \| `triangleRect` \| `simple` | `vee` | | ### 自环边样式 自环边是指起始节点和结束节点为同一个节点的特殊边。 #### 基础自环边 创建基本的自环边: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, data: { nodes: [{ id: 'node1', style: { x: 100, y: 50 } }], edges: [{ source: 'node1', target: 'node1' }], }, edge: { style: { stroke: '#1890FF', lineWidth: 2, endArrow: true, loopPlacement: 'top', // 自环位置 loopDist: 30, // 自环大小 }, }, }); graph.render(); ``` #### 多个自环边 为同一节点创建多个不同位置的自环边: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 120, data: { nodes: [{ id: 'node1', style: { x: 100, y: 60 } }], edges: [ { id: 'edge1', source: 'node1', target: 'node1' }, { id: 'edge2', source: 'node1', target: 'node1' }, { id: 'edge3', source: 'node1', target: 'node1' }, ], }, edge: { style: { lineWidth: 2, endArrow: true, loopPlacement: (datum) => { const placements = ['top', 'right', 'bottom']; return placements[parseInt(datum.id.slice(-1)) - 1]; }, loopDist: 25, stroke: (datum) => { const colors = ['#1890FF', '#52C41A', '#722ED1']; return colors[parseInt(datum.id.slice(-1)) - 1]; }, }, }, }); graph.render(); ``` 以下为完整的自环边样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ---- | | loop | 是否启用自环边 | boolean | true | | | loopClockwise | 指定是否顺时针绘制环 | boolean | true | | | loopDist | 从节点边缘到自环顶部的距离,用于指定自环的曲率 | number | 默认为节点尺寸的最大值 | | | loopPlacement | 自环边的位置 | `left` \| `right` \| `top` \| `bottom` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` | `top` | | ## State 在一些交互行为中,比如点击选中一个边或鼠标悬停激活一个边,仅仅是在该元素做了某些状态的标识。为了将这些状态反应到终端用户所见的视觉空间中,我们需要为不同的状态设置不同的图元素样式,以响应该图元素状态的变化。 G6 提供了几种内置的状态,包括选中(selected)、高亮(highlight)、激活(active)、不活跃(inactive)和禁用(disabled)。此外,它还支持自定义状态,以满足更特定的需求。对于每个状态,开发者可以定义一套样式规则,这些规则会覆盖元素的默认样式。 数据结构如下: ```typescript type EdgeState = { [state: string]: EdgeStyle; }; ``` 例如,当边处于 `focus` 状态时,可以为其添加一个宽度为 6 且颜色为橙色的光晕。 ```js {4-9} const graph = new Graph({ edge: { state: { focus: { halo: true, haloLineWidth: 6, haloStroke: 'orange', haloStrokeOpacity: 0.6, }, }, }, }); ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 100, data: { nodes: [{ id: 'node1' }, { id: 'node2' }], edges: [{ source: 'node1', target: 'node2', states: ['focus'] }], }, edge: { state: { focus: { halo: true, haloLineWidth: 6, haloStroke: 'orange', }, }, }, layout: { type: 'grid', cols: 2, }, }); graph.render(); ``` ## Animation 定义边的动画效果,支持下列两种配置方式: 1. 关闭边全部动画 ```json { "edge": { "animation": false } } ``` 2. 配置阶段动画 阶段动画是指边在进入画布、更新、离开画布时的动画效果。目前支持的阶段包括: - `enter`: 边进入画布时的动画 - `update`: 边更新时的动画 - `exit`: 边离开画布时的动画 - `show`: 边从隐藏状态显示时的动画 - `hide`: 边隐藏时的动画 - `collapse`: 边收起时的动画 - `expand`: 边展开时的动画 你可以参考 [动画范式](/zh/manual/animation/animation/#动画范式) 使用动画语法来配置边,如: ```json { "edge": { "animation": { "update": [ { "fields": ["stroke"], // 更新时只对 stroke 属性进行动画 "duration": 1000, // 动画持续时间 "easing": "linear" // 缓动函数 } ] } } } ``` 也可以使用内置的动画效果: ```json { "edge": { "animation": { "enter": "fade", // 使用渐变动画 "update": "path-in", // 使用路径动画 "exit": "fade" // 使用渐变动画 } } } ``` 你可以传入 false 来关闭特定阶段的动画: ```json { "edge": { "animation": { "enter": false // 关闭边入场动画 } } } ``` ## Palette 定义边的色板,即预定义边颜色池,并根据规则进行分配,将颜色映射到 `stroke` 属性。 > 有关色板的定义,请参考 [色板](/zh/manual/theme/palette/)。 | 属性 | 描述 | 类型 | 默认值 | | ------ | ------------------------------------------------------------------- | ----------------------------- | ------- | | color | 色板颜色。如果色板注册过,可以直接指定其注册名,也接受一个颜色数组 | string \| string[] | - | | field | 指定元素数据中的分组字段。若不指定,默认取 id 作为分组字段 | string \| ((datum) => string) | `id` | | invert | 是否反转色板 | boolean | false | | type | 指定当前色板类型。
- `group`: 离散色板
- `value`: 连续色板 | `group` \| `value` | `group` | 如将一组数据按 `direction` 字段分配边颜色,使得同类别的边颜色相同: ```json { "edge": { "palette": { "type": "group", "field": "direction", "color": ["#F08F56", "#00C9C9", "#D580FF"] } } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: new Array(6).fill(0).map((_, i) => ({ id: `node-${i + 1}` })), edges: [ { source: 'node-1', target: 'node-2', data: { direction: 'out' } }, { source: 'node-1', target: 'node-3', data: { direction: 'out' } }, { source: 'node-1', target: 'node-4', data: { direction: 'out' } }, { source: 'node-5', target: 'node-1', data: { direction: 'in' } }, { source: 'node-6', target: 'node-1', data: { direction: 'in' } }, ], }, layout: { type: 'radial', unitRadius: 120, linkDistance: 120, }, edge: { style: { endArrow: true, }, palette: { type: 'group', field: 'direction', color: ['#F08F56', '#00C9C9'], }, }, }); graph.render(); ``` 也可以使用默认配置: ```json { "edge": { "palette": "tableau" // tableau 为色板名,默认根据 ID 分配颜色 } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: new Array(6).fill(0).map((_, i) => ({ id: `node-${i + 1}` })), edges: [ { source: 'node-1', target: 'node-2', data: { direction: 'out' } }, { source: 'node-1', target: 'node-3', data: { direction: 'out' } }, { source: 'node-1', target: 'node-4', data: { direction: 'out' } }, { source: 'node-5', target: 'node-1', data: { direction: 'in' } }, { source: 'node-6', target: 'node-1', data: { direction: 'in' } }, ], }, layout: { type: 'radial', unitRadius: 120, linkDistance: 120, }, edge: { style: { endArrow: true, }, palette: 'tableau', }, }); graph.render(); ``` #### 节点通用配置项 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/BaseNode/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/BaseNode.md - Description: 节点通用配置项 --- title: "节点通用配置项" description: "节点通用配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/BaseNode/" version: "5.1.1" --- 本文介绍内置节点通用属性配置。 ## NodeOptions ```js {5-9} import { Graph } from '@antv/g6'; const graph = new Graph({ node: { type: 'circle', // 节点类型 style: {}, // 节点样式 state: {}, // 状态样式 palette: {}, // 色板配置 animation: {}, // 动画配置 }, }); ``` | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------- | ----------------------- | -------- | ---- | | type | 节点类型,内置节点类型名称或自定义节点的名称 | [Type](#type) | `circle` | | | style | 节点样式配置,包括颜色、大小等 | [Style](#style) | - | | | state | 不同状态下的样式配置 | [State](#state) | - | | | palette | 定义节点的色板,用于根据不同数据映射颜色 | [Palette](#palette) | - | | | animation | 定义节点的动画效果 | [Animation](#animation) | - | | ## Type 指定节点类型,内置节点类型名称或自定义节点的名称。默认为 `circle`(圆形)。**⚠️ 注意**:这里决定了主图形的形状。 ```js {3} const graph = new Graph({ node: { type: 'circle', }, }); ``` **⚠️ 动态配置说明**:`type` 属性同样支持动态配置,可以根据节点数据动态选择节点类型: ```js const graph = new Graph({ node: { // 静态配置 type: 'circle', // 动态配置 - 箭头函数形式 type: (datum) => datum.data.nodeType || 'circle', // 动态配置 - 普通函数形式(可访问 graph 实例) type: function (datum) { console.log(this); // graph 实例 return datum.data.category === 'important' ? 'diamond' : 'circle'; }, }, }); ``` 可选值有: - `circle`:[圆形节点](/zh/manual/element/node/Circle/) - `diamond`:[菱形节点](/zh/manual/element/node/Diamond/) - `donut`:[甜甜圈节点](/zh/manual/element/node/Donut/) - `ellipse`:[椭圆节点](/zh/manual/element/node/Ellipse/) - `hexagon`:[六边形节点](/zh/manual/element/node/Hexagon/) - `html`:[HTML 节点](/zh/manual/element/node/Html/) - `image`:[图片节点](/zh/manual/element/node/Image/) - `rect`:[矩形节点](/zh/manual/element/node/Rect/) - `star`:[星形节点](/zh/manual/element/node/Star/) - `triangle`:[三角形节点](/zh/manual/element/node/Triangle/) ## Style 定义节点的样式,包括颜色、大小等。 ```js {3} const graph = new Graph({ node: { style: {}, }, }); ``` **⚠️ 动态配置说明**:以下所有样式属性都支持动态配置,即可以传入函数来根据节点数据动态计算属性值: ```js const graph = new Graph({ node: { style: { // 静态配置 fill: '#1783FF', // 动态配置 - 箭头函数形式 stroke: (datum) => (datum.data.isActive ? '#FF0000' : '#000000'), // 动态配置 - 普通函数形式(可访问 graph 实例) lineWidth: function (datum) { console.log(this); // graph 实例 return datum.data.importance > 5 ? 3 : 1; }, // 嵌套属性也支持动态配置 labelText: (datum) => `节点: ${datum.id}`, badges: (datum) => datum.data.tags.map((tag) => ({ text: tag })), }, }, }); ``` 其中 `datum` 参数为节点数据对象 (`NodeData`),包含节点的所有数据信息。 一个完整的节点由以下几部分构成: - `key` :节点的主图形,表示节点的主要形状,例如矩形、圆形等; - `label` :文本标签,通常用于展示节点的名称或描述; - `icon` :图标图形,通常用于展示节点的图标,可以是图片或者文本图标; - `badge` :默认位于节点右上角的徽标; - `halo` :主图形周围展示的光晕效果的图形; - `port` :节点上的连接点,用于连接边。 以下样式配置将按原子图形依次说明: ### 主图形样式 主图形是节点的核心部分,定义了节点的基本形状和外观。以下是常见的配置场景: #### 基础样式配置 设置节点的基本外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#5B8FF9', // 蓝色填充 stroke: '#1A1A1A', // 深色描边 lineWidth: 2, size: 40, }, }, }); graph.render(); ``` #### 透明度和阴影效果 为节点添加透明度和阴影效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#61DDAA', fillOpacity: 0.85, shadowColor: 'rgba(97, 221, 170, 0.4)', shadowBlur: 12, shadowOffsetX: 2, shadowOffsetY: 4, stroke: '#F0F0F0', lineWidth: 1, }, }, }); graph.render(); ``` #### 虚线边框样式 创建带虚线边框的节点: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#FFF1F0', stroke: '#F5222D', lineWidth: 2, lineDash: [6, 4], lineCap: 'round', }, }, }); graph.render(); ``` 以下为完整的主图形样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------- | --------- | ---- | | collapsed | 当前节点/组合是否折叠 | boolean | false | | | cursor | 节点鼠标移入样式,[配置项](#cursor) | string | default | | | fill | 节点填充色 | string | `#1783FF` | | | fillOpacity | 节点填充色透明度 | number \| string | 1 | | | increasedLineWidthForHitTesting | 当 lineWidth 较小时,可交互区域也随之变小,有时我们想增大这个区域,让"细线"更容易被拾取到 | number | 0 | | | lineCap | 节点描边端点样式 | `round` \| `square` \| `butt` | `butt` | | | lineDash | 节点描边虚线样式 | number[] | - | | | lineDashOffset | 节点描边虚线偏移量 | number | - | | | lineJoin | 节点描边连接处样式 | `round` \| `bevel` \| `miter` | `miter` | | | lineWidth | 节点描边宽度 | number | 1 | | | opacity | 节点透明度 | number \| string | 1 | | | pointerEvents | 节点如何响应指针事件,[配置项](#pointerevents) | string | `auto` | | | shadowBlur | 节点阴影模糊度 | number | - | | | shadowColor | 节点阴影颜色 | string | - | | | shadowOffsetX | 节点阴影在 x 轴方向上的偏移量 | number \| string | - | | | shadowOffsetY | 节点阴影在 y 轴方向上的偏移量 | number \| string | - | | | shadowType | 节点阴影类型 | `inner` \| `outer` | `outer` | | | size | 节点大小,快捷设置节点宽高,[配置项](#size) | number \| number[] | 32 | | | stroke | 节点描边色 | string | `#000` | | | strokeOpacity | 节点描边色透明度 | number \| string | 1 | | | transform | transform 属性允许你旋转、缩放、倾斜或平移给定节点 | string | - | | | transformOrigin | 旋转与缩放中心,也称作变换中心 | string | - | | | visibility | 节点是否可见 | `visible` \| `hidden` | `visible` | | | x | 节点 x 坐标 | number | 0 | | | y | 节点 y 坐标 | number | 0 | | | z | 节点 z 坐标 | number | 0 | | | zIndex | 节点渲染层级 | number | 0 | | #### Size 节点大小,快捷设置节点宽高,支持三种配置方式: - number:表示节点宽高相同为指定值 - [number, number]:表示节点宽高分别为数组元素依次表示节点的宽度、高度 - [number, number, number]:表示节点宽高分别为数组元素依次表示节点的宽度、高度以及深度 #### PointerEvents `pointerEvents` 属性控制图形如何响应交互事件,可参考 [MDN 文档](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)。 可选值有:`visible` | `visiblepainted` | `visiblestroke` | `non-transparent-pixel` | `visiblefill` | `visible` | `painted` | `fill` | `stroke` | `all` | `none` | `auto` | `inherit` | `initial` | `unset` 简而言之,`fill`、`stroke` 和 `visibility` 都可以独立或组合影响拾取判定行为。目前支持以下关键词: - **`auto`**:默认值,等同于 `visiblepainted` - **`none`**:永远不会成为响应事件的目标 - **`visiblepainted`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充区域触发同时 `fill` 取非 `none` 的值;或者在图形描边区域触发同时 `stroke` 取非 `none` 的值 - **`visiblefill`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充区域触发,不受 `fill` 取值的影响 - **`visiblestroke`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形描边区域触发,不受 `stroke` 取值的影响 - **`visible`**:满足以下条件才会响应事件: - `visibility` 设置为 `visible`,即图形为可见的 - 在图形填充或者描边区域触发,不受 `fill` 和 `stroke` 取值的影响 - **`painted`**:满足以下条件才会响应事件: - 在图形填充区域触发同时 `fill` 取非 `none` 的值;或者在图形描边区域触发同时 `stroke` 取非 `none` 的值 - 不受 `visibility` 取值的影响 - **`fill`**:满足以下条件才会响应事件: - 在图形填充区域触发,不受 `fill` 取值的影响 - 不受 `visibility` 取值的影响 - **`stroke`**:满足以下条件才会响应事件: - 在图形描边区域触发,不受 `stroke` 取值的影响 - 不受 `visibility` 取值的影响 - **`all`**:只要进入图形的填充和描边区域就会响应事件,不会受 `fill`、`stroke`、`visibility` 的取值影响 **使用示例:** ```js // 示例1:只有描边区域响应事件 const graph = new Graph({ node: { style: { fill: 'none', stroke: '#000', lineWidth: 2, pointerEvents: 'stroke', // 只有描边响应事件 }, }, }); // 示例2:完全不响应事件 const graph = new Graph({ node: { style: { pointerEvents: 'none', // 节点不响应任何事件 }, }, }); ``` #### Cursor 可选值有:`auto` | `default` | `none` | `context-menu` | `help` | `pointer` | `progress` | `wait` | `cell` | `crosshair` | `text` | `vertical-text` | `alias` | `copy` | `move` | `no-drop` | `not-allowed` | `grab` | `grabbing` | `all-scroll` | `col-resize` | `row-resize` | `n-resize` | `e-resize` | `s-resize` | `w-resize` | `ne-resize` | `nw-resize` | `se-resize` | `sw-resize` | `ew-resize` | `ns-resize` | `nesw-resize` | `nwse-resize` | `zoom-in` | `zoom-out` ### 标签样式 标签用于显示节点的文本信息,支持多种样式配置和布局方式。以下是常见的使用场景: #### 基础文本标签 最简单的文本标签配置: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 120, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { labelText: '节点名称', labelFill: '#262626', labelFontSize: 12, labelPlacement: 'bottom', }, }, }); graph.render(); ``` #### 多行文本标签 当文本较长时,可以设置自动换行: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 120, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { labelText: '这是一个很长的节点名称需要换行显示', labelWordWrap: true, labelMaxWidth: '150%', labelMaxLines: 3, labelTextOverflow: 'ellipsis', labelFill: '#434343', labelPlacement: 'bottom', labelTextAlign: 'center', }, }, }); graph.render(); ``` #### 带背景的标签 为标签添加背景,提高可读性: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 120, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { labelText: '重要节点', labelBackground: true, labelBackgroundFill: 'rgba(250, 140, 22, 0.1)', labelBackgroundRadius: 6, labelPadding: [6, 12], labelFill: '#D4380D', labelFontWeight: 'bold', labelPlacement: 'bottom', }, }, }); graph.render(); ``` 以下为完整的标签样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------ | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------- | ---- | | label | 是否显示节点标签 | boolean | true | | | labelCursor | 鼠标移入节点标签时显示的样式,[配置项](#cursor) | string | `default` | | | labelFill | 节点标签文字颜色 | string | - | | | labelFontFamily | 节点标签字体族 | string | - | | | labelFontSize | 节点标签字体大小 | number | 12 | | | labelFontStyle | 节点标签字体样式 | `normal` \| `italic` \| `oblique` | - | | | labelFontVariant | 节点标签字体变种 | `normal` \| `small-caps` \| string | - | | | labelFontWeight | 节点标签字体粗细 | `normal` \| `bold` \| `bolder` \| `lighter` \| number | - | | | labelLeading | 行间距 | number | 0 | | | labelLetterSpacing | 节点标签字间距 | number \| string | - | | | labelLineHeight | 节点标签行高 | number \| string | - | | | labelMaxLines | 节点标签最大行数 | number | 1 | | | labelMaxWidth | 节点标签最大宽度,[配置项](#labelmaxwidth) | number \| string | `200%` | | | labelOffsetX | 节点标签在 x 轴方向上的偏移量 | number | 0 | | | labelOffsetY | 节点标签在 y 轴方向上的偏移量 | number | 0 | | | labelPadding | 节点标签内边距 | number \| number[] | 0 | | | labelPlacement | 节点标签相对于节点主图形的位置,[配置项](#labelplacement) | string | `bottom` | | | labelText | 节点标签文字内容 | `string` \| `(datum) => string` | - | | | labelTextAlign | 节点标签文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | | labelTextBaseline | 节点标签文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | - | | | labelTextDecorationColor | 节点标签文本装饰线颜色 | string | - | | | labelTextDecorationLine | 节点标签文本装饰线 | string | - | | | labelTextDecorationStyle | 节点标签文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | - | | | labelTextOverflow | 节点标签文本溢出处理方式 | `clip` \| `ellipsis` \| string | - | | | labelTextPath | 节点标签文本路径 | Path | - | | | labelWordWrap | 节点标签是否开启自动折行。开启 labelWordWrap 后,超出 labelMaxWidth 的部分自动换行 | boolean | false | | | labelZIndex | 节点标签渲染层级 | number | 0 | | #### LabelPlacement 可选值有:`left` | `right` | `top` | `bottom` | `left-top` | `left-bottom` | `right-top` | `right-bottom` | `top-left` | `top-right` | `bottom-left` | `bottom-right` | `center` | `bottom` #### LabelMaxWidth 开启自动折行 `labelWordWrap` 后,超出该宽度则换行: - string: 表示以相对于节点宽度的百分比形式定义最大宽度。例如 `50%` 表示标签宽度不超过节点宽度的一半 - number: 表示以像素值为单位定义最大宽度。例如 100 表示标签的最大宽度为 100 像素 比如,设置多行标签文字: ```json { "labelWordWrap": true, "labelMaxWidth": 200, "labelMaxLines": 3 } ``` ### 标签背景样式 标签背景用于显示节点标签的背景: | 属性 | 描述 | 类型 | 默认值 | | ----------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | --------- | | labelBackground | 节点标签背景是否显示 | boolean | false | | labelBackgroundCursor | 节点标签背景鼠标移入样式,[配置项](#cursor) | string | `default` | | labelBackgroundFill | 节点标签背景填充色 | string | - | | labelBackgroundFillOpacity | 节点标签背景透明度 | number | 1 | | labelBackgroundHeight | 节点标签背景高度 | string \| number | - | | labelBackgroundLineDash | 节点标签背景虚线配置 | number \| string \|(number \| string )[] | - | | labelBackgroundLineDashOffset | 节点标签背景虚线偏移量 | number | - | | labelBackgroundLineWidth | 节点标签背景描边线宽 | number | - | | labelBackgroundRadius | 节点标签背景圆角半径
- number: 统一设置四个圆角半径
- number[]: 分别设置四个圆角半径,不足则自动补充 | number \| number[] | 0 | | labelBackgroundShadowBlur | 节点标签背景阴影模糊程度 | number | - | | labelBackgroundShadowColor | 节点标签背景阴影颜色 | string | - | | labelBackgroundShadowOffsetX | 节点标签背景阴影 X 方向偏移 | number | - | | labelBackgroundShadowOffsetY | 节点标签背景阴影 Y 方向偏移 | number | - | | labelBackgroundStroke | 节点标签背景描边颜色 | string | - | | labelBackgroundStrokeOpacity | 节点标签背景描边透明度 | number \| string | 1 | | labelBackgroundVisibility | 节点标签背景是否可见 | `visible` \| `hidden` | - | | labelBackgroundZIndex | 节点标签背景渲染层级 | number | 1 | ### 光晕样式 光晕是围绕节点主图形显示的效果,通常用于高亮显示或表示节点的特殊状态。 #### 基础光晕效果 为节点添加基本的光晕效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { lineWidth: 1.5, halo: true, haloStroke: '#1890FF', haloLineWidth: 6, haloStrokeOpacity: 0.3, }, }, }); graph.render(); ``` 以下为完整的光晕样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------------- | ---------------------------------------------------------------------- | ---------------------- | ---------------------------- | ---- | | halo | 节点光晕是否显示 | boolean | false | | | haloCursor | 节点光晕鼠标移入样式,[配置项](#cursor) | strig | `default` | | | haloDraggable | 节点光晕是否允许拖拽 | boolean | true | | | haloDroppable | 节点光晕是否允许接收被拖拽的元素 | boolean | true | | | haloFillRule | 节点光晕填充规则 | `nonzero` \| `evenodd` | - | | | haloFilter | 节点光晕滤镜 | string | - | | | haloLineWidth | 节点光晕描边宽度 | number | 3 | | | haloPointerEvents | 节点光晕效果是否响应指针事件,[配置项](#pointerevents) | string | `none` | | | haloStroke | 节点光晕描边色,**此属性用于设置节点周围光晕的颜色,帮助突出显示节点** | string | 与主图形的填充色 `fill` 一致 | | | haloStrokeOpacity | 节点光晕描边色透明度 | number | 0.25 | | | haloVisibility | 节点光晕可见性 | `visible` \| `hidden` | `visible` | | | haloZIndex | 节点光晕渲染层级 | number | -1 | | ### 图标样式 节点图标支持三种常见的使用方式:文字图标、图片图标和 IconFont 图标。下面分别展示这三种方式的配置: #### 1. 文字图标 直接使用文字作为图标,适合简单的标识: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#FFF0F6', stroke: '#EB2F96', lineWidth: 1.5, iconText: 'A', // 图标文字内容 iconFill: '#C41D7F', // 深粉色图标 iconFontSize: 16, iconFontWeight: 'bold', }, }, }); graph.render(); ``` #### 2. 图片图标 使用图片作为图标,支持各种图片格式: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#F6FFED', stroke: '#52C41A', lineWidth: 1.5, iconSrc: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEyIDJMMTMuMDkgOC4yNkwyMSA5TDEzLjA5IDE1Ljc4TDEyIDIyTDEwLjkxIDE1Ljc4TDMgOUwxMC45MSA4LjI2TDEyIDJaIiBmaWxsPSIjNTJDNDFBIi8+Cjwvc3ZnPgo=', iconWidth: 20, iconHeight: 20, }, }, }); graph.render(); ``` #### 3. IconFont 图标 使用 IconFont 字体图标,需要先引入相应的字体文件: ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { fill: '#E6F7FF', // 淡蓝色背景 stroke: '#1890FF', // 蓝色边框 lineWidth: 1.5, iconFontFamily: 'iconfont', iconText: '\ue602', iconFill: '#1890FF', }, }, }); graph.render(); ``` 以下为完整的图标样式配置: | 属性 | 描述 | 类型 | 默认值 | | ----------------------- | ----------------------------------- | --------------------------------------------------------------------------- | ---------------- | | icon | 是否显示节点图标 | boolean | true | | iconFill | 节点图标文字颜色 | string | - | | iconFontFamily | 节点图标字体族 | string | - | | iconFontSize | 节点图标字体大小 | number | 16 | | iconFontStyle | 节点图标字体样式 | `normal` \| `italic` \| `oblique` | `normal` | | iconFontVariant | 节点图标字体变种 | `normal` \| `small-caps` \| string | `normal` | | iconFontWeight | 节点图标字体粗细 | number \| string | `normal` | | iconHeight | 节点图标高度 | number | 主图形高度的一半 | | iconLetterSpacing | 节点图标文本字间距 | number \| string | - | | iconLineHeight | 节点图标文本行高 | number \| string | - | | iconMaxLines | 节点图标文本最大行数 | number | 1 | | iconRadius | 节点图标圆角半径 | number | 0 | | iconSrc | 节点图片来源。其优先级高于 iconText | string \| ((datum) => string) | - | | iconText | 节点图标文字 | string \| ((datum) => string) | - | | iconTextAlign | 节点图标文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | iconTextBaseline | 节点图标文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | `alphabetic` | | iconTextDecorationColor | 节点图标文本装饰线颜色 | string | - | | iconTextDecorationLine | 节点图标文本装饰线 | string | - | | iconTextDecorationStyle | 节点图标文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | `solid` | | iconTextOverflow | 节点图标文本溢出处理方式 | `clip` \| `ellipsis` \| string | `clip` | | iconWidth | 节点图标宽度 | number | 主图形宽度的一半 | | iconWordWrap | 节点图标文本是否自动换行 | boolean | - | ### 徽标样式 徽标是节点上显示的小标记,通常用于展示状态、数量或其他辅助信息。支持多个徽标同时显示,并可自定义位置。 #### 单个徽标 为节点添加一个简单的徽标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { badges: [ { text: 'NEW' }, // 默认显示在上方 ], }, }, }); graph.render(); ``` #### 多个徽标 为节点添加多个不同位置的徽标: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { badge: true, // 是否显示徽标 badges: [ { text: 'A', placement: 'right-top' }, { text: 'Important', placement: 'right' }, { text: 'Notice', placement: 'right-bottom' }, ], badgePalette: ['#7E92B5', '#F4664A', '#FFBE3A'], // 徽标的背景色板 badgeFontSize: 7, // 徽标字体大小 }, }, }); graph.render(); ``` #### 自定义徽标样式 完全自定义徽标的外观: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { badges: [ { text: '99+', placement: 'right-top', backgroundFill: '#FF4D4F', // 红色背景 fill: '#fff', // 白色文字 fontSize: 10, padding: [2, 6], backgroundRadius: 8, }, ], }, }, }); graph.render(); ``` 以下为完整的徽标样式配置: | 属性 | 描述 | 类型 | 默认值 | | ------------ | ------------------ | ------------------------------------- | --------------------------------- | | badge | 节点是否显示徽标 | boolean | true | | badgePalette | 节点徽标的背景色板 | string[] | [`#7E92B5`, `#F4664A`, `#FFBE3A`] | | badges | 节点徽标设置 | [BadgeStyleProps](#badgestyleprops)[] | - | #### BadgeStyleProps | 属性 | 描述 | 类型 | 默认值 | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | | background | 节点徽标是否显示背景 | boolean | true | | backgroundCursor | 节点徽标背景鼠标移入样式,[配置项](#cursor) | string | `default` | | backgroundFill | 节点徽标背景填充色。若不指定,优先考虑 badgePalette 按顺序分配 | string | - | | backgroundFillOpacity | 节点徽标背景填充透明度 | number | 1 | | backgroundFilter | 节点徽标背景滤镜 | string | - | | backgroundHeight | 节点徽标背景高度 | number \| string | - | | backgroundLineDash | 节点徽标背景虚线配置 | number \| string \|(number \| string )[] | - | | backgroundLineDashOffset | 节点徽标背景虚线偏移量 | number | - | | backgroundLineWidth | 节点徽标背景描边线宽 | number | - | | backgroundRadius | 节点徽标背景圆角半径
- number: 统一设置四个圆角半径
- number[]: 分别设置四个圆角半径,会补足缺省的分量
- string: 与 [CSS padding](https://developer.mozilla.org/zh-CN/docs/Web/CSS/padding) 属性类似,使用空格分隔 | number \| number[] \| string | 0 | | backgroundShadowBlur | 节点徽标背景阴影模糊程度 | number | - | | backgroundShadowColor | 节点徽标背景阴影颜色 | string | - | | backgroundShadowOffsetX | 节点徽标背景阴影 X 方向偏移 | number | - | | backgroundShadowOffsetY | 节点徽标背景阴影 Y 方向偏移 | number | - | | backgroundStroke | 节点徽标背景描边颜色 | string | - | | backgroundStrokeOpacity | 节点徽标背景描边透明度 | number \| string | 1 | | backgroundVisibility | 节点徽标背景是否可见 | `visible` \| `hidden` | - | | backgroundZIndex | 节点徽标背景渲染层级 | number | - | | fill | 节点徽标文字颜色 | string | - | | fontFamily | 节点徽标字体族 | string | - | | fontSize | 节点徽标字体大小 | number | 8 | | fontStyle | 节点徽标字体样式 | `normal` \| `italic` \| `oblique` | `normal` | | fontVariant | 节点徽标字体变种 | `normal` \| `small-caps` \| string | `normal` | | fontWeight | 节点徽标字体粗细 | number \| string | `normal` | | lineHeight | 节点徽标行高 | string \| number | - | | lineWidth | 节点徽标行宽 | string \| number | - | | maxLines | 节点徽标文本最大行数 | number | 1 | | offsetX | 节点徽标在 x 轴方向上的偏移量 | number | 0 | | offsetY | 节点徽标在 y 轴方向上的偏移量 | number | 0 | | padding | 节点徽标内边距 | number \| number[] | 0 | | placement | 节点徽标相对于节点主图形的位置。若不指定,默认从右上角顺时针依次排放 | `left` \| `right` \| `top` \| `bottom` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` | - | | text | 节点徽标文字内容 | string | - | | textAlign | 节点徽标文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | `left` | | textBaseline | 节点徽标文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom` | `alphabetic` | | textDecorationColor | 节点徽标文本装饰线颜色 | string | - | | textDecorationLine | 节点徽标文本装饰线 | string | - | | textDecorationStyle | 节点徽标文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | `solid` | | textOverflow | 节点徽标文本溢出处理方式 | `clip` \| `ellipsis` \| string | `clip` | | visibility | 节点徽标是否可见 | `visible` \| `hidden` | - | | wordWrap | 节点徽标文本是否自动换行 | boolean | - | | zIndex | 节点徽标渲染层级 | number | 3 | ### 连接桩样式 连接桩是节点上的连接点,用于连接边。支持在节点的不同位置添加多个连接桩,并可自定义样式。 #### 基础连接桩 为节点添加四个基本方向的连接桩: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { port: true, ports: [ { key: 'top', placement: 'top', fill: '#7E92B5' }, { key: 'right', placement: 'right', fill: '#F4664A' }, { key: 'bottom', placement: 'bottom', fill: '#FFBE3A' }, { key: 'left', placement: 'left', fill: '#D580FF' }, ], portR: 3, portLineWidth: 1, portStroke: '#fff', }, }, }); graph.render(); ``` #### 自定义位置连接桩 使用百分比或绝对坐标精确定位连接桩: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { ports: [ { key: 'custom1', placement: [0.2, 0] }, // 相对位置:左上角20%处 { key: 'custom2', placement: [0.8, 0] }, // 相对位置:右上角80%处 { key: 'custom3', placement: [1, 0.5] }, // 相对位置:右边中央 ], portR: 4, portLineWidth: 1, portStroke: '#fff', }, }, }); graph.render(); ``` #### 差异化连接桩样式 为不同的连接桩设置不同的样式: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1' }] }, node: { style: { ports: [ { key: 'input', placement: 'left', fill: '#52C41A', // 绿色输入桩 r: 4, }, { key: 'output', placement: 'right', fill: '#FF4D4F', // 红色输出桩 r: 4, }, ], portStroke: '#fff', // 统一的描边颜色 portLineWidth: 2, }, }, }); graph.render(); ``` 以下为完整的连接桩样式配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----- | ------------------------------------ | ----------------------------------- | ------ | ---- | | port | 节点是否显示连接桩 | boolean | true | | | ports | 节点连接桩配置项,支持配置多个连接桩 | [PortStyleProps](#portstyleprops)[] | | | #### PortStyleProps | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | ---- | | key | 节点连接桩的键值,默认为节点连接桩的索引 | string | - | | | placement | 节点连接桩相对于节点主图形的位置 | `left` \| `right` \| `top` \| `bottom` \| `center` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` \| [number, number] | - | ✓ | | r | 节点连接桩半径
- 如果设置为 undefined,则连接桩被视为一个点,不在画布上显示但存在,边会优先连接到最近的连接桩
- 如果设置为数字,则连接桩被视为一个圆,圆的半径由此处指定 | number | - | | | linkToCenter | 边是否连接到节点连接桩的中心
- 若为 true,则边连接到节点连接桩的中心
- 若为 false,则边连接到节点连接桩的边缘 | boolean | false | | | cursor | 节点连接桩鼠标移入样式,[配置项](#cursor) | string | `default` | | | fill | 节点连接桩填充颜色 | string | - | | | fillOpacity | 节点连接桩填充透明度 | number | 1 | | | isBillboard | 节点连接桩是否为Billboard 效果 | boolean | - | | | isSizeAttenuation | 节点连接桩是否启用大小衰减 | boolean | - | | | lineDash | 节点连接桩描边虚线配置 | number \| string \|(number \| string )[] | - | | | lineDashOffset | 节点连接桩描边虚线偏移量 | number | - | | | lineWidth | 节点连接桩描边线宽 | number | - | | | shadowBlur | 节点连接桩阴影模糊程度 | number | - | | | shadowColor | 节点连接桩阴影颜色 | string | - | | | shadowOffsetX | 节点连接桩阴影 X 方向偏移 | number | - | | | shadowOffsetY | 节点连接桩阴影 Y 方向偏移 | number | - | | | stroke | 节点连接桩描边颜色 | string | - | | | strokeOpacity | 节点连接桩描边透明度 | number \| string | 1 | | | visibility | 节点连接桩是否可见 | `visible` \| `hidden` | `visible` | | | zIndex | 节点连接桩渲染层级 | number | 2 | | ## State 在一些交互行为中,比如点击选中一个节点或鼠标悬停激活一个边,仅仅是在该元素做了某些状态的标识。为了将这些状态反应到终端用户所见的视觉空间中,我们需要为不同的状态设置不同的图元素样式,以响应该图元素状态的变化。 G6 提供了几种内置的状态,包括选中(selected)、高亮(highlight)、激活(active)、不活跃(inactive)和禁用(disabled)。此外,它还支持自定义状态,以满足更特定的需求。对于每个状态,开发者可以定义一套样式规则,这些规则会覆盖元素的默认样式。 数据结构如下: ```typescript type NodeState = { [state: string]: NodeStyle; }; ``` 例如,当节点处于 `focus` 状态时,可以为其添加一个宽度为 3 且颜色为橙色的描边。 ```js {4-7} const graph = new Graph({ node: { state: { focus: { lineWidth: 3, // 描边宽度 stroke: 'orange', // 描边颜色 }, }, }, }); ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, autoFit: 'center', data: { nodes: [{ id: 'node1', states: ['focus'] }], }, node: { state: { focus: { lineWidth: 3, stroke: 'orange', }, }, }, }); graph.render(); ``` ## Animation 定义节点的动画效果,支持下列两种配置方式: 1. 关闭节点全部动画 ```json { "node": { "animation": false } } ``` 2. 配置阶段动画 阶段动画是指节点在进入画布、更新、离开画布时的动画效果。目前支持的阶段包括: - `enter`: 节点进入画布时的动画 - `update`: 节点更新时的动画 - `exit`: 节点离开画布时的动画 - `show`: 节点从隐藏状态显示时的动画 - `hide`: 节点隐藏时的动画 - `collapse`: 节点收起时的动画 - `expand`: 节点展开时的动画 你可以参考 [动画范式](/zh/manual/animation/animation/#动画范式) 使用动画语法来配置节点,如: ```json { "node": { "animation": { "update": [ { "fields": ["x", "y"], // 更新时只对 x 和 y 属性进行动画 "duration": 1000, // 动画持续时间 "easing": "linear" // 缓动函数 } ], } } ``` 也可以使用内置的动画效果: ```json { "node": { "animation": { "enter": "fade", // 使用渐变动画 "update": "translate", // 使用平移动画 "exit": "fade" // 使用渐变动画 } } } ``` 你可以传入 false 来关闭特定阶段的动画: ```json { "node": { "animation": { "enter": false // 关闭节点入场动画 } } } ``` ## Palette 定义节点的色板,即预定义节点颜色池,并根据规则进行分配,将颜色映射到 `fill` 属性。 > 有关色板的定义,请参考 [色板](/zh/manual/theme/palette/)。 | 属性 | 描述 | 类型 | 默认值 | | ------ | ------------------------------------------------------------------- | ----------------------------- | ------- | | color | 色板颜色。如果色板注册过,可以直接指定其注册名,也接受一个颜色数组 | string \| string[] | - | | field | 指定元素数据中的分组字段。若不指定,默认取 id 作为分组字段 | string \| ((datum) => string) | `id` | | invert | 是否反转色板 | boolean | false | | type | 指定当前色板类型。
- `group`: 离散色板
- `value`: 连续色板 | `group` \| `value` | `group` | 如将一组数据按 `category` 字段分配节点颜色,使得同类别的节点颜色相同: ```json { "node": { "palette": { "type": "group", "field": "category", "color": ["#1783FF", "#F08F56", "#D580FF", "#00C9C9", "#7863FF"] } } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 100, data: { nodes: new Array(10) .fill(0) .map((_, i) => ({ id: `node-${i}`, data: { category: ['A', 'B', 'C', 'D', 'E'][i % 5] } })), }, layout: { type: 'grid', cols: 10 }, node: { palette: { type: 'group', field: 'category', color: ['#1783FF', '#F08F56', '#D580FF', '#00C9C9', '#7863FF'], }, }, }); graph.render(); ``` 也可以使用默认配置: ```json { "node": { "palette": "tableau" // tableau 为色板名,默认根据 ID 分配颜色 } } ``` 效果如下图所示: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 100, data: { nodes: new Array(10) .fill(0) .map((_, i) => ({ id: `node-${i}`, data: { category: ['A', 'B', 'C', 'D', 'E'][i % 5] } })), }, layout: { type: 'grid', cols: 10 }, node: { palette: 'tableau', }, }); graph.render(); ``` #### 元素总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/overview.md - Description: 元素总览 --- title: "元素总览" description: "元素总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/overview/" version: "5.1.1" --- ## 元素体系 G6 图表的核心是由三种基本元素构成:**节点(Node)**、**边(Edge)** 和 **组合(Combo)**。这些元素是构建复杂图形网络的基础单元。 ### 节点 (Node) [节点](/zh/manual/element/node/overview/) 表示图中的实体或概念,如人物、地点、对象等。G6 提供了丰富的内置节点类型: G6 还支持 [使用 React 定义节点](/zh/manual/element/node/react-node/) 或 [自定义节点](/zh/manual/element/node/custom-node/) 以满足特定需求。 ### 边 (Edge) [边](/zh/manual/element/edge/overview/)表示节点间的连接关系,如朋友关系、交易往来等。G6 内置多种边类型: 当内置边不满足需求时,可以通过 [自定义边](/zh/manual/element/edge/custom-edge/) 来实现复杂的连接表现。 ### 组合 (Combo) [组合](/zh/manual/element/combo/overview/)是一种特殊元素,可以包含节点和其他组合,用于表示集合、分组或层级关系。G6 内置两种组合类型: - **圆形组合**(`circle`):适合紧凑型分组 - **矩形组合**(`rect`):适合规则布局的分组 组合支持嵌套、拖拽、展开/收起等交互,可以通过 [自定义组合](/zh/manual/element/combo/custom-combo/) 来实现更复杂的容器行为。 ## 元素构成原理 每个元素由一个或多个基础图形(Shape)组成。图形是 G6 中的最小图形单元,包括 [矩形](/zh/manual/element/shape/properties/#rectstyleprops)、[圆形](/zh/manual/element/shape/properties/#circlestyleprops)、[文本](/zh/manual/element/shape/properties/#textstyleprops)、[路径](/zh/manual/element/shape/properties/#pathstyleprops)等。 例如: - 一个节点可能由背景图形(如圆形)和文本标签组成 - 一条边可能由路径、箭头和文本标签组成 - 一个组合可能由容器图形、标题文本和展开/收起按钮组成 要了解更多关于图形的信息,请参阅 [图形 Shape 总览](/zh/manual/element/shape/overview/) 和 [Shape 样式属性](/zh/manual/element/shape/properties/)。 ## 元素状态 [元素状态](/zh/manual/element/state/) 是一种强大的机制,用于展示元素在不同交互或业务场景下的视觉变化。G6 提供了一套完整的状态管理系统: - **预设状态**:`selected`(选中)、`highlight`(高亮)、`active`(激活)等 - **状态叠加**:元素可同时拥有多个状态,样式按优先级叠加 - **自定义状态**:可根据业务需求定义任意状态 ## 配置元素 G6 5.x 采用扁平化的配置结构,所有元素的配置都在同一层级,便于查找和管理: ```typescript { node: { // 节点默认样式 style: { fill: 'orange', labelText: 'node', }, // 节点在不同状态下的样式 state: { selected: { stroke: '#1890FF', lineWidth: 2, } } }, edge: { // 边默认样式 style: { stroke: '#aaa', }, // 边在不同状态下的样式 state: { highlight: { stroke: 'red', } } }, combo: { // 组合默认样式 style: { fill: 'lightblue', stroke: 'blue', } } }; ``` 配置方式有三种,按优先级从高到低: 1. **使用实例方法动态配置**:如 `graph.setNode()`、`graph.setEdge()`、`graph.setCombo()` 2. **实例化图时全局配置**:在 `new Graph()` 时指定配置项 3. **在数据中配置**:在节点、边、组合的数据对象中设置 在 VSCode 等编辑器中,你可以看到元素的全部可配置属性,并基于关键字进行搜索: ## 扩展能力 G6 提供了强大的扩展能力,满足各种自定义需求: - **自定义节点**:[自定义节点指南](/zh/manual/element/node/custom-node/) - **自定义边**:[自定义边指南](/zh/manual/element/edge/custom-edge/) - **自定义组合**:[自定义组合指南](/zh/manual/element/combo/custom-combo/) - **React 节点**:[使用 React 定义节点](/zh/manual/element/node/react-node/) - **3D 扩展**:通过 `@antv/g6-extension-3d` 使用 3D 节点 ## 内置元素参考 ### 节点类型 - [内置节点库](/zh/manual/element/node/BaseNode/) ### 边类型 - [内置边库](/zh/manual/element/edge/BaseEdge/) ### 组合类型 - [内置组合库](/zh/manual/element/combo/BaseCombo/) #### 图形 Shape 与 KeyShape - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/shape/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/shape/overview.md - Description: 图形 Shape 与 KeyShape --- title: "图形 Shape 与 KeyShape" description: "图形 Shape 与 KeyShape" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/shape/overview/" version: "5.1.1" --- ## 图形 Shape Shape 指 G6 中的图形、形状,可以是圆形、矩形、路径等。它一般与 G6 中的节点、边、Combo 相关。**💡 G6 中的每一种节点/边/Combo 都是由一个或多个 Shape 组合而成。节点、边、Combo 的样式配置都会被体现到对应的图形上。** 例如下图(左)的节点包含了一个圆形图形;下图(中)的节点含有一个圆形和一个文本图形;下图(右)的节点中含有 5 个圆形(蓝绿色的圆和上下左右四个锚点)、一个文本图形。但每种节点/边/Combo 都会有自己的唯一关键图形 keyShape,下图中三个节点的 keyShape 都是蓝绿色的圆,keyShape 主要用于交互检测、样式随 [元素状态](/zh/manual/element/state/) 自动更新等,见 [keyShape](#keyshape)。 imgimgimg > (左)只含有一个圆形图形的节点,keyShape 是该圆形。(中)含有圆形和文本图形的节点,keyShape 是圆形。(右)含有主要圆形、文本、上下左右四个小圆形的节点,keyShape 是圆形。 G6 使用不同的 shape 组合,设计了多种内置的节点/边/ Combo 。G6 内置节点的有 'circle', 'rect','ellipse',...(详见 [内置节点](/zh/manual/element/node/BaseNode/));内置边的有 'line','polyline','cubic',...(详见 [内置边](/zh/manual/element/edge/BaseEdge/));内置 Combo 有 'circle','rect',(详见 [内置 Combo](/zh/manual/element/combo/BaseCombo/))。 除了使用内置的节点/边/ Combo 外,G6 还允许用户通过自己搭配和组合 shape 进行节点/边/ Combo 的自定义,详见 [自定义节点](/zh/manual/element/node/custom-node/),[自定义边](/zh/manual/element/edge/custom-edge/),[自定义 Combo](/zh/manual/element/combo/custom-combo/)。 ## KeyShape 在 G6 中,每个节点、边、Combo 都由一个或多个 Shape 组成,但其中有一个 Shape 被称为 keyShape,它是该元素的“关键图形”: > 节点的关键图形就是上图的颜色区域 ### 包围盒确定 **确定节点 / Combo 的包围盒(Bounding Box)** ,从而计算相关边的连入点(与相关边的交点)。若 keyShape 不同,节点与边的交点计算结果不同。 #### 示例   本例中的一个节点由一个 rect 图形和一个带灰色描边、填充透明的 circle 图形构成。 - 当节点的 keyShape 为 circle 时: img - 当节点的 keyShape 为 rect 时: img ## Shape 的生命周期 > 当用户需要 [自定义节点](/zh/manual/element/node/custom-node/)、[自定义边](/zh/manual/element/edge/custom-edge/)、[自定义 Combo](/zh/manual/element/combo/custom-combo/) 时,需要了解 Shape 的生命周期。使用内置节点/边/Combo 则可以跳过这一部分内容。 从整体来看,Shape 的生命周期分为: - **初始化渲染**:首次根据数据和样式配置绘制出 Shape。 - **更新**:当数据或样式发生变化时,自动更新 Shape 的表现。 - **操作**:响应交互状态(如 selected、active、hover 等),动态调整样式。 - **销毁**:Shape 被移除时的清理(通常由 Graph 自动管理,用户无需关心)。 在自定义 Shape 时,最常见的需求就是“如何高效地管理 Shape 的创建、更新和销毁”。G6 为此在 BaseShape 中设计了一个非常实用的方法: ### upsert 的原理与优势 upsert 是“update” 和 “insert” 的合成词,意思是“有则更新,无则创建”。它的作用可以简单理解为: - **自动判断**:你只需描述希望 Shape 呈现的样子,`upsert` 会自动判断当前 Shape 是否已存在。如果不存在则创建,如果已存在则更新,如果需要删除则自动移除。 - **简化逻辑**:开发者无需手动管理 Shape 的增删改查,避免了重复代码和状态混乱。 - **提升健壮性**:无论是初次渲染、数据变更还是状态切换,upsert 都能保证 Shape 始终与数据和配置保持同步。 **类型定义:** ```js /** * 创建、更新或删除图形 * @param className 图形名称 * @param Ctor 图形类型 * @param style 图形样式。若要删除图形,传入 false * @param container 容器 * @param hooks 钩子函数 * @returns 图形实例 */ upsert( className: string, Ctor: string | { new (...args: any[]): T }, style: T['attributes'] | false, container: DisplayObject, hooks?: UpsertHooks, ): T | undefined {} ``` 你只需要描述“我现在想要什么样的图形”,不用关心它是新建、更新还是删除,upsert 都会帮你处理好。这让自定义和管理复杂的复合 Shape 变得非常简单和安全。 #### 渲染器 - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/renderer/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/renderer.md - Description: 渲染器 --- title: "渲染器" description: "渲染器" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/renderer/" version: "5.1.1" --- G6 默认使用 Canvas 作为渲染器,但也支持通过 SVG 和 WebGL 进行渲染,要切换到 SVG 或 WebGL 渲染器,只需在初始化时传入 `renderer` 参数即可。 ## 使用 SVG 渲染器 1. 安装渲染器依赖: ```bash npm install @antv/g-svg ``` 2. 配置渲染器: ```javascript import { Renderer as SVGRenderer } from '@antv/g-svg'; import { Graph } from '@antv/g6'; const graph = new Graph({ // ... other options // 这里所有的画布都会使用 SVG 渲染器 renderer: () => new SVGRenderer(), }); ``` ## 使用 WebGL 渲染器 1. 安装渲染器依赖: ```bash npm install @antv/g-webgl ``` 2. 配置渲染器: ```javascript import { Renderer as WebGLRenderer } from '@antv/g-webgl'; import { Graph } from '@antv/g6'; const graph = new Graph({ // ... other options // 这里所有的画布都会使用 WebGL 渲染器 renderer: () => new WebGLRenderer(), }); ``` ## 分层使用不同的渲染器 G6 采用了分层画布进行渲染,因此 `renderer` 是一个回调函数,参数是画布类型,返回渲染器实例,如果你想在不同的画布上使用不同的渲染器,可以这样配置: ```javascript import { Renderer as SVGRenderer } from '@antv/g-svg'; import { Renderer as WebGLRenderer } from '@antv/g-webgl'; const graph = new Graph({ // ... other options renderer: (layer) => { // 主画布使用 WebGL 渲染器,其他画布使用 SVG 渲染器 if (layer === 'main') return new WebGLRenderer(); return new SVGRenderer(); }, }); ``` ## 动态切换渲染器 G6 没有提供单独的 API 来切换渲染器,但你仍可以通过 `setOptions` 方法来更新 `renderer` 参数: ```javascript import { Renderer as SVGRenderer } from '@antv/g-svg'; import { Renderer as WebGLRenderer } from '@antv/g-webgl'; // 初始化时使用 WebGL 渲染器 const graph = new Graph({ // ... other options renderer: () => new WebGLRenderer(), }); await graph.render(); // 切换到 SVG 渲染器 graph.setOptions({ renderer: () => new SVGRenderer(), }); ``` #### 安装 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/installation/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/installation.md - Description: 安装 --- title: "安装" description: "安装" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/installation/" version: "5.1.1" --- ## npm ```bash # npm npm install @antv/g6 --save # pnpm pnpm add @antv/g6 # yarn yarn add @antv/g6 ``` 在代码中引入 G6: ```js import { Graph } from '@antv/g6'; ``` 访问 [G6 npm 示例](https://codesandbox.io/p/sandbox/using-g6-from-npm-d9spnr) 查看完整示例代码。 ## CDN `@antv/g6` 在多个 CDN 上提供: - unpkg: https://unpkg.com/@antv/g6@latest/dist/g6.min.js - jsDelivr: https://cdn.jsdelivr.net/npm/@antv/g6@5/dist/g6.min.js - npmmirror: https://registry.npmmirror.com/@antv/g6/5/files/dist/g6.min.js 使用 `script` 标签引入 G6: ```html ``` 访问 [G6 CDN 示例](https://codesandbox.io/p/sandbox/using-g6-from-cdn-xt9ty6) 查看完整示例代码。 #### 在 Vue 中使用 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/vue/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/vue.md - Description: 在 Vue 中使用 --- title: "在 Vue 中使用" description: "在 Vue 中使用" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/integration/vue/" version: "5.1.1" --- :::warning{title=注意} 请不要将 Vue 响应式数据直接传递给 G6 实例,这可能会导致 G6 无法正确渲染,甚至导致页面崩溃。 ::: 参考下面的示例,你可以在 Vue 中使用 G6,也可以查看 [在线示例](https://stackblitz.com/edit/g6-in-vue?file=src/App.vue)。 ```html ``` #### 布局通用配置项 - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/BaseLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/BaseLayout.md - Description: 布局通用配置项 --- title: "布局通用配置项" description: "布局通用配置项" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/BaseLayout/" version: "5.1.1" --- 本文介绍内置布局通用属性配置。 ## 通用配置 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ---------- | ---- | | type | 布局类型,内置布局或自定义布局的名称 | [Type](#Type) | - | ✓ | | isLayoutInvisibleNodes | 不可见节点是否参与布局(当 preLayout 为 true 时生效) | boolean | false | | | nodeFilter | 参与该布局的节点 | (node: NodeData) => boolean | () => true | | | comboFilter | 参与该布局的combo元素 | (combo: ComboData) => boolean | () => true | | | preLayout | 使用前布局,在初始化元素前计算布局 | boolean | false | | | enableWorker | 是否在 WebWorker 中运行布局 | boolean | - | | | iterations | 迭代布局的迭代次数 | number | - | | | animation | 是否启用布局动画 | boolean | false | | | width | 布局区域宽度,默认使用当前容器宽度 | number | - | | | height | 布局区域高度,默认使用当前容器高度 | number | - | | | center | 布局中心点 | [number, number] \| [number, number, number] | - | | | node | 节点字段映射,用于把业务字段映射为布局字段 | (datum) => ({ id?, x?, y?, z?, parentId?, isCombo? }) | - | | | edge | 边字段映射,用于把业务字段映射为布局字段 | (datum) => ({ id?, source?, target? }) | - | | 补充说明: - `width` / `height` / `center` 是 `@antvis/layout` 统一支持的通用布局字段。 - `node` / `edge` 用于适配非标准 `id/source/target` 业务数据。 - `iterations` 是 G6 运行时用于驱动迭代布局的步数,不等同于某些布局内部自己的算法参数。 ### Type 指定布局类型,内置布局类型名称或自定义布局的名称。 ```js {4} const graph = new Graph({ // 其他配置... layout: { type: 'antv-dagre', }, }); ``` 可选值有: - `antv-dagre`:[基于 dagre 定制的布局](/zh/manual/layout/AntvDagreLayout/) - `circular`:[环形布局](/zh/manual/layout/CircularLayout/) - `combo-combined`:[适用于存在组合的布局](/zh/manual/layout/ComboCombinedLayout/) - `concentric`:[同心圆布局](/zh/manual/layout/ConcentricLayout/) - `d3-force`[基于 D3 的力导向布局](/zh/manual/layout/D3ForceLayout/) - `d3-force-3d`:[3D力导向布局](/zh/manual/layout/D3Force3DLayout/) - `dagre`:[dagre 布局](/zh/manual/layout/DagreLayout/) - `fishbone`:[鱼骨布局](/zh/manual/layout/Fishbone/) - `force`:[力导向布局](/zh/manual/layout/ForceLayout/) - `force-atlas2`:[ForceAtlas2 布局](/zh/manual/layout/ForceAtlas2Layout/) - `fruchterman`:[Fruchterman 布局](/zh/manual/layout/FruchtermanLayout/) - `grid`:[网格布局](/zh/manual/layout/GridLayout/) - `mds`:[高维数据降维算法布局](/zh/manual/layout/MdsLayout/) - `radial`:[径向布局](/zh/manual/layout/RadialLayout/) - `random`:[随机布局](/zh/manual/layout/RandomLayout/) - `snake`:[蛇形布局](/zh/manual/layout/Snake/) - `compact-box`:[紧凑树布局](/zh/manual/layout/CompactBoxLayout/) - `dendrogram`:[树状布局](/zh/manual/layout/DendrogramLayout/) - `mindmap`:[思维导图布局](/zh/manual/layout/MindmapLayout/) - `indented`:[缩进树布局](/zh/manual/layout/IndentedLayout/) #### 背景 Background - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Background/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Background.md - Description: 背景 Background --- title: "背景 Background" description: "背景 Background" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Background/" version: "5.1.1" --- ## 概述 支持为图画布设置一个背景图片,让画布更有层次感、叙事性。 ## 使用场景 这一插件主要用于: - 为图表设置统一的品牌背景色或图片 - 通过背景区分不同的功能区域 - 增强图表的视觉层次感和美观度 ## 基本用法 以下是一个简单的 Background 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'background', key: 'my-background', // 为插件指定标识符,方便动态更新 backgroundColor: '#f0f2f5', // 设置背景色 backgroundImage: 'url(https://example.com/bg.png)', // 设置背景图 }, ], }); ``` ## 配置项 Background 插件的配置项继承了所有 CSS 样式属性([CSSStyleDeclaration](https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration)),因此你可以使用任何合法的 CSS 属性来配置背景。以下是一些常用配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------ | ---------------------------- | ------ | ----------------- | ---- | | type | 插件类型 | string | `background` | ✓ | | key | 插件唯一标识符,用于后续更新 | string | - | | | width | 背景宽度 | string | `100%` | | | height | 背景高度 | string | `100%` | | | backgroundColor | 背景颜色 | string | - | | | backgroundImage | 背景图片 | string | - | | | backgroundSize | 背景尺寸 | string | `cover` | | | backgroundPosition | 背景位置 | string | - | | | backgroundRepeat | 背景重复方式 | string | - | | | opacity | 背景透明度 | string | - | | | transition | 过渡动画 | string | `background 0.5s` | | | zIndex | 层叠顺序 | string | -1 | | > 注意:`zIndex` 默认为 -1,这是为了避免背景覆盖其他插件的 DOM 元素,如网格线。 ## 代码示例 ### 基础背景色 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 200, plugins: [ { type: 'background', width: '300px', height: '200px', backgroundColor: '#f0f2f5', }, ], }); graph.render(); ``` ### 使用背景图片 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 200, plugins: [ { type: 'background', width: '300px', height: '200px', backgroundImage: 'url(https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*0Qq0ToQm1rEAAAAAAAAAAAAADmJ7AQ/original)', backgroundRepeat: 'no-repeat', backgroundSize: 'cover', opacity: 0.2, }, ], }); graph.render(); ``` ### 渐变背景 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 200, plugins: [ { type: 'background', width: '300px', height: '200px', background: 'linear-gradient(45deg, #1890ff, #722ed1)', opacity: '0.8', }, ], }); graph.render(); ``` ### 动态更新背景 ```js // 初始化时配置 const graph = new Graph({ // 其他配置... plugins: [ { type: 'background', key: 'my-background', backgroundColor: '#f0f2f5', }, ], }); // 后续更新 graph.updatePlugin({ key: 'my-background', backgroundColor: '#e6f7ff', transition: 'background 1s ease', }); ``` ## 常见问题 ### 1. 背景与其他插件冲突? 默认情况下,背景插件的 `zIndex` 设为 `-1`,以确保它位于其他元素之下。如果仍有冲突,可以调整 `zIndex` 值: ```js const graph = new Graph({ plugins: [ { type: 'background', zIndex: '-2', // 降低 z-index 避免冲突 }, ], }); ``` #### 主题总览 - Canonical page: https://g6.antv.antgroup.com/zh/manual/theme/overview/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/theme/overview.md - Description: 主题总览 --- title: "主题总览" description: "主题总览" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/theme/overview/" version: "5.1.1" --- ## 概述 G6 中的主题是 Graph Options 的子集,它包含了关于画布和元素样式的配置。多主题可以帮助你快速地切换不同的图样式。 ## 主题结构 一个主题由以下四个部分组成: 1. **画布背景色 (background)** - 控制整个画布的背景颜色 2. **节点配置 (node)** - 基础样式:填充色、描边、标签等静态视觉属性 - [调色板](/zh/manual/theme/palette/):用于节点分组的颜色配置 - 状态样式:不同状态下的样式配置(选中、激活、禁用等) - 动画配置:节点的动画效果配置 3. **边配置 (edge)** - 基础样式:线条样式、箭头、标签等静态视觉属性 - [调色板](/zh/manual/theme/palette/):用于边分组的颜色配置 - 状态样式:不同状态下的样式配置 - 动画配置:边的动画效果配置 4. **Combo 配置 (combo)** - 基础样式:填充、描边、折叠按钮等静态视觉属性 - 状态样式:不同状态下的样式配置 - 动画配置:Combo 的动画效果配置 > 注意:主题中的样式配置仅支持静态值,不支持回调函数形式的动态配置。如需动态样式,请使用图的配置项。 ## 内置主题 G6 默认提供两种内置主题: ### 亮色主题(默认) 亮色主题
查看亮色主题完整配置项 ```js const lightTheme = { background: '#ffffff', node: { palette: { type: 'group', color: [ '#1783FF', '#00C9C9', '#F08F56', '#D580FF', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }, style: { donutOpacity: 1, badgeBackgroundOpacity: 1, badgeFill: '#fff', badgeFontSize: 8, badgePadding: [0, 4], badgePalette: ['#7E92B5', '#F4664A', '#FFBE3A'], fill: '#1783ff', fillOpacity: 1, halo: false, iconFill: '#fff', iconOpacity: 1, labelBackground: false, labelBackgroundFill: '#ffffff', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelFill: '#000000', labelFillOpacity: 0.85, labelLineHeight: 16, labelPadding: [0, 2], labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, labelOffsetY: 2, lineWidth: 0, portFill: '#1783ff', portLineWidth: 1, portStroke: '#000000', portStrokeOpacity: 0.65, size: 32, stroke: '#000000', strokeOpacity: 1, zIndex: 2, }, state: { selected: { halo: true, haloLineWidth: 24, haloStrokeOpacity: 0.25, labelFontSize: 12, labelFontWeight: 'bold', lineWidth: 4, stroke: '#000000', }, active: { halo: true, haloLineWidth: 12, haloStrokeOpacity: 0.15, }, highlight: { labelFontWeight: 'bold', lineWidth: 4, stroke: '#000000', strokeOpacity: 0.85, }, inactive: { badgeBackgroundOpacity: 0.25, donutOpacity: 0.25, fillOpacity: 0.25, iconOpacity: 0.85, labelFill: '#000000', labelFillOpacity: 0.25, strokeOpacity: 0.25, }, disabled: { badgeBackgroundOpacity: 0.25, donutOpacity: 0.06, fill: '#1B324F', fillOpacity: 0.06, iconFill: '#1B324F', iconOpacity: 0.25, labelFill: '#000000', labelFillOpacity: 0.25, strokeOpacity: 0.06, }, }, animation: { enter: 'fade', exit: 'fade', show: 'fade', hide: 'fade', expand: 'node-expand', collapse: 'node-collapse', update: [{ fields: ['x', 'y', 'fill', 'stroke'] }], translate: [{ fields: ['x', 'y'] }], }, }, edge: { palette: { type: 'group', color: [ '#99ADD1', '#1783FF', '#00C9C9', '#F08F56', '#D580FF', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }, style: { badgeBackgroundFill: '#99ADD1', badgeFill: '#fff', badgeFontSize: 8, badgeOffsetX: 10, fillOpacity: 1, halo: false, haloLineWidth: 12, haloStrokeOpacity: 1, increasedLineWidthForHitTesting: 2, labelBackground: false, labelBackgroundFill: '#ffffff', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelBackgroundPadding: [4, 4, 4, 4], labelFill: '#000000', labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, labelPlacement: 'center', labelTextBaseline: 'middle', lineWidth: 1, stroke: '#99ADD1', strokeOpacity: 1, zIndex: 1, }, state: { selected: { halo: true, haloStrokeOpacity: 0.25, labelFontSize: 14, labelFontWeight: 'bold', lineWidth: 3, }, active: { halo: true, haloStrokeOpacity: 0.15, }, highlight: { labelFontWeight: 'bold', lineWidth: 3, }, inactive: { stroke: '#1B324F', fillOpacity: 0.08, labelOpacity: 0.25, strokeOpacity: 0.08, badgeBackgroundOpacity: 0.25, }, disabled: { stroke: '#d9d9d9', fillOpacity: 0.45, strokeOpacity: 0.45, labelOpacity: 0.25, badgeBackgroundOpacity: 0.45, }, }, animation: { enter: 'fade', exit: 'fade', expand: 'path-in', collapse: 'path-out', show: 'fade', hide: 'fade', update: [{ fields: ['sourceNode', 'targetNode'] }, { fields: ['stroke'], shape: 'key' }], translate: [{ fields: ['sourceNode', 'targetNode'] }], }, }, combo: { style: { collapsedMarkerFill: '#ffffff', collapsedMarkerFontSize: 12, collapsedMarkerFillOpacity: 1, collapsedSize: 32, collapsedFillOpacity: 1, fill: '#99ADD1', halo: false, haloLineWidth: 12, haloStroke: '#99ADD1', haloStrokeOpacity: 0.25, labelBackground: false, labelBackgroundFill: '#ffffff', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelBackgroundPadding: [2, 4, 2, 4], labelFill: '#000000', labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, lineDash: 0, lineWidth: 1, fillOpacity: 0.04, strokeOpacity: 1, padding: 10, stroke: '#99ADD1', }, state: { selected: { halo: true, labelFontSize: 14, labelFontWeight: 700, lineWidth: 4, }, active: { halo: true, }, highlight: { labelFontWeight: 700, lineWidth: 4, }, inactive: { fillOpacity: 0.65, labelOpacity: 0.25, strokeOpacity: 0.65, }, disabled: { fill: '#d9d9d9', fillOpacity: 0.25, labelOpacity: 0.25, stroke: '#d9d9d9', strokeOpacity: 0.25, }, }, animation: { enter: 'fade', exit: 'fade', show: 'fade', hide: 'fade', expand: 'combo-expand', collapse: 'combo-collapse', update: [{ fields: ['x', 'y'] }, { fields: ['fill', 'stroke', 'lineWidth'], shape: 'key' }], translate: [{ fields: ['x', 'y'] }], }, }, }; ```
### 暗色主题 暗色主题
查看暗色主题完整配置项 ```js const darkTheme = { background: '#000000', node: { palette: { type: 'group', color: [ '#1783FF', '#00C9C9', '#F08F56', '#D580FF', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }, style: { donutOpacity: 1, badgeBackgroundOpacity: 1, badgeFill: '#fff', badgeFontSize: 8, badgePadding: [0, 4], badgePalette: ['#7E92B5', '#F4664A', '#FFBE3A'], fill: '#1783ff', fillOpacity: 1, halo: false, iconFill: '#fff', iconOpacity: 1, labelBackground: false, labelBackgroundFill: '#000000', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelFill: '#ffffff', labelFillOpacity: 0.85, labelLineHeight: 16, labelPadding: [0, 2], labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, labelOffsetY: 2, lineWidth: 0, portFill: '#1783ff', portLineWidth: 1, portStroke: '#d0e4ff', portStrokeOpacity: 0.65, size: 32, stroke: '#d0e4ff', strokeOpacity: 1, zIndex: 2, }, state: { selected: { halo: true, haloLineWidth: 24, haloStrokeOpacity: 0.45, labelFontSize: 12, labelFontWeight: 'bold', lineWidth: 4, stroke: '#d0e4ff', }, active: { halo: true, haloLineWidth: 12, haloStrokeOpacity: 0.25, }, highlight: { labelFontWeight: 'bold', lineWidth: 4, stroke: '#d0e4ff', strokeOpacity: 0.85, }, inactive: { badgeBackgroundOpacity: 0.45, donutOpacity: 0.45, fillOpacity: 0.45, iconOpacity: 0.45, labelFill: '#ffffff', labelFillOpacity: 0.45, strokeOpacity: 0.45, }, disabled: { badgeBackgroundOpacity: 0.25, donutOpacity: 0.25, fill: '#D0E4FF', fillOpacity: 0.25, iconFill: '#D0E4FF', iconOpacity: 0.25, labelFill: '#ffffff', labelFillOpacity: 0.25, strokeOpacity: 0.25, }, }, animation: { enter: 'fade', exit: 'fade', show: 'fade', hide: 'fade', expand: 'node-expand', collapse: 'node-collapse', update: [{ fields: ['x', 'y', 'fill', 'stroke'] }], translate: [{ fields: ['x', 'y'] }], }, }, edge: { palette: { type: 'group', color: [ '#637088', '#0F55A6', '#008383', '#9C5D38', '#8B53A6', '#4E40A6', '#8F6608', '#3E801D', '#A65383', '#175E75', '#0F8248', ], }, style: { badgeBackgroundFill: '#637088', badgeFill: '#fff', badgeFontSize: 8, badgeOffsetX: 10, fillOpacity: 1, halo: false, haloLineWidth: 12, haloStrokeOpacity: 1, increasedLineWidthForHitTesting: 2, labelBackground: false, labelBackgroundFill: '#000000', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelBackgroundPadding: [4, 4, 4, 4], labelFill: '#ffffff', labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, labelPlacement: 'center', labelTextBaseline: 'middle', lineWidth: 1, stroke: '#637088', strokeOpacity: 1, zIndex: 1, }, state: { selected: { halo: true, haloStrokeOpacity: 0.25, labelFontSize: 14, labelFontWeight: 'bold', lineWidth: 3, }, active: { halo: true, haloStrokeOpacity: 0.15, }, highlight: { labelFontWeight: 'bold', lineWidth: 3, }, inactive: { stroke: '#D0E4FF', fillOpacity: 0.08, labelOpacity: 0.25, strokeOpacity: 0.08, badgeBackgroundOpacity: 0.25, }, disabled: { stroke: '#637088', fillOpacity: 0.45, strokeOpacity: 0.45, labelOpacity: 0.25, badgeBackgroundOpacity: 0.45, }, }, animation: { enter: 'fade', exit: 'fade', expand: 'path-in', collapse: 'path-out', show: 'fade', hide: 'fade', update: [{ fields: ['sourceNode', 'targetNode'] }, { fields: ['stroke'], shape: 'key' }], translate: [{ fields: ['sourceNode', 'targetNode'] }], }, }, combo: { style: { collapsedMarkerFill: '#000000', collapsedMarkerFontSize: 12, collapsedMarkerFillOpacity: 1, collapsedSize: 32, collapsedFillOpacity: 1, fill: '#fdfdfd', halo: false, haloLineWidth: 12, haloStroke: '#99add1', haloStrokeOpacity: 0.25, labelBackground: false, labelBackgroundFill: '#000000', labelBackgroundLineWidth: 0, labelBackgroundOpacity: 0.75, labelBackgroundPadding: [2, 4, 2, 4], labelFill: '#ffffff', labelFontSize: 12, labelFontWeight: 400, labelOpacity: 1, lineDash: 0, lineWidth: 1, fillOpacity: 0.04, strokeOpacity: 1, padding: 10, stroke: '#99add1', }, state: { selected: { halo: true, labelFontSize: 14, labelFontWeight: 700, lineWidth: 4, }, active: { halo: true, }, highlight: { labelFontWeight: 700, lineWidth: 4, }, inactive: { fillOpacity: 0.65, labelOpacity: 0.25, strokeOpacity: 0.65, }, disabled: { fill: '#d0e4ff', fillOpacity: 0.25, labelOpacity: 0.25, stroke: '#969696', strokeOpacity: 0.25, }, }, animation: { enter: 'fade', exit: 'fade', show: 'fade', hide: 'fade', expand: 'combo-expand', collapse: 'combo-collapse', update: [{ fields: ['x', 'y'] }, { fields: ['fill', 'stroke', 'lineWidth'], shape: 'key' }], translate: [{ fields: ['x', 'y'] }], }, }, }; ```
## 使用主题 ### 配置主题 在创建图时通过 `theme` 选项指定要使用的主题: ```javascript const graph = new Graph({ theme: 'light', // 或 'dark' // ... 其他配置 }); ``` ### 切换主题 创建图后,可以通过 `setTheme` 方法动态切换主题: ```javascript // 切换到暗色主题 graph.setTheme('dark'); // 获取当前主题 const currentTheme = graph.getTheme(); // 'dark' ``` ## 样式优先级 在 G6 中,元素的最终样式由多个层级的样式合并而成,按优先级从低到高排序: **⭐️ 主题默认样式** < 调色板样式 < 数据样式 < 图的默认样式 < **⭐️ 主题状态样式** < 图的状态样式 详细说明: 1. **主题默认样式**:主题系统提供的基础样式 2. **调色板样式**:基于主题调色板配置的自动着色样式 3. **数据样式**:在数据中定义的样式 4. **图的默认样式**:通过图的配置项设置的样式 5. **主题状态样式**:主题中定义的状态样式 6. **图的状态样式**:通过图的配置项设置的状态样式 更多关于自定义主题的内容,请参考[自定义主题](/zh/manual/theme/custom-theme/)。 #### 动态调整节点大小 MapNodeSize - Canonical page: https://g6.antv.antgroup.com/zh/manual/transform/MapNodeSize/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/transform/MapNodeSize.md - Description: 动态调整节点大小 MapNodeSize --- title: "动态调整节点大小 MapNodeSize" description: "动态调整节点大小 MapNodeSize" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/transform/MapNodeSize/" version: "5.1.1" --- ## 概述 在图可视化中,节点的大小通常用于传达节点的重要性或影响力。通过根据节点中心性调整节点的大小,我们可以更直观地展示网络中各个节点的重要性,从而帮助用户更好地理解和分析复杂的网络结构。 ## 使用场景 需要通过节点大小来突出节点的重要性和影响力时,可使用此数据处理。 以下为常见的场景: - **社交网络分析**:比如分析社交媒体平台中用户的活跃度与影响力,通过节点大小突出高互动用户。 - **金融风险传导网络**:比如识别金融系统中承担关键资金流转职能的机构,预防系统性风险。 - **交通枢纽规划**:比如优化城市地铁网络设计,识别换乘压力点。 ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------ | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------------- | ---- | | type | 数据处理类型 | map-node-size | - | ✓ | | centrality | 节点中心性的度量方法,[配置项](#centrality) | [NodeCentralityOptions](#nodecentralityoptions) \| ((graphData: [GraphData](/zh/manual/data/#图数据graphdata)) => Map<string, number>) | `{ type: 'degree' }` | | | mapLabelSize | 是否同步调整标签大小 | boolean \| [number, number] | false | | | maxSize | 节点最大尺寸 | number \| [number, number] \| [number, number, number] | 80 | | | minSize | 节点最小尺寸 | number \| [number, number] \| [number, number, number] | 20 | | | scale | 插值函数,用于将节点中心性映射到节点大小,[配置项](#scale) | `linear` \| `log` \| `pow` \| `sqrt` \| ((value: number, domain: [number, number], range: [number, number]) => number) | `log` | | ### centrality 节点中心性的度量方法 - `'degree'`:度中心性,通过节点的度数(连接的边的数量)来衡量其重要性。度中心性高的节点通常具有较多的直接连接,在网络中可能扮演着重要的角色 - `'betweenness'`:介数中心性,通过节点在所有最短路径中出现的次数来衡量其重要性。介数中心性高的节点通常在网络中起到桥梁作用,控制着信息的流动 - `'closeness'`:接近中心性,通过节点到其他所有节点的最短路径长度总和的倒数来衡量其重要性。接近中心性高的节点通常能够更快地到达网络中的其他节点 - `'eigenvector'`:特征向量中心性,通过节点与其他中心节点的连接程度来衡量其重要性。特征向量中心性高的节点通常连接着其他重要节点 - `'pagerank'`:PageRank 中心性,通过节点被其他节点引用的次数来衡量其重要性,常用于有向图。PageRank 中心性高的节点通常在网络中具有较高的影响力,类似于网页排名算法 - 自定义中心性计算方法:`(graphData: GraphData) => Map`,其中 `graphData` 为图数据,`Map` 为节点 ID 到中心性值的映射 **示例:** ```typescript {6-9} const graph = new Graph({ // 其他配置... transforms: [ { type: 'map-node-size', centrality: { type: 'degree', direction: 'both', }, }, ], }); ``` 效果如下(可切换度量方法查看不同效果,示例中节点 label 为`${节点 id } - ${节点大小}`): ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, { source: 'node1', target: 'node4' }, { source: 'node1', target: 'node3' }, ], }, node: { type: 'circle', style: { labelText: (d) => d.id + ' - ' + d.style.size[0].toFixed(0), }, }, layout: { type: 'circular', radius: 180, }, behaviors: ['drag-canvas'], transforms: [ { key: 'map-node-size', type: 'map-node-size', centrality: { type: 'pagerank', }, }, ], }, { width: 600, height: 460 }, (gui, graph) => { const options = { type: 'degree', }; const optionFolder = gui.addFolder('Centrality Options'); optionFolder.add(options, 'type', ['degree', 'betweenness', 'closeness', 'eigenvector', 'pagerank']); optionFolder.onChange(async ({ property, value }) => { graph.updateTransform({ key: 'map-node-size', centrality: { [property]: value, }, }); graph.render(); }); }, ); ``` #### NodeCentralityOptions ```typescript type NodeCentralityOptions = | { type: 'degree'; direction?: 'in' | 'out' | 'both' } | { type: 'betweenness'; directed?: boolean; weightPropertyName?: string } | { type: 'closeness'; directed?: boolean; weightPropertyName?: string } | { type: 'eigenvector'; directed?: boolean } | { type: 'pagerank'; epsilon?: number; linkProb?: number }; ``` `direction`:表示统计哪些方向的边,`in` -入边、 `out` -出边、 `both` -入边和出边都考虑进去 `directed`:是否为有向图 `weightPropertyName`:边的权重属性名 `epsilon`:PageRank 算法的收敛容差 `linkProb`:PageRank 算法的阻尼系数,指任意时刻,用户访问到某节点后继续访问该节点链接的下一个节点的概率,经验值 0.85 ### scale - `'linear'`:线性插值函数,将一个值从一个范围线性映射到另一个范围,常用于处理中心性值的差异较小的情况 - `'log'`:对数插值函数,将一个值从一个范围对数映射到另一个范围,常用于处理中心性值的差异较大的情况 - `'pow'`:幂律插值函数,将一个值从一个范围幂律映射到另一个范围,常用于处理中心性值的差异较大的情况 - `'sqrt'`:平方根插值函数,将一个值从一个范围平方根映射到另一个范围,常用于处理中心性值的差异较大的情况 - 自定义插值函数:`(value: number, domain: [number, number], range: [number, number]) => number`,其中 `value` 为需要映射的值,`domain` 为输入值的范围,`range` 为输出值的范围 **示例:** ```typescript {9} const graph = new Graph({ // 其他配置... transforms: [ { type: 'map-node-size', centrality: { type: 'degree', }, scale: 'linear', }, ], }); ``` 效果如下(该示例为基于度中心性 `degree` ,可切换插值函数查看不同效果,示例中节点 label 为`${节点 id } - ${节点大小}`): ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [ { id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }, { id: 'node6' }, { id: 'node7' }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node5' }, { source: 'node3', target: 'node6' }, { source: 'node4', target: 'node7' }, ], }, node: { type: 'circle', style: { labelText: (d) => d.id + ' - ' + d.style.size[0].toFixed(0), }, }, layout: { type: 'antv-dagre', }, behaviors: ['drag-canvas'], transforms: [ { key: 'map-node-size', type: 'map-node-size', centrality: { type: 'degree', }, scale: 'log', }, ], }, { width: 600, height: 400 }, (gui, graph) => { const options = { scale: 'log', }; const optionFolder = gui.addFolder('MapNodeSize Options'); optionFolder.add(options, 'scale', ['log', 'linear', 'pow', 'sqrt']); optionFolder.onChange(async ({ property, value }) => { graph.updateTransform({ key: 'map-node-size', [property]: value, }); graph.render(); }); }, ); ``` ## 实际案例 - [场景案例:独角兽和他们的投资者](/zh/examples/feature/default/unicorns-investors/) ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 新版本特性 - Canonical page: https://g6.antv.antgroup.com/zh/manual/whats-new/feature/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/whats-new/feature.md - Description: 新版本特性 --- title: "新版本特性" description: "新版本特性" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/whats-new/feature/" version: "5.1.1" --- ## 🏖️ 全新设计图配置范式 G6 5.0 重新设计了图配置范式,在保证能力完善的基础上,优化配置项结构,更加直观、易于理解。 仅需快速了解基本[核心概念](/zh/manual/graph/graph/),即可快速上手 G6,快速实现图可视化。 **😰 4.0 配置项** 嵌套结构复杂,语义化能力较弱 ```typescript { defaultNode: { size: 30, style: { fill: 'steelblue', stroke: '#666', lineWidth: 1 }, labelCfg: { style: { fill: '#fff', } } }, nodeStateStyles: { hover: { fill: 'lightsteelblue' } }, modes: { default: ['zoom-canvas', 'drag-canvas', 'drag-node'], }, } ``` **😄 5.0 配置项** 结构清晰,易于理解 ```typescript { node: { style: { size: 30, fill: 'steelblue', stroke: '#666', lineWidth: 1 labelFill: '#fff', }, state: { hover: { fill: 'lightsteelblue' } } }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], } ``` ## 🔨 全新 API 设计 G6 5.0 采用了更加简洁、易用的 API 设计,更加符合现代前端框架的设计风格。 ## 🌲 合并图与树图 树图本质上是一种单向无环图,G6 5.0 融合了图与树图的设计,降低了理解和使用成本。 现在,你可以在 G6 中直接使用 `Graph` 来实例化绘制树图,而不需要再使用 `TreeGraph`,仅需指定布局为树图布局即可。 此外,G6 提供了 `treeToGraphData` 工具方法,帮助你快速将树图数据转换为图数据。 ```ts import { Graph, treeToGraphData } from '@antv/g6'; const data = { id: 'root', children: [ { id: 'node1', children: [{ id: 'node1-1' }, { id: 'node1-2' }] }, { id: 'node2', children: [{ id: 'node2-1' }, { id: 'node2-2' }] }, ], }; const graph = new Graph({ container: 'container', layout: { type: 'compact-box', direction: 'TB', }, data: treeToGraphData(data), edge: { type: 'cubic-vertical', }, }); graph.render(); ``` ```ts import * as g6 from '@antv/g6'; import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, autoFit: 'view', data: g6.treeToGraphData({ id: 'root', children: [ { id: 'node1', children: [{ id: 'node1-1' }, { id: 'node1-2' }] }, { id: 'node2', children: [{ id: 'node2-1' }, { id: 'node2-2' }] }, ], }), layout: { type: 'compact-box', direction: 'TB', }, node: { style: { ports: [{ placement: 'center' }], }, }, edge: { type: 'cubic-vertical', }, }); graph.render(); ``` ## 🌆 多渲染器支持 G6 5.0 采用了新一代设计的 @antv/g 渲染引擎,提供了 `Canvas` `SVG` `WebGL` 多种渲染器支持,并且分层画布支持不同渲染器的混合使用。 ```typescript import { Renderer } from '@antv/g-webgl'; import { Graph } from '@antv/g6'; const graph = new Graph({ // ... 其他配置 // 使用 WebGL 渲染器 renderer: () => new Renderer(), }); ``` ## 🚀 高性能布局 G6 5.0 采用了全新布局引擎,部分布局提供 Rust 实现,提供了更高性能的布局计算。另有布局支持 WebGPU 加速。 > 🚀 高性能布局需要安装 `@antv/layout-wasm` 包 ```typescript import { ForceAtlas2Layout, initThreads, supportsThreads } from '@antv/layout-wasm'; import { Graph, register, ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.LAYOUT, 'forceatlas2-wasm', ForceAtlas2Layout); const supported = await supportsThreads(); const threads = await initThreads(supported); const graph = new Graph({ // ... 其他配置 layout: { type: 'forceatlas2-wasm', threads, // ... 其他布局配置 }, }); ``` > GPU 加速布局需要安装 `@antv/layout-gpu` 包 ```typescript import { FruchtermanLayout } from '@antv/layout-gpu'; import { Graph, register, ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.LAYOUT, 'fruchterman-gpu', FruchtermanLayout); const graph = new Graph({ // ... 其他配置 layout: { type: 'fruchterman-gpu', // ... 其他布局配置 }, }); ``` ## 🎨 多主题机制 G6 5.0 内置了亮色、暗色两套主题,并可基于使用场景进行灵活定制,具体可参考[自定义主题](/zh/manual/theme/custom-theme/)。 ## 🌍 3D 大图 G6 5.0 提供了 3D 大图渲染、布局、交互能力,从 `@antv/g6-extension-3d` 中引入 3D 元素、渲染器、交互等注册即可使用,详见:[使用 3D](/zh/manual/further-reading/3d/)。 ## 💪 插件优化增强 G6 5.0 对现有插件进行了优化增强,解除了 Graph 与插件之间的耦合,并优化配置的同时提供了更加丰富了能力。 敬请前往[插件](/zh/manual/plugin/overview/)体验更多插件的能力。 ## 💼 优化包体积 得益于 G6 5.0 良好的模块化的设计以及扩展注册机制,对于未使用的模块,不会被打包到最终的构建文件中,减小了包体积。 与 4.0 相比,UMD 包体积从 1.8 MB 减小到 0.96 MB,减小了近 50%。 #### 自定义动画 - Canonical page: https://g6.antv.antgroup.com/zh/manual/animation/custom-animation/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/animation/custom-animation.md - Description: 自定义动画 --- title: "自定义动画" description: "自定义动画" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/animation/custom-animation/" version: "5.1.1" --- ## 概述 ## 实现动画 对于圆形节点(Circle)元素,其主图形是一个圆形,现在为其编写一个动画,当节点的尺寸发生变化时,能够以缩放的方式进行过渡动画: ```typescript [ { fields: ['r'], shape: 'key', }, ]; ``` 下面我们创建一个图实例并更新元素尺寸来触发更新动画: ```typescript const graph = new Graph({ container: 'container', width: 50, height: 50, data: { nodes: [{ id: 'node-1', style: { x: 25, y: 25, size: 20 } }], }, node: { animation: { update: [{ fields: ['r'], shape: 'key' }], }, }, }); graph.draw().then(() => { graph.updateNodeData([{ id: 'node-1', style: { size: 40 } }]); graph.draw(); }); ``` > ⬇️ 指针移动至下方图中,并点击左侧播放按钮进行重新播放 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ width: 50, height: 50, container, data: { nodes: [{ id: 'node-1', style: { x: 25, y: 25, size: 20 } }], }, node: { animation: { update: [ { fields: ['r'], shape: 'key', }, ], }, }, }); graph.draw().then(() => { graph.updateNodeData([{ id: 'node-1', style: { size: 40 } }]); graph.draw(); }); ``` #### 原理分析 当对一个元素执行动画时,该元素会将其动画帧参数转化为其各个子图形上的动画帧参数,并执行对应的动画。 在上面的例子中,通过更新节点尺寸(size),对该节点执行了动画,其动画帧参数为: ```json [{ "size": 20 }, { "size": 40 }] ``` 节点元素拿到该属性后,将其转化为主图形(圆形)的动画帧参数: ```json [{ "r": 10 }, { "r": 20 }] ``` 因此这里最终是对圆形执行了半径从 10 到 20 的过渡动画。 #### 复合动画 直接将位置变化动画和尺寸变化动画合并到一个动画范式即可得到复合动画范式: ```typescript [ { fields: ['x', 'y'], }, { fields: ['r'], shape: 'key', }, ]; ``` 并同时更新该节点的位置和尺寸: ```typescript graph.updateNodeData([{ id: 'node-1', style: { x: 175, size: 40 } }]); graph.draw(); ``` > ⬇️ 指针移动至下方图中,并点击左侧播放按钮进行重新播放 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 50, data: { nodes: [{ id: 'node-1', style: { x: 25, y: 25, size: 20 } }], }, node: { animation: { update: [ { fields: ['x', 'y'], }, { fields: ['r'], shape: 'key' }, ], }, }, }); graph.draw().then(() => { graph.updateNodeData([{ id: 'node-1', style: { x: 175, size: 40 } }]); graph.draw(); }); ``` 加入颜色过渡: ```typescript [ { fields: ['x', 'y'], }, { fields: ['r', 'fill'], shape: 'key', }, ]; ``` 执行节点更新: ```typescript graph.updateNodeData([{ id: 'node-1', style: { x: 175, size: 40, fill: 'pink' } }]); graph.draw(); ``` > ⬇️ 指针移动至下方图中,并点击左侧播放按钮进行重新播放 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 50, data: { nodes: [{ id: 'node-1', style: { x: 25, y: 25, size: 20 } }], }, node: { animation: { update: [ { fields: ['x', 'y'], }, { fields: ['r', 'fill'], shape: 'key' }, ], }, }, }); graph.draw().then(() => { graph.updateNodeData([{ id: 'node-1', style: { x: 175, size: 40, fill: 'pink' } }]); graph.draw(); }); ``` #### 框选 BrushSelect - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/BrushSelect/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/BrushSelect.md - Description: 框选 BrushSelect --- title: "框选 BrushSelect" description: "框选 BrushSelect" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/BrushSelect/" version: "5.1.1" --- ## 概述 鼠标点击拖一个框笼罩元素,框选范围内的元素会被选中。 ## 使用场景 这一交互主要用于: - 快速选中一批元素 - 快速取消选中一批元素 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'brush-select', key: 'brush-select', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'brush-select', type: 'brush-select', animation: false, enable: true, enableElements: ['node', 'edge', 'combo'], immediately: false, mode: 'default', state: 'selected', trigger: 'shift+drag', }; const optionFolder = gui.addFolder('BrushSelect Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'enableElements', [ ['node', 'edge', 'combo'], ['node', 'edge'], ['node', 'combo'], ['combo', 'edge'], ['node'], ['edge'], ['combo'], ]); optionFolder.add(options, 'trigger', { 'shift+drag': ['shift'], drag: [], }); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'mode', ['union', 'intersect', 'diff', 'default']).onChange((e) => { immediately.show(e === 'default'); }); const immediately = optionFolder.add(options, 'immediately'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'brush-select', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['brush-select'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'brush-select', key: 'brush-select-1', immediately: true, // 可以看到框框笼罩过去时,元素立即被框选了 trigger: ['shift', 'alt', 'control'], // 配合多种按键进行框选 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------- | ---- | | type | 交互类型名称。此插件已内置,你可以通过 `type: 'brush-select'` 来使用它。 | `brush-select` \| string | `brush-select` | ✓ | | animation | 是否启用动画 | boolean | false | | | enable | 是否启用框选功能 | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | enableElements | 可框选的元素类型 | ( `node` \| `edge` \| `combo` )[] | [`node`, `combo`, `edge`] | | | immediately | 是否及时框选, 仅在 [框选模式 mode](#mode) 为 `default` 时生效,[示例](#immediately) | boolean | false | | | mode | 框选的选择模式,[示例](#mode) | `union` \| `intersect` \| `diff` \| `default` | `default` | | | onSelect | 框选元素状态回调 | (states:Record<string,string\|string[]>) =>Record<string,string\|string[]> | | | | state | 被选中时切换到该状态 | string \| `selected` \| `active` \| `inactive` \| `disabled` \| `highlight` | `selected` | | | style | 指定框选时的框样式,[配置项](#style) | | 见下文 | | | trigger | 按下该快捷键配合鼠标点击进行框选 **按键参考:** _MDN Key Values_ 。若设为**空数组**时则表示鼠标点击进行框选,不需要按下其他按键配合
⚠️ 注意,`trigger` 设置为 `['drag']` 时会导致 `drag-canvas` 行为失效。两者不可同时配置。 | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | [`shift`] | | ### immediately 是否及时框选, 仅在框选模式为 `default` 时生效 ```js const graph = new Graph({ behaviors: [ { type: 'brush-select', key: 'brush-select', immediately: true, // 可以看到框框笼罩过去时,元素立即被框选了 trigger: [], // 不需要配合其他按键,点击鼠标拖动即可框选 }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, data: { nodes: [ { id: 'node-1', style: { x: 100, y: 50 } }, { id: 'node-2', style: { x: 260, y: 50 } }, { id: 'node-3', style: { x: 280, y: 100 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, }, edge: { stroke: '#8b9baf', }, behaviors: [ { type: 'brush-select', key: 'brush-select', immediately: true, // 立即框选 trigger: [], }, ], plugins: [{ type: 'grid-line', size: 30 }], }); graph.render(); ``` ### mode 内置支持四种框选的选择模式: - `union`:保持已选元素的当前状态,并添加指定的 state 状态。 - `intersect`:如果已选元素已有指定的 state 状态,则保留;否则清除该状态。 - `diff`:对已选元素的指定 state 状态进行取反操作。 - `default`:清除已选元素的当前状态,并添加指定的 state 状态。 ```js const graph = new Graph({ behaviors: [ { type: 'brush-select', key: 'brush-select', mode: 'default', // 框选模式, 默认框选模式 }, ], }); ``` ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'brush-select', key: 'brush-select', trigger: [], immediately: true, }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'brush-select', type: 'brush-select', animation: false, enable: true, enableElements: ['node', 'edge', 'combo'], mode: 'default', state: 'selected', }; const optionFolder = gui.addFolder('BrushSelect Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'mode', ['union', 'intersect', 'diff', 'default']); // .onChange((e) => { // immediately.show(e === 'default'); // }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'brush-select', [property]: value, }); graph.render(); }); }, ); ``` ### style | 属性 | 描述 | 类型 | 默认值 | | ----------------- | ------------------ | ---------------------------------------- | --------- | | cursor | 鼠标样式 | string | | | fill | 填充颜色 | string \| Pattern \| null | `#1677FF` | | fillOpacity | 填充透明度 | number \| string | 0.1 | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | lineCap | 线段端点样式 | `butt` \| `round` \| `square` | | | lineDash | 虚线配置 | number \| string \| (string \| number)[] | | | lineDashOffset | 虚线偏移量 | number | | | lineJoin | 线段连接处样式 | `miter` \| `round` \| `bevel` | | | lineWidth | 线宽度 | number \| string | 1 | | opacity | 整体透明度 | number \| string | | | radius | 矩形圆角半径 | number \| string \| number[] | | | shadowBlur | 阴影模糊程度 | number | | | shadowColor | 阴影颜色 | string | | | shadowOffsetX | 阴影 X 方向偏移 | number | | | shadowOffsetY | 阴影 Y 方向偏移 | number | | | stroke | 描边颜色 | string \| Pattern \| null | `#1677FF` | | strokeOpacity | 描边透明度 | number \| string | | | visibility | 可见性 | `visible` \| `hidden` | | | zIndex | 渲染层级 | number | 2 | **示例**: ```js const graph = new Graph({ behaviors: [ { type: 'brush-select', key: 'brush-select', style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], // 虚线外框 // rgb超级炫彩框框 fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, }, edge: { stroke: '#8b9baf', }, behaviors: [ { type: 'brush-select', key: 'brush-select', trigger: [], immediately: true, style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], // 虚线外框 // rgb超级炫彩框框 fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }); graph.render(); ``` ### 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', style: { x: 200, y: 250 } }, { id: 'node-2', style: { x: 250, y: 200 } }, { id: 'node-3', style: { x: 300, y: 250 } }, { id: 'node-4', style: { x: 250, y: 300 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-2', target: 'node-3' }, { source: 'node-3', target: 'node-4' }, { source: 'node-4', target: 'node-1' }, ], }, behaviors: [ { key: 'brush-select', type: 'brush-select', enable: true, animation: false, mode: 'default', // union intersect diff default state: 'selected', // 'active', 'selected', 'inactive', ... trigger: [], // ['Shift', 'Alt', 'Control', 'Drag', 'Meta', ...] style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 圆形组合 Circle - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/combo/CircleCombo/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/combo/CircleCombo.md - Description: 圆形组合 Circle --- title: "圆形组合 Circle" description: "圆形组合 Circle" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/combo/CircleCombo/" version: "5.1.1" --- ## 概述 圆形组合以圆形边界包裹子节点或子组合,适合表示平等或非层级化的群组关系。 适用场景: - 适合表示无明确层级关系的节点群组,圆形组合能体现成员的平等性,如社交网络中的用户群体、分散式团队结构(突出协作性)。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } }, ], combos: [ { id: 'combo1', combo: 'combo2' }, { id: 'combo2', style: {} }, ], }, node: { style: { fill: '#7e3feb' } }, behaviors: ['drag-element', 'collapse-expand'], plugins: ['grid-line'], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { gui.add({ type: 'circle' }, 'type').disable(); }, ); ``` 设置 `combo.type` 为 `circle` 以使用圆形组合。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseCombo](/zh/manual/element/combo/BaseCombo/) ## 示例 以下示例为兴趣小组人员分布: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 600, autoFit: 'center', data: { nodes: [ { id: 'node1', combo: 'combo2', style: { x: 150, y: 150 } }, { id: 'node2', combo: 'combo2', style: { x: 200, y: 150 } }, { id: 'node3', combo: 'combo3', style: { x: 300, y: 150 } }, { id: 'node4', combo: 'combo3', style: { x: 350, y: 150 } }, { id: 'node5', combo: 'combo4', style: { x: 230, y: 300 } }, { id: 'node6', combo: 'combo4', style: { x: 280, y: 300 } }, ], combos: [ { id: 'combo1', style: { labelText: '兴趣小组' } }, { id: 'combo2', combo: 'combo1', style: { labelText: '书法' } }, { id: 'combo3', combo: 'combo1', style: { labelText: '影视' } }, { id: 'combo4', combo: 'combo1', style: { labelText: '游戏' } }, ], }, node: { style: { labelText: (d) => d.id, }, }, behaviors: ['drag-element', 'collapse-expand'], animation: true, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 三次贝塞尔曲线边 Cubic - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/Cubic/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/Cubic.md - Description: 三次贝塞尔曲线边 Cubic --- title: "三次贝塞尔曲线边 Cubic" description: "三次贝塞尔曲线边 Cubic" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/Cubic/" version: "5.1.1" --- ## 概述 三次贝塞尔曲线是一种通用的平滑曲线,其控制点可以自由分布,适合连接任意方向的节点。 使用场景: - 适用于任意布局的图,如网络图、关系图。 - 当需要平滑连接节点且无特定方向要求时使用。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node1' }, { id: 'node2' }], edges: [{ id: 'edge1', source: 'node1', target: 'node2', text: 'cubic' }], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, }, }, edge: { type: 'cubic', style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, }, }, behaviors: ['drag-canvas', 'drag-element'], layout: { type: 'grid', cols: 2 }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { gui.add({ type: 'cubic' }, 'type').disable(); const options = { curveOffset: 20, curvePosition: 0.5, }; const optionFolder = gui.addFolder('cubic.style'); optionFolder.add(options, 'curveOffset', 0, 100, 1); optionFolder.add(options, 'curvePosition', 0, 1, 0.1); optionFolder.onChange(({ property, value }) => { graph.updateEdgeData([{ id: 'edge1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `edge.type` 为 `cubic` 以使用三次贝塞尔曲线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------- | ------ | ---- | | controlPoints | 控制点数组,用于定义曲线的形状。如果不指定,将会通过 `curveOffset` 和 `curvePosition` 来计算控制点 | [[Point](#point), [Point](#point)] | - | | | curvePosition | 控制点在两端点连线上的相对位置,范围为`0-1` | number | number[] | 0.5 | | | curveOffset | 控制点距离两端点连线的距离,可理解为控制边的弯曲程度 | number | number[] | 20 | | #### Point ```typescript type Point = [number, number] | [number, number, number] | Float32Array; ``` ## 示例 ### 内置三次贝塞尔曲线边效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'cubic', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 圆形节点 Circle - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Circle/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Circle.md - Description: 圆形节点 Circle --- title: "圆形节点 Circle" description: "圆形节点 Circle" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Circle/" version: "5.1.1" --- ## 概述 圆形是一个对称的几何形状,具有均匀的半径。 适用场景: - 用于表示节点的大小或权重(通过半径控制)。 - 适合表示无方向性的关系,如社交网络中的用户节点。 - 常用于流程图、网络图、拓扑图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }], }, node: { type: 'circle', }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'circle' }, 'type').disable(); const options = { size: 40 }; const optionFolder = gui.addFolder('circle.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见[BaseNode](/zh/manual/element/node/BaseNode/) ## 示例 ### 内置圆形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'circle', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 原子 Shape 以及其属性 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/shape/properties/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/shape/properties.md - Description: 原子 Shape 以及其属性 --- title: "原子 Shape 以及其属性" description: "原子 Shape 以及其属性" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/shape/properties/" version: "5.1.1" --- G6 中的元素(节点/边)是由**一个或多个 [图形 Shape](/zh/manual/element/shape/overview/)** 组成,主要通过自定义节点或自定义边时在 `render` 方法中使用 `upsert` 添加,G6 中支持以下的图形 Shape: 1. [Circle - 圆形](#circlestyleprops) 2. [Ellipse - 椭圆](#ellipsestyleprops) 3. [Rect - 矩形](#rectstyleprops) 4. [HTML - HTML元素](#htmlstyleprops) 5. [Image - 图片](#imagestyleprops) 6. [Line - 线](#linestyleprops) 7. [Path - 路径](#pathstyleprops) 8. [Polygon - 多边形](#polygonstyleprops) 9. [Polyline - 折线](#polylinestyleprops) 10. [Text - 文本](#textstyleprops) ## 各图形 Shape 的通用属性 ### BaseShapeStyle | 属性 | 描述 | 类型 | 必选 | | -------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------- | ---- | | x | x 坐标 | number | ✓ | | y | y 坐标 | number | ✓ | | width | 宽度 | number | ✓ | | height | 高度 | number | ✓ | | fill | 填充颜色 | string \| Pattern \| null | | | stroke | 描边颜色 | string \| Pattern \| null | | | opacity | 整体透明度 | number \| string | | | fillOpacity | 填充透明度 | number \| string | | | strokeOpacity | 描边透明度 | number \| string | | | lineWidth | 线宽度 | number \| string | | | lineCap | 线段端点样式 | `butt` \| `round` \| `square` | | | lineJoin | 线段连接处样式 | `miter` \| `round` \| `bevel` | | | lineDash | 虚线配置 | number \| string \| (string \| number)[] | | | lineDashOffset | 虚线偏移量 | number | | | shadowBlur | 阴影模糊程度 | number | | | shadowColor | 阴影颜色 | string | | | shadowOffsetX | 阴影 X 方向偏移 | number | | | shadowOffsetY | 阴影 Y 方向偏移 | number | | | cursor | 鼠标样式,[CSS 的 cursor](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) 选项都支持 | string | | | zIndex | 渲染层级 | number | | | visibility | 可见性 | `visible` \| `hidden` | | **示例:** ```js const shape = BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'circle', { cx: 100, cy: 100, r: 50, fill: 'blue', }, container, ); ``` ## 各图形 Shape 的通用方法 ### attr() 设置或获取实例的绘图属性。 ### attr(name) 获取实例的属性值。 ```js const width = shape.attr('width'); ``` ### attr(name, value) 更新实例的单个绘图属性。 ### attr({...}) 批量更新实例绘图属性。 ```js shape.attr({ fill: '#999', stroke: '#666', }); ``` ## 圆图形 Circle ### CircleStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ---------------------------------- | ---------------- | ---- | | cx | 圆心 x 坐标 | number \| string | ✓ | | cy | 圆心 y 坐标 | number \| string | ✓ | | cz | 圆心 z 坐标 | number \| string | | | r | 圆的半径 | number \| string | ✓ | | isBillboard | 是否启用公告牌模式(始终面向相机) | boolean | | | isSizeAttenuation | 是否启用大小衰减(随视距变化大小) | boolean | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'circle', { cx: 100, cy: 100, r: 50, fill: 'blue', }, container, ); ``` ## 矩形图形 Rect ### RectStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ------------------ | ---------------------------- | ---- | | x | 矩形 x 坐标 | number \| string | | | y | 矩形 y 坐标 | number \| string | | | z | 矩形 z 坐标 | number | | | width | 矩形宽度 | number \| string | ✓ | | height | 矩形高度 | number \| string | ✓ | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | radius | 矩形圆角半径 | number \| string \| number[] | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'rect', { x: 100, y: 100, width: 100, height: 100, radius: 8, fill: 'blue', }, container, ); ``` ## 椭圆图形 Ellipse ### EllipseStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ------------------ | ---------------- | ---- | | cx | 椭圆中心 x 坐标 | number \| string | ✓ | | cy | 椭圆中心 y 坐标 | number \| string | ✓ | | cz | 椭圆中心 z 坐标 | number \| string | | | rx | 椭圆 x 轴半径 | number \| string | ✓ | | ry | 椭圆 y 轴半径 | number \| string | ✓ | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'ellipse', { cx: 100, cy: 100, rx: 50, ry: 80, fill: 'blue', }, container, ); ``` ## HTML DOM ### HTMLStyleProps | 属性 | 描述 | 类型 | 必选 | | --------- | ---------------- | --------------------- | ---- | | x | HTML 元素 x 坐标 | number \| string | | | y | HTML 元素 y 坐标 | number \| string | | | innerHTML | HTML 内容 | string \| HTMLElement | ✓ | | width | HTML 元素宽度 | number \| string | | | height | HTML 元素高度 | number \| string | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'html', { x: 100, y: 100, innerHTML:
content
, }, container, ); ``` ## 图片图形 Image ### ImageStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ---------------------------- | -------------------------- | ---- | | x | 图片 x 坐标 | number \| string | | | y | 图片 y 坐标 | number \| string | | | z | 图片 z 坐标 | number | | | src | 图片资源路径或 HTML 图片元素 | string \| HTMLImageElement | ✓ | | width | 图片宽度 | number \| string | | | height | 图片高度 | number \| string | | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | billboardRotation | 公告牌模式下的旋转角度 | number | | | keepAspectRatio | 是否保持图片原有宽高比 | boolean | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'image', { x: 100, y: 100, src: 'http://', }, container, ); ``` ## 直线 Line ### LineStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ------------------ | --------------------- | ---- | | x1 | 线段起点 x 坐标 | number | ✓ | | y1 | 线段起点 y 坐标 | number | ✓ | | x2 | 线段终点 x 坐标 | number | ✓ | | y2 | 线段终点 y 坐标 | number | ✓ | | z1 | 线段起点 z 坐标 | number | | | z2 | 线段终点 z 坐标 | number | | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | markerStart | 线段起点的标记 | DisplayObject \| null | | | markerEnd | 线段终点的标记 | DisplayObject \| null | | | markerStartOffset | 起点标记的偏移量 | number | | | markerEndOffset | 终点标记的偏移量 | number | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'line', { x1: 100, y1: 100, x2: 150, y2: 150, stroke: 'blue', }, container, ); ``` ## 路径 Path ### PathStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | -------------------- | ---------------------- | ---- | | d | 路径定义字符串或数组 | string \| PathArray | ✓ | | markerStart | 路径起点的标记 | DisplayObject \| null | | | markerEnd | 路径终点的标记 | DisplayObject \| null | | | markerMid | 路径中间点的标记 | DisplayObject \| null | | | markerStartOffset | 起点标记的偏移量 | number | | | markerEndOffset | 终点标记的偏移量 | number | | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | fillRule | 填充规则 | `nonzero` \| `evenodd` | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'path', { d: 'M 0,0 L 20,10 L 20,-10 Z', stroke: 'blue', }, container, ); ``` ## 多边形图形 Polygon ### PolygonStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ------------------ | ------------------------------------------------ | ---- | | points | 多边形的顶点数组 | ([number, number] \| [number, number, number])[] | ✓ | | markerStart | 多边形起点的标记 | DisplayObject \| null | | | markerEnd | 多边形终点的标记 | DisplayObject \| null | | | markerMid | 多边形中间点的标记 | DisplayObject \| null | | | markerStartOffset | 起点标记的偏移量 | number | | | markerEndOffset | 终点标记的偏移量 | number | | | isClosed | 是否闭合多边形 | boolean | | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'polygon', { points: [ [30, 30], [40, 20], [30, 50], [60, 100], ], fill: 'red', }, container, ); ``` ## 折线 Polyline ### PolylineStyleProps | 属性 | 描述 | 类型 | 必选 | | ----------------- | ------------------ | ------------------------------------------------ | ---- | | points | 折线的顶点数组 | ([number, number] \| [number, number, number])[] | ✓ | | markerStart | 折线起点的标记 | DisplayObject \| null | | | markerEnd | 折线终点的标记 | DisplayObject \| null | | | markerMid | 折线中间点的标记 | DisplayObject \| null | | | markerStartOffset | 起点标记的偏移量 | number | | | markerEndOffset | 终点标记的偏移量 | number | | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'polyline', { points: [ [30, 30], [40, 20], [30, 50], [60, 100], ], fill: 'red', }, container, ); ``` ## 文字 Text ### TextStyleProps | 属性 | 描述 | 类型 | 必选 | | ------------------- | ------------------ | --------------------------------------------------------------------------- | ---- | | x | 文本 x 坐标 | number \| string | | | y | 文本 y 坐标 | number \| string | | | z | 文本 z 坐标 | number \| string | | | text | 文本内容 | number \| string | ✓ | | fontSize | 字体大小 | number \| string | | | fontFamily | 字体族 | string | | | fontStyle | 字体样式 | `normal` \| `italic` \| `oblique` | | | fontWeight | 字体粗细 | `normal` \| `bold` \| `bolder` \| `lighter` \| number | | | fontVariant | 字体变种 | `normal` \| `small-caps` \| string | | | textAlign | 文本水平对齐方式 | `start` \| `center` \| `middle` \| `end` \| `left` \| `right` | | | textBaseline | 文本基线 | `top` \| `hanging` \| `middle` \| `alphabetic` \| `ideographic` \| `bottom' | | | textOverflow | 文本溢出处理方式 | `clip` \| `ellipsis` \| string | | | lineHeight | 行高 | number \| string | | | letterSpacing | 字间距 | number \| string | | | maxLines | 最大行数 | number | | | textPath | 文本路径 | Path | | | textPathSide | 文本路径侧边 | `left` \| `right` | | | textPathStartOffset | 文本路径起始偏移 | number \| string | | | textDecorationLine | 文本装饰线 | string | | | textDecorationColor | 文本装饰线颜色 | string | | | textDecorationStyle | 文本装饰线样式 | `solid` \| `double` \| `dotted` \| `dashed` \| `wavy` | | | isBillboard | 是否启用公告牌模式 | boolean | | | billboardRotation | 公告牌旋转角度 | number | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | wordWrap | 是否自动换行 | boolean | | | wordWrapWidth | 自动换行宽度 | number | | | dx | X 方向偏移 | number \| string | | | dy | Y 方向偏移 | number \| string | | **示例:** ```js BaseShape.upsert( // 指定图形 key,需要保证在同一个自定义元素类型中保持唯一性 'shape', 'text', { x: 100, y: 100, text: 'text', }, container, ); ``` 多行文字显示: ```js { wordWrap: true, wordWrapWidth: 100, maxLines: 4, textOverflow: 'ellipsis', } ``` #### 元素状态 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/state/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/state.md - Description: 元素状态 --- title: "元素状态" description: "元素状态" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/state/" version: "5.1.1" --- ## 什么是元素状态 元素状态(State)是指图中元素(节点、边、组合)在不同交互场景下的视觉表现形式。比如当用户点击一个节点时,节点可能会变成"选中"状态并改变颜色;当鼠标悬停在边上时,边可能会进入"高亮"状态并加粗显示。 **简单来说,状态让元素能够根据用户的操作或业务逻辑动态改变外观。** ### 状态的特点 - **多状态共存**:一个元素可以同时拥有多个状态,比如既是"选中"又是"高亮" - **样式叠加**:多个状态的样式会叠加在一起,后设置的状态样式优先级更高 - **完全自定义**:除了内置状态,您可以创建任何符合业务需求的自定义状态 ## 内置状态类型 G6 提供了一些常用的内置状态,您可以直接使用: | 状态名 | 说明 | 典型使用场景 | | ----------- | ---------- | ------------------ | | `selected` | 选中状态 | 用户点击选择元素时 | | `active` | 激活状态 | 当前正在交互的元素 | | `highlight` | 高亮状态 | 需要强调显示的元素 | | `inactive` | 非活跃状态 | 淡化显示非关注元素 | | `disabled` | 禁用状态 | 不可交互的元素 | > 💡 **提示**:这些内置状态并非必须使用,您完全可以根据业务需求定义自己的状态名称。 ## 配置状态样式 ### 基础配置 在创建图实例时,为不同状态配置相应的样式: ```javascript const graph = new Graph({ // 节点的状态样式配置 node: { // 默认样式(无状态时的样式) style: { fill: '#C6E5FF', stroke: '#5B8FF9', lineWidth: 1, }, // 各种状态下的样式 state: { selected: { fill: '#95D6FB', stroke: '#1890FF', lineWidth: 2, shadowColor: '#1890FF', shadowBlur: 10, }, highlight: { stroke: '#FF6A00', lineWidth: 2, }, disabled: { fill: '#ECECEC', stroke: '#BFBFBF', opacity: 0.5, }, }, }, // 边的状态样式配置 edge: { style: { stroke: '#E2E2E2', lineWidth: 1, }, state: { selected: { stroke: '#1890FF', lineWidth: 2, }, highlight: { stroke: '#FF6A00', lineWidth: 3, }, }, }, // 组合的状态样式配置 combo: { style: { fill: '#F0F0F0', stroke: '#D9D9D9', }, state: { selected: { stroke: '#1890FF', lineWidth: 2, }, }, }, }); ``` ### 自定义状态 您可以创建任何符合业务需求的自定义状态: ```javascript const graph = new Graph({ node: { style: { fill: '#C6E5FF', stroke: '#5B8FF9', }, state: { // 自定义状态:错误 error: { fill: '#FFEBE6', stroke: '#FF4D4F', lineWidth: 2, lineDash: [4, 4], // 虚线边框 }, // 自定义状态:成功 success: { fill: '#F6FFED', stroke: '#52C41A', lineWidth: 2, }, // 自定义状态:警告 warning: { fill: '#FFFBE6', stroke: '#FAAD14', lineWidth: 2, // 添加图标 icon: { show: true, text: '⚠️', fontSize: 16, }, }, }, }, }); ``` ## 设置元素状态 ### 数据中设置初始状态 在数据中为元素设置初始状态: ```javascript const data = { nodes: [ { id: 'node1', states: ['selected'], // 初始为选中状态 }, { id: 'node2', states: ['disabled'], // 初始为禁用状态 }, { id: 'node3', states: ['highlight', 'active'], // 初始有多个状态 }, ], edges: [ { source: 'node1', target: 'node2', states: ['highlight'], // 边的初始状态 }, ], }; graph.setData(data); ``` ### 动态设置状态 通过 API 动态改变元素状态: ```javascript // 设置单个元素的单个状态 graph.setElementState('node1', 'selected'); // 设置单个元素的多个状态 graph.setElementState('node2', ['highlight', 'active']); // 批量设置多个元素的状态 graph.setElementState({ node1: ['selected'], node2: ['highlight'], edge1: ['active'], }); ``` ### 状态的叠加效果 当元素有多个状态时,样式会按顺序叠加: ```javascript // 假设节点同时有 selected 和 highlight 状态 graph.setElementState('node1', ['selected', 'highlight']); // 最终样式 = 默认样式 + selected状态样式 + highlight状态样式 // 如果有样式冲突,后面的状态样式会覆盖前面的 ``` ## 清除元素状态 ### 清除所有状态 将元素恢复到默认状态(无任何状态): ```javascript // 清除单个元素的所有状态 graph.setElementState('node1', []); // 批量清除多个元素的状态 graph.setElementState({ node1: [], node2: [], edge1: [], }); ``` ### 清除特定状态 如果元素有多个状态,您可以只清除其中的某些状态: ```javascript // 假设 node1 当前有 ['selected', 'highlight', 'active'] 三个状态 // 现在只想保留 'selected' 状态,清除其他状态 graph.setElementState('node1', ['selected']); // 或者获取当前状态,然后过滤掉不需要的状态 const currentStates = graph.getElementState('node1'); const newStates = currentStates.filter((state) => state !== 'highlight'); graph.setElementState('node1', newStates); ``` ### 清除所有元素的特定状态 ```javascript // 清除所有节点的 'highlight' 状态 const allNodes = graph.getNodeData(); const stateUpdates = {}; allNodes.forEach((node) => { const currentStates = graph.getElementState(node.id); const newStates = currentStates.filter((state) => state !== 'highlight'); stateUpdates[node.id] = newStates; }); graph.setElementState(stateUpdates); ``` ## 查询元素状态 ### 获取元素状态 ```javascript // 获取指定元素的所有状态 const states = graph.getElementState('node1'); console.log(states); // 例如:['selected', 'highlight'] // 如果元素没有任何状态,返回空数组 console.log(states); // [] ``` ### 查找特定状态的元素 ```javascript // 获取所有处于 'selected' 状态的节点数据 const selectedNodes = graph.getElementDataByState('node', 'selected'); // 获取所有处于 'highlight' 状态的边数据 const highlightEdges = graph.getElementDataByState('edge', 'highlight'); ``` ### 判断元素是否处于某状态 ```javascript // 检查元素是否处于特定状态 const states = graph.getElementState('node1'); const isSelected = states.includes('selected'); const isHighlight = states.includes('highlight'); console.log('节点是否选中:', isSelected); console.log('节点是否高亮:', isHighlight); ``` #### 坐标系 - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/coordinate/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/coordinate.md - Description: 坐标系 --- title: "坐标系" description: "坐标系" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/coordinate/" version: "5.1.1" --- ## 概述 在 G6 5.0 中主要会涉及三个坐标系:画布坐标系(Canvas)、视口坐标系(Viewport)和浏览器坐标系(Client)。 ### 画布坐标系 G6 元素绘制时所使用的坐标系,其不受相机缩放、平移的影响,要改变一个元素的位置,需要直接修改元素的位置属性(x/y/z)。 画布空间理论上是无限大的,在初始状态下(无平移、缩放倍率为1),画布坐标系的原点位于视口左上角位置。 ### 视口坐标系 视口坐标系是相机坐标系的投影,当相机发生平移、缩放时,画布中元素位置在视口坐标系中的位置也会发生变化。 视口的大小即画布 DOM 容器的大小,视口坐标系的原点位于视口左上角位置,x 轴正方向向右,y 轴正方向向下。 ![viewport](https://developer.mozilla.org/en-US/Web/API/Canvas_API/Tutorial/Drawing_shapes/canvas_default_grid.png) ### 浏览器坐标系 浏览器坐标系以浏览器左上角为原点,x 轴正方向向右,y 轴正方向向下。 下图描述了视口坐标系和浏览器坐标系之间的关系: ## 坐标系转换 G6 提供了坐标系转换的方法,可以方便地在不同坐标系之间进行转换。 - 画布坐标系转视口坐标系:[getViewportByCanvas](/zh/api/coordinate/#graphgetviewportbycanvaspoint) - 浏览器坐标系转画布坐标系:[getCanvasByClient](/zh/api/coordinate/#graphgetcanvasbyclientpoint) - 视口坐标系转画布坐标系:[getCanvasByViewport](/zh/api/coordinate/#graphgetcanvasbyviewportpoint) - 画布坐标系转浏览器坐标系:[getClientByCanvas](/zh/api/coordinate/#graphgetclientbycanvaspoint) 另外还提供了其他相关 API: - 获取视口中心的视口坐标:[getCanvasCenter](/zh/api/viewport/#graphgetcanvascenter) - 获取视口中心的画布坐标:[getViewportCenter](/zh/api/viewport/#graphgetviewportcenter) - 获取图原点在视口坐标系中的位置:[getPosition](/zh/api/viewport/#graphgetposition) #### 在 Angular 中使用 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/angular/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/integration/angular.md - Description: 在 Angular 中使用 --- title: "在 Angular 中使用" description: "在 Angular 中使用" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/integration/angular/" version: "5.1.1" --- 参考下面的示例,你可以在 Angular 中使用 G6,也可以查看 [在线示例](https://stackblitz.com/edit/g6-in-angular?file=src%2Fmain.ts)。 **app.component.html** ```html

{{ title }}

``` **app.component.ts** ```ts import { Component, ViewChild, ElementRef } from '@angular/core'; import { Graph } from '@antv/g6'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'Use G6 in Angular'; @ViewChild('container') container: ElementRef; ngAfterViewInit() { const graph = new Graph({ container: this.container.nativeElement, width: 500, height: 500, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 100 }, }, { id: 'node-2', style: { x: 150, y: 100 }, }, ], edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2' }], }, }); graph.render(); } } ``` #### AntV Dagre 布局 AntvDagre - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/AntvDagreLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/AntvDagreLayout.md - Description: AntV Dagre 布局 AntvDagre --- title: "AntV Dagre 布局 AntvDagre" description: "AntV Dagre 布局 AntvDagre" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/AntvDagreLayout/" version: "5.1.1" --- ## 概述 AntvDagre 在原先[dagre](https://github.com/dagrejs/dagre/wiki)布局的基础上增加了更多有用的设置项,比如`nodeOrder`、`edgeLabelSpace`等等。 `dagre`布局本身一种层次化布局,适用于有向无环图(DAG)的布局场景,能够自动处理节点之间的方向和间距,支持水平和垂直布局。参考更多 Dagre 布局[样例](/zh/examples/layout/dagre/)或[源码](https://github.com/dagrejs/dagre/blob/master/lib/layout.js)以及[官方文档](https://github.com/dagrejs/dagre/wiki)。 Dagre布局 ## 配置方式 ```js const graph = new Graph({ layout: { type: 'antv-dagre', rankdir: 'TB', align: 'UL', nodesep: 50, ranksep: 50, controlPoints: false, }, }); ``` ## 配置项 > 更多`dagre`原生配置项可参考[官方文档](https://github.com/dagrejs/dagre/wiki#configuring-the-layout),这里仅列出部分核心配置和新增的配置 Dagre 布局配置项图解 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------ | ---- | | type | 布局类型 | `antv-dagre` | - | ✓ | | rankdir | 布局方向,可选值 | `TB` \| `BT` \| `LR` \| `RL` | `TB` | | | align | 节点对齐方式,可选值 | `UL` \| `UR` \| `DL` \| `DR` | `UL` | | | nodesep | 节点间距(px)。在 rankdir 为 `TB` 或 `BT` 时是节点的水平间距;在 rankdir 为 `LR` 或 `RL` 时代表节点的竖直方向间距 | number | 50 | | | nodesepFunc | 节点间距(px)的回调函数,优先级高于 `nodesep` | (d?: Node) => number | - | | | ranksep | 层间距(px)。在 rankdir 为 `TB` 或 `BT` 时是竖直方向相邻层间距;在 rankdir 为 `LR` 或 `RL` 时代表水平方向相邻层间距 | number | 50 | | | ranksepFunc | 层间距(px)的回调函数,优先级高于 `ranksep` | (d?: Node) => number | - | | | ranker | 为每个节点分配等级的算法,共支持三种算法:`longest-path`、`tight-tree`、`network-simplex` | `network-simplex` \| `tight-tree` \| `longest-path` | - | | | nodeSize | 统一指定或为每个节点指定节点大小,用于占位与间距计算 | Size \| ((nodeData: Node) => Size) | - | | | controlPoints | 是否保留边的控制点,仅在边配置中使用了内置折线(type: 'polyline-edge')时,或任何将自定义消费了 `style.controlPoints` 字段作为控制点位置的边时生效 | boolean | false | | | begin | 布局的左上角对齐位置 | [number, number] \| [number, number, number] | - | | | sortByCombo | 同一层节点是否根据每个节点数据中的 `parentId` 进行排序,以防止 Combo 重叠 | boolean | false | | | edgeLabelSpace | 是否为边的 label 预留位置 | boolean | true | | | nodeOrder | 同层节点顺序的参考数组,存放节点 id 值 | string[] | - | | | radial | 是否基于 `dagre` 进行辐射布局 | boolean | - | | | focusNode | 关注的节点,仅在 `radial` 为 true 时生效 | ID \| Node \| null | - | | | preset | 布局计算时参考的节点位置,一般用于切换数据时保证重新布局的连续性 | NodeData[] | - | | > 补充:在 G6 中,`antv-dagre` 计算得到的控制点会被写入边的 `style.controlPoints`。 ### align > _DagreAlign_ **Default:** `UL` 节点对齐方式 U:upper(上);D:down(下);L:left(左);R:right(右) - `UL`:对齐到左上角 - `UR`:对齐到右上角 - `DL`:对齐到左下角 - `DR`:对齐到右下角 ### rankdir > _DagreRankdir_ **Default:** `TB` 布局的方向。T:top(上);B:bottom(下);L:left(左);R:right(右) - `TB`:从上至下布局 - `BT`:从下至上布局 - `LR`:从左至右布局 - `RL`:从右至左布局 ### ranker > _`network-simplex` \| `tight-tree` \| `longest-path`_ 布局的模式 ### ranksep > _number_ **Default:** 50 层间距(px) 在 rankdir 为 'TB' 或 'BT' 时是竖直方向相邻层间距;在 rankdir 为 'LR' 或 'RL' 时代表水平方向相邻层间距。ranksepFunc 拥有更高的优先级 ### ranksepFunc > _(d?: Node) => number_ 层间距(px)的回调函数 在 rankdir 为 'TB' 或 'BT' 时是竖直方向相邻层间距;在 rankdir 为 'LR' 或 'RL' 时代表水平方向相邻层间距。优先级高于 nodesep,即若设置了 nodesepFunc,则 nodesep 不生效 ### nodesep > _number_ **Default:** 50 节点间距(px) 在 rankdir 为 'TB' 或 'BT' 时是节点的水平间距;在 rankdir 为 'LR' 或 'RL' 时代表节点的竖直方向间距。nodesepFunc 拥有更高的优先级 ### nodesepFunc > _(d?: Node) => number_ 节点间距(px)的回调函数,通过该参数可以对不同节点设置不同的节点间距 在 rankdir 为 'TB' 或 'BT' 时是节点的水平间距;在 rankdir 为 'LR' 或 'RL' 时代表节点的竖直方向间距。优先级高于 nodesep,即若设置了 nodesepFunc,则 nodesep 不生效 ### begin > _[number, number] \| [number, number, number]_ **Default:** undefined 布局的左上角对齐位置 ### controlPoints > _boolean_ **Default:** false 是否保留边的控制点,仅在边配置中使用了内置折线(type: 'polyline-edge') 时,或任何将自定义消费了 `style.controlPoints` 字段作为控制点位置的边时生效。本质上就是给边数据增加了 `style.controlPoints` ### edgeLabelSpace > _boolean_ **Default:** true 是否为边的label留位置 这会影响是否在边中间添加dummy node ### focusNode > _ID \| Node \| null_ 关注的节点,注意,仅在`radial` 为 true 时生效 - ID: 节点 id - Node: 节点实例 - null: 取消关注 ### nodeOrder > _string[]_ **Default:** undefined 同层节点顺序的参考数组,存放节点 id 值 若未指定,则将按照 dagre 本身机制排列同层节点顺序 ### nodeSize > _Size \| ((nodeData: Node) => Size)_ **Default:** undefined 统一指定或为每个节点指定节点大小。 用于防止节点重叠时的碰撞检测 ### preset > _OutNode[]_ **Default:** undefined 布局计算时参考的节点位置 一般用于切换数据时保证重新布局的连续性。在 G6 中,若是更新数据,则将自动使用已存在的布局结果数据作为输入 ### radial > _boolean_ 是否基于 dagre 进行辐射布局 ### sortByCombo > _boolean_ **Default:** false 同一层节点是否根据每个节点数据中的 parentId 进行排序,以防止 Combo 重叠 建议在有 Combo 的情况下配置 ## 布局适用场景 - **流程图**:适合展示流程图,节点之间的方向和间距会自动处理; - **依赖关系图**:展示软件包或模块之间的依赖关系; - **任务调度图**:展示任务之间的依赖关系和执行顺序。 ## 相关文档 > 以下文档可以帮助你更好地理解 Dagre 布局 - [图布局算法|详解 Dagre 布局](https://mp.weixin.qq.com/s/EdyTfFUH7fyMefNSBXI2nA) - [深入解读Dagre布局算法](https://www.yuque.com/antv/g6-blog/xxp5nl) #### 气泡集 BubbleSets - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/BubbleSets/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/BubbleSets.md - Description: 气泡集 BubbleSets --- title: "气泡集 BubbleSets" description: "气泡集 BubbleSets" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/BubbleSets/" version: "5.1.1" --- ## 概述 BubbleSets 插件通过创建气泡形状来表示集合及其关系,帮助用户直观地理解集合间的交集、并集等逻辑关系。它是一种增强数据可视化效果的工具,特别适用于展示复杂的数据集合关系。 ## 使用场景 BubbleSets 插件主要适用于以下场景: - 展示集合间的关系(如交集、并集) - 增强数据可视化的表达能力 - 在复杂网络图中标识特定节点或边的集合 ## 基本用法 以下是一个简单的 BubbleSets 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node1', 'node2'], // 需要包裹的节点 ID 列表 label: true, // 是否显示标签 }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, node: { style: { labelText: (d) => d.id }, palette: { field: 'cluster', color: ['#7e3feb', '#ffa940'] }, }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ 'grid-line', { type: 'bubble-sets', key: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], labelText: 'bubblesets-a', fill: '#7e3feb', fillOpacity: 0.1, stroke: '#7e3feb', strokeOpacity: 1, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: '#7e3feb', labelBackgroundRadius: 5, }, ], }, { width: 600, height: 450 }, (gui, graph) => { const options = { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], avoidMembers: [], // style fill: '#7e3feb', fillOpacity: 0.1, stroke: '#7e3feb', strokeOpacity: 1, // label label: true, labelCloseToPath: true, labelAutoRotate: true, labelOffsetX: 0, labelOffsetY: 0, labelPlacement: 'bottom', // bubblesets maxRoutingIterations: 100, maxMarchingIterations: 20, pixelGroup: 4, edgeR0: 10, edgeR1: 20, nodeR0: 15, nodeR1: 50, morphBuffer: 10, threshold: 1, memberInfluenceFactor: 1, edgeInfluenceFactor: 1, nonMemberInfluenceFactor: -0.8, virtualEdges: true, }; const optionFolder = gui.addFolder('Bubblesets Options'); optionFolder.add(options, 'type').disable(); optionFolder.addColor(options, 'fill'); optionFolder.addColor(options, 'stroke'); optionFolder.add(options, 'fillOpacity', 0, 1, 0.1); optionFolder.add(options, 'strokeOpacity', 0, 1, 0.1); optionFolder.add(options, 'label'); optionFolder.add(options, 'labelCloseToPath'); optionFolder.add(options, 'labelAutoRotate'); optionFolder.add(options, 'labelOffsetX', 0, 20, 1); optionFolder.add(options, 'labelOffsetY', 0, 20, 1); optionFolder.add(options, 'labelPlacement', ['left', 'right', 'top', 'bottom', 'center']); optionFolder.add(options, 'maxRoutingIterations', 0, 200, 1); optionFolder.add(options, 'maxMarchingIterations', 0, 40, 1); optionFolder.add(options, 'pixelGroup', 0, 20, 1); optionFolder.add(options, 'edgeR0', 0, 50, 1); optionFolder.add(options, 'edgeR1', 0, 50, 1); optionFolder.add(options, 'nodeR0', 0, 50, 1); optionFolder.add(options, 'nodeR1', 0, 50, 1); optionFolder.add(options, 'morphBuffer', 0, 20, 1); optionFolder.add(options, 'threshold', -1, 1, 0.1); optionFolder.add(options, 'memberInfluenceFactor', -1, 1, 0.1); optionFolder.add(options, 'edgeInfluenceFactor', -1, 1, 0.1); optionFolder.add(options, 'nonMemberInfluenceFactor', -1, 1, 0.1); optionFolder.add(options, 'virtualEdges'); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'bubble-sets', [property]: value, }); graph.render(); }); const apiConfig = { member: 'node-1', avoidMember: 'node-1', }; const apiFolder = gui.addFolder('Bubblesets API'); const instance = graph.getPluginInstance('bubble-sets'); const nodeIds = graph.getData().nodes.map((node) => node.id); const edgeIds = graph.getData().edges.map((edge) => edge.id); apiFolder.add(apiConfig, 'member', [...nodeIds, ...edgeIds]); apiFolder.add({ addMember: () => instance.addMember(apiConfig.member) }, 'addMember').name('add member'); apiFolder .add({ removeMember: () => instance.removeMember(apiConfig.member) }, 'removeMember') .name('remove member'); apiFolder .add({ removeMember: () => alert('Members in Bubblesets: ' + instance.getMember()) }, 'removeMember') .name('get member'); apiFolder.add(apiConfig, 'avoidMember', nodeIds); apiFolder .add({ addAvoidMember: () => instance.addAvoidMember(apiConfig.avoidMember) }, 'addAvoidMember') .name('add avoid member'); apiFolder .add({ removeAvoidMember: () => instance.removeAvoidMember(apiConfig.avoidMember) }, 'removeAvoidMember') .name('remove avoid member'); apiFolder .add({ removeMember: () => alert('Avoid members in Bubblesets: ' + instance.getAvoidMember()) }, 'removeMember') .name('get avoid member'); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------------ | ---------------------------------------------------------------- | -------------------------------------------------------------- | ------------- | ---- | | type | 插件类型 | string | `bubble-sets` | ✓ | | key | 插件唯一标识符,用于后续更新 | string | - | | | members | 成员元素,包括节点和边,[示例](#members) | string[] | - | ✓ | | avoidMembers | 需要避开的元素,在绘制轮廓时不会包含这些元素(目前支持设置节点) | string[] | - | | | label | 是否显示标签 | boolean | true | | | labelPlacement | 标签位置 | `left` \| `right` \| `top` \| `bottom` \| `center` \| `bottom` | `bottom` | | | labelBackground | 是否显示背景 | boolean | false | | | labelPadding | 标签内边距 | number \| number[] | 0 | | | labelCloseToPath | 标签是否贴合轮廓,[示例](#labelclosetopath) | boolean | true | | | labelAutoRotate | 标签是否跟随轮廓旋转,[示例](#labelautorotate) | boolean | true | | | labelOffsetX | 标签 x 轴偏移量 | number | 0 | | | labelOffsetY | 标签 y 轴偏移量 | number | 0 | | | labelMaxWidth | 文本的最大宽度,超出会自动省略 | number | - | | | maxRoutingIterations | 计算成员之间路径的最大迭代次数 | number | 100 | | | maxMarchingIterations | 计算轮廓的最大迭代次数 | number | 20 | | | pixelGroup | 每个潜在区域组的像素数,用于提高速度 | number | 4 | | | edgeR0 | 边的半径参数 R0 | number | - | | | edgeR1 | 边的半径参数 R1 | number | - | | | nodeR0 | 节点的半径参数 R0 | number | - | | | nodeR1 | 节点的半径参数 R1 | number | - | | | morphBuffer | 形态缓冲区大小 | number | | | | threshold | 阈值 | number | - | | | memberInfluenceFactor | 成员影响因子 | number | - | | | edgeInfluenceFactor | 边影响因子 | number | - | | | nonMemberInfluenceFactor | 非成员影响因子 | number | - | | | virtualEdges | 是否使用虚拟边 | boolean | - | | ### members 成员元素,包括节点和边。 ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2'], }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'view', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, behaviors: ['drag-canvas', 'zoom-canvas'], plugins: [ { type: 'bubble-sets', key: 'bubble-sets-a', members: ['node-0', 'node-1', 'node-2'], }, ], }); graph.render(); ``` ### labelCloseToPath 示例:不让 label 贴合轮廓 ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelText: 'cluster-a', labelCloseToPath: false, }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'view', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, plugins: [ { key: 'bubble-sets-a', type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelText: 'cluster-a', labelCloseToPath: false, }, ], behaviors: ['drag-canvas', 'zoom-canvas'], }); graph.render(); ``` ### labelAutoRotate 示例:不让label标签跟随轮廓旋转 ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelText: 'cluster-a', labelAutoRotate: false, }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'view', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, plugins: [ { key: 'bubble-sets-a', type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelText: 'cluster-a', labelAutoRotate: false, }, ], behaviors: ['drag-canvas', 'zoom-canvas'], }); graph.render(); ``` ## 使用示例 ### 基础 BubbleSets 最简单的方式是直接使用预设配置: ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'center', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, behaviors: ['drag-canvas', 'zoom-canvas'], plugins: [ { type: 'bubble-sets', key: 'bubble-sets-a', members: ['node-0', 'node-1', 'node-2', 'node-3'], }, ], }); graph.render(); ``` ### 自定义 BubbleSets 样式 ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], fill: '#7e3feb', // 气泡填充颜色 fillOpacity: 0.1, // 填充透明度 stroke: '#7e3feb', // 边框颜色 strokeOpacity: 1, // 边框透明度 }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'center', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], fill: '#7e3feb', // 气泡填充颜色 fillOpacity: 0.1, // 填充透明度 stroke: '#7e3feb', // 边框颜色 strokeOpacity: 1, // 边框透明度 }, ], behaviors: ['drag-canvas', 'zoom-canvas'], }); graph.render(); ``` ### 标签配置 您可以配置标签的位置、背景、偏移量等属性,以增强可视化效果。 ```js const graph = new Graph({ plugins: [ { type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelPlacement: 'top', // 标签位置 labelBackground: true, // 显示标签背景 labelPadding: 5, // 标签内边距 }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'center', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { id: 'edge-0', source: 'node-0', target: 'node-2', }, { id: 'edge-1', source: 'node-1', target: 'node-2', }, { id: 'edge-2', source: 'node-2', target: 'node-3', }, { id: 'edge-3', source: 'node-3', target: 'node-4', }, { id: 'edge-4', source: 'node-3', target: 'node-5', }, { id: 'edge-5', source: 'node-3', target: 'node-6', }, ], }, plugins: [ { key: 'bubble-sets-a', type: 'bubble-sets', members: ['node-0', 'node-1', 'node-2', 'node-3'], label: true, // 显示标签 labelText: 'cluster-a', labelPlacement: 'top', // 标签位置 labelBackground: true, // 显示标签背景 labelPadding: 5, // 标签内边距 }, ], behaviors: ['drag-canvas', 'zoom-canvas'], }); graph.render(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/collection.json') .then((res) => res.json()) .then((data) => { const groupedNodesByCluster = data.nodes.reduce((acc, node) => { const cluster = node.data.cluster; acc[cluster] ||= []; acc[cluster].push(node.id); return acc; }, {}); const createStyle = (baseColor) => ({ fill: baseColor, stroke: baseColor, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: baseColor, labelBackgroundRadius: 5, }); const graph = new Graph({ container: 'container', data, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], node: { palette: { field: 'cluster' }, }, layout: { type: 'force', preventOverlap: true, linkDistance: (d) => { if (d.source === 'node0' || d.target === 'node0') { return 200; } return 80; }, }, plugins: [ { key: 'bubble-sets-a', type: 'bubble-sets', members: groupedNodesByCluster['a'], labelText: 'cluster-a', ...createStyle('#1783FF'), }, { key: 'bubble-sets-b', type: 'bubble-sets', members: groupedNodesByCluster['b'], labelText: 'cluster-b', ...createStyle('#00C9C9'), }, { key: 'bubble-sets-c', type: 'bubble-sets', members: groupedNodesByCluster['c'], labelText: 'cluster-c', ...createStyle('#F08F56'), }, { key: 'bubble-sets-d', type: 'bubble-sets', members: groupedNodesByCluster['d'], labelText: 'cluster-d', ...createStyle('#D580FF'), }, ], autoFit: 'center', }); graph.render(); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 自定义主题 - Canonical page: https://g6.antv.antgroup.com/zh/manual/theme/custom-theme/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/theme/custom-theme.md - Description: 自定义主题 --- title: "自定义主题" description: "自定义主题" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/theme/custom-theme/" version: "5.1.1" --- 除了使用内置主题外,G6 还支持创建自定义主题来满足特定的视觉需求。本文将介绍如何创建和使用自定义主题。 ## 创建自定义主题 一个自定义主题需要遵循主题的基本结构,包含画布背景色和元素样式配置: ```javascript const customTheme = { // 1. 画布背景色 background: '#f0f0f0', // 2. 节点配置 node: { // 调色板配置 palette: { type: 'group', color: ['#1783FF', '#00C9C9' /* 自定义颜色... */], }, // 基础样式 style: { fill: '#fff', stroke: '#d9d9d9', lineWidth: 1, // ... 其他节点样式 }, // 状态样式 state: { selected: { fill: '#e8f3ff', stroke: '#1783FF', }, // ... 其他状态样式 }, }, // 3. 边配置 edge: { style: { stroke: '#d9d9d9', lineWidth: 1, // ... 其他边样式 }, state: { // ... 状态样式 }, }, // 4. Combo 配置 combo: { style: { fill: '#f7f7f7', stroke: '#d9d9d9', // ... 其他 Combo 样式 }, state: { // ... 状态样式 }, }, }; ``` ## 使用限制 在创建自定义主题时,需要注意以下限制: 1. **仅支持静态值** ```javascript // ❌ 错误示例:不支持回调函数 const theme = { node: { style: { fill: (d) => d.style.color, }, }, }; ``` 2. **不支持配置元素类型** ```javascript // ❌ 错误示例:不支持在主题中配置元素类型 const theme = { node: { type: 'rect', style: { fill: '#fff', }, }, }; ``` 3. **状态样式需要对应默认样式** ```javascript // ✅ 正确示例:状态样式的属性在默认样式中都有定义 const theme = { node: { style: { fill: '#fff', stroke: '#000', }, state: { selected: { fill: '#e8f3ff', stroke: '#1783FF', }, }, }, }; ``` ## 应用自定义主题 先注册主题,然后通过名称引用: ```javascript // 1. 注册主题 import { register, ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.THEME, 'custom-theme', customTheme); // 2. 使用主题 const graph = new Graph({ theme: 'custom-theme', // ... 其他配置 }); ``` #### 径向标签 PlaceRadialLabels - Canonical page: https://g6.antv.antgroup.com/zh/manual/transform/PlaceRadialLabels/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/transform/PlaceRadialLabels.md - Description: 径向标签 PlaceRadialLabels --- title: "径向标签 PlaceRadialLabels" description: "径向标签 PlaceRadialLabels" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/transform/PlaceRadialLabels/" version: "5.1.1" --- **参考示例**: - [径向生态树](/zh/examples/scene-case/tree-graph/radial-dendrogram/) - [径向紧凑树](/zh/examples/scene-case/tree-graph/radial-compact-tree/) ## 配置项 ### type > _`place-radial-labels` \| string_ 此数据处理已内置,你可以通过 `type: 'place-radial-labels'` 来使用它。 ### offset > _number_ 偏移量 #### 点击选中 ClickSelect - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/ClickSelect/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/ClickSelect.md - Description: 点击选中 ClickSelect --- title: "点击选中 ClickSelect" description: "点击选中 ClickSelect" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/ClickSelect/" version: "5.1.1" --- ## 概述 当鼠标点击元素时,会使元素高亮。 ## 使用场景 这一交互主要用于: - 聚焦元素 - 查看元素详情 - 查看元素关系 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 280, y: 60, fill: '#E4504D', labelText: 'degree: 0' } }, { id: 'node-2-1', style: { x: 330, y: 140, fill: '#FFC40C', labelText: 'degree: 1' } }, { id: 'node-2-2', style: { x: 230, y: 140, fill: '#FFC40C', labelText: 'degree: 1' } }, { id: 'node-3-1', style: { x: 380, y: 220, fill: '#0f0', labelText: 'degree: 2' } }, { id: 'node-3-2', style: { x: 180, y: 220, fill: '#0f0', labelText: 'degree: 2' } }, { id: 'degree引导', style: { x: 525, y: 110, fill: null, labelText: '这里可以修改degree ->', labelFontWeight: 700, labelFontSize: 10, }, }, ], edges: [ { source: 'node-1', target: 'node-2-1' }, { source: 'node-1', target: 'node-2-2' }, { source: 'node-2-1', target: 'node-3-1' }, { source: 'node-2-2', target: 'node-3-2' }, ], }, node: { style: { label: true, labelFill: '#666', labelFontSize: 14, labelPlacement: 'bottom' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'click-select', key: 'click-select', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'click-select', type: 'click-select', animation: true, enable: true, multiple: false, trigger: 'shift+click', state: 'selected', unselectedState: undefined, degree: 0, }; const optionFolder = gui.addFolder('Click Select Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'degree', 0, 2, 1); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'unselectedState', [undefined, 'inactive']); const trigger = optionFolder .add(options, 'trigger', { 'shift+click': ['shift'], 'meta+click': ['Meta'], }) .hide(); optionFolder.add(options, 'multiple').onChange((v) => trigger.show(v)); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'click-select', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['click-select'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'click-select', key: 'click-select-1', degree: 2, // 选中扩散范围 state: 'active', // 选中的状态 neighborState: 'neighborActive', // 相邻节点附着状态 unselectedState: 'inactive', // 未选中节点状态 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | -------------- | ---- | | type | 交互类型名称。此交互已内置,你可以通过 `type: 'click-select'` 来使用它。 | `click-select` \| string | `click-select` | ✓ | | animation | 是否在元素状态切换时启用动画效果 | boolean | true | | | degree | 控制了高亮扩散范围,[示例](#degree) | number \| (event:[Event](/zh/api/event/#事件对象属性)) => number | 0 | | | enable | 是否启用点击元素的功能,支持通过函数的方式动态控制是否启用,[示例](#enable) | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | multiple | 是否允许多选 | boolean | false | | | state | 当元素被选中时应用的状态 | string \| `selected` \| `active`\| `inactive`\| `disabled`\| `highlight` | `selected` | | | neighborState | 当有元素选中时,其相邻 n 度关系的元素应用的状态。n 的值由属性 degree 控制,例如 degree 为 1 时表示直接相邻的元素,[示例](#neighborstate) | string \| `selected` \| `active`\| `inactive`\| `disabled`\| `highlight` | `selected` | | | unselectedState | 当有元素被选中时,除了选中元素及其受影响的邻居元素外,其他所有元素应用的状态,[示例](#unselectedState) | string \| `selected` \| `active`\| `inactive`\| `disabled`\| `highlight` | | | | onClick | 点击元素时的回调 | (event: [Event](/zh/api/event/#事件对象属性)) => void | | | | trigger | 按下该快捷键配合鼠标点击进行多选,按键参考: _MDN Key Values_ | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | `['shift']` | | ### degree 控制了高亮扩散范围 - 对于节点来说,`0` 表示只选中当前节点,`1` 表示选中当前节点及其直接相邻的节点和边,以此类推。 - 对于边来说,`0` 表示只选中当前边,`1` 表示选中当前边及其直接相邻的节点,以此类推。 > 如下示例,当 `degree: 0` 仅高亮红色点; > 当 `degree: 1` 高亮红色和橙色点。 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 280, y: 60, fill: '#E4504D', labelText: 'degree: 0' } }, { id: 'node-2-1', style: { x: 330, y: 140, fill: '#FFC40C', labelText: 'degree: 1' } }, { id: 'node-2-2', style: { x: 230, y: 140, fill: '#FFC40C', labelText: 'degree: 1' } }, { id: 'node-3-1', style: { x: 380, y: 220, fill: '#0f0', labelText: 'degree: 2' } }, { id: 'node-3-2', style: { x: 180, y: 220, fill: '#0f0', labelText: 'degree: 2' } }, { id: 'degree引导', style: { x: 525, y: 110, fill: null, labelText: '这里可以修改degree ->', labelFontWeight: 700, labelFontSize: 10, }, }, ], edges: [ { source: 'node-1', target: 'node-2-1' }, { source: 'node-1', target: 'node-2-2' }, { source: 'node-2-1', target: 'node-3-1' }, { source: 'node-2-2', target: 'node-3-2' }, ], }, node: { style: { label: true, labelFill: '#666', labelFontSize: 14, labelPlacement: 'bottom' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'click-select', key: 'click-select', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'click-select', type: 'click-select', animation: true, enable: true, multiple: false, trigger: 'shift+click', state: 'selected', unselectedState: undefined, degree: 0, }; const optionFolder = gui.addFolder('Click Select Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'degree', 0, 2, 1); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'unselectedState', [undefined, 'inactive']); const trigger = optionFolder .add(options, 'trigger', { 'shift+click': ['shift'], 'meta+click': ['Meta'], }) .hide(); optionFolder.add(options, 'multiple').onChange((v) => trigger.show(v)); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'click-select', [property]: value, }); graph.render(); }); }, ); ``` ### enable 是否启用点击元素的功能 可以通过函数的方式动态控制是否启用,例如只有节点被选中时才启用。 ```js { //⚠️ 注意,这里需要同时设置节点和画布,否则用户点击画布时将不会监听到事件 enable: (event) => ['node', 'canvas'].includes(event.targetType); } ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, data: { nodes: [ { id: 'node1', style: { x: 100, y: 60 } }, { id: 'node2', style: { x: 200, y: 60 } }, { id: 'node3', style: { x: 300, y: 60 } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, ], }, node: { style: { fill: '#E4504D', }, state: { active: { fill: '#0f0', }, neighborActive: { fill: '#FFC40C', }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', neighborState: 'neighborActive', enable: (event) => ['node', 'canvas'].includes(event.targetType), }, ], }); graph.render(); ``` 同理,如果只希望边能被选中: ```js { enable: (event) => ['edge', 'canvas'].includes(event.targetType); } ``` ### neighborState 当有元素选中时,其相邻 n 度关系的元素应用的状态。n 的值由属性 degree 控制,例如 degree 为 1 时表示直接相邻的元素 ```js const graph = new Graph({ behaviors: [ { type: 'click-select', degree: 1, // 被直接点击的节点附着的状态 state: 'active', // 相邻的节点附着的状态 neighborState: 'neighborActive', }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, node: { style: { fill: '#E4504D', }, state: { active: { fill: '#0f0', }, neighborActive: { fill: '#FFC40C', halo: true, }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', neighborState: 'neighborActive', }, ], }); graph.render(); ``` ### unselectedState 当有元素被选中时,除了被选中元素和扩散的邻居元素外,其他所有元素应用的状态。 内置状态: `selected` `active` `inactive` `disabled` `highlight` ```js const graph = new Graph({ behaviors: [ { type: 'click-select', degree: 1, unselectedState: 'inactive', }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, node: { style: { fill: '#E4504D', }, state: { active: { fill: '#0f0', }, neighborActive: { fill: '#FFC40C', }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', neighborState: 'neighborActive', unselectedState: 'inactive', }, ], }); graph.render(); ``` ## 示例 ### 点击选中节点及其直接相连的节点 **点击节点** 会从 默认状态 切换为 active
**相邻节点** 会从 默认状态 切换为 neighborActive ```js const graph = new Graph({ node: { style: { fill: '#E4504D', }, state: { // 选中节点状态 active: { fill: '#0f0', }, // 相邻节点状态 neighborActive: { fill: '#FFC40C', }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', // 相邻节点附着状态 neighborState: 'neighborActive', // 未选中节点状态 unselectedState: 'inactive', }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, node: { style: { fill: '#E4504D', }, state: { active: { fill: '#0f0', }, neighborActive: { fill: '#FFC40C', }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', neighborState: 'neighborActive', unselectedState: 'inactive', }, ], }); graph.render(); ``` ### 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, node: { style: { fill: '#E4504D', }, state: { active: { fill: '#0b0', }, }, }, behaviors: [ { type: 'click-select', degree: 1, state: 'active', unselectedState: 'inactive', multiple: true, trigger: ['shift'], }, 'drag-element', ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 矩形组合 Rect - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/combo/RectCombo/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/combo/RectCombo.md - Description: 矩形组合 Rect --- title: "矩形组合 Rect" description: "矩形组合 Rect" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/combo/RectCombo/" version: "5.1.1" --- ## 概述 矩形组合以直角边界组织内容,支持严格的层级结构。 适用场景: - **系统架构图**:如系统架构里面的服务分层,以及每层服务里面的细分等。 - **地理区域划分**:如城市包含多个区域,矩形组合能直观展示行政边界或功能分区。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } }, ], combos: [ { id: 'combo1', combo: 'combo2' }, { id: 'combo2', style: {} }, ], }, node: { style: { fill: '#7e3feb' } }, combo: { type: 'rect' }, behaviors: ['collapse-expand'], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { gui.add({ type: 'rect' }, 'type').disable(); }, ); ``` 设置 `combo.type` 为 `rect` 以使用矩形组合。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseCombo](/zh/manual/element/combo/BaseCombo/) ## 示例 以下示例为简单的微服务架构服务层: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 400, autoFit: 'center', data: { nodes: [ { id: 'node1', combo: 'combo2', style: { x: 100, y: 100, labelText: '微服务1' } }, { id: 'node2', combo: 'combo2', style: { x: 200, y: 100, labelText: '微服务2' } }, { id: 'node3', combo: 'combo2', style: { x: 100, y: 200, labelText: '微服务3' } }, { id: 'node4', combo: 'combo2', style: { x: 200, y: 200, labelText: '微服务4' } }, { id: 'node5', combo: 'combo3', style: { x: 300, y: 100, labelText: '第三方登录' } }, { id: 'node6', combo: 'combo3', style: { x: 300, y: 150, labelText: '任务调度' } }, { id: 'node7', combo: 'combo3', style: { x: 300, y: 200, labelText: '消息服务' } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node3', target: 'node4' }, ], combos: [ { id: 'combo1', style: { labelText: '服务层' } }, { id: 'combo2', combo: 'combo1', style: { labelText: '业务微服务' } }, { id: 'combo3', combo: 'combo1', style: { labelText: '集成模块' } }, ], }, node: { type: 'rect', }, edge: { style: { endArrow: true, }, }, combo: { type: 'rect', style: { padding: 16, }, }, behaviors: ['drag-element', 'collapse-expand'], animation: true, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 水平三次贝塞尔曲线边 CubicHorizontal - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/CubicHorizontal/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/CubicHorizontal.md - Description: 水平三次贝塞尔曲线边 CubicHorizontal --- title: "水平三次贝塞尔曲线边 CubicHorizontal" description: "水平三次贝塞尔曲线边 CubicHorizontal" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/CubicHorizontal/" version: "5.1.1" --- ## 概述 水平三次贝塞尔曲线是一种平滑的曲线,其控制点主要沿水平方向分布,适合在水平方向上连接节点。 使用场景: - 适用于水平布局的图,如流程图、层次结构图。 - 当需要强调水平方向的连接关系时使用。 > 特别注意,计算控制点时主要考虑 x 轴上的距离,忽略 y 轴的变化 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }, { id: 'node6' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4', text: 'cubic-horizontal' }, { source: 'node1', target: 'node5' }, { source: 'node1', target: 'node6' }, ], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, port: true, ports: [{ placement: 'left' }, { placement: 'right' }], }, }, edge: { type: 'cubic-horizontal', style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, }, }, behaviors: ['drag-canvas', 'drag-element'], layout: { type: 'antv-dagre', rankdir: 'LR', nodesep: 15, ranksep: 100, }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 400 }, (gui, graph) => { gui.add({ type: 'cubic-horizontal' }, 'type').disable(); const options = { curveOffset: 20, curvePosition: 0.5, }; const optionFolder = gui.addFolder('cubic-horizontal.style'); optionFolder.add(options, 'curveOffset', 0, 100); optionFolder.add(options, 'curvePosition', 0, 1); optionFolder.onChange(({ property, value }) => { graph.updateEdgeData((prev) => prev.map((edge) => ({ ...edge, style: { [property]: value } }))); graph.render(); }); }, ); ``` 设置 `edge.type` 为 `cubic-horizontal` 以使用水平方向的三次贝塞尔曲线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | ---------------------------------------------------- | ---------------------- | --------- | ---- | | curvePosition | 控制点在两端点连线上的相对位置,范围为`0-1` | number | number[] | [0.5,0.5] | | | curveOffset | 控制点距离两端点连线的距离,可理解为控制边的弯曲程度 | number | number[] | [0,0] | | ## 示例 ### 内置水平三次贝塞尔曲线边效果 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { port: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, }, edge: { type: 'cubic-horizontal', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, }, }, layout: { type: 'antv-dagre', rankdir: 'LR', nodesep: 20, ranksep: 120, }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 菱形节点 Diamond - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Diamond/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Diamond.md - Description: 菱形节点 Diamond --- title: "菱形节点 Diamond" description: "菱形节点 Diamond" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Diamond/" version: "5.1.1" --- ## 概述 菱形是一个四边相等的几何形状,具有对角线对称性。 适用场景: - 用于表示决策节点、条件判断或关键路径。 - 适合表示流程图中的判断节点或关键步骤。 - 常用于流程图、决策树、网络图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: [48, 24], fill: '#7e3feb' } }] }, node: { type: 'diamond' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'diamond' }, 'type').disable(); const options = { 'size[0]': 48, 'size[1]': 24 }; const optionFolder = gui.addFolder('diamond.style'); optionFolder.add(options, 'size[0]', 0, 100, 1); optionFolder.add(options, 'size[1]', 0, 100, 1); optionFolder.onChange(({ object }) => { graph.updateNodeData([{ id: 'node1', style: { size: [object['size[0]'], object['size[1]']] } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `diamond` 以使用菱形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) ## 示例 ### 内置菱形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'diamond', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 复合 Shape 的设计与实现 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/shape/label-shape/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/shape/label-shape.md - Description: 复合 Shape 的设计与实现 --- title: "复合 Shape 的设计与实现" description: "复合 Shape 的设计与实现" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/shape/label-shape/" version: "5.1.1" --- G6 提供了灵活的 Shape 机制,支持开发者自定义各种图形,并在节点、边、Combo 等元素中高效复用。本文将以 Label(标签)为例,讲解如何自定义 Shape、如何在元素中应用。 ## 一、Shape 的自定义与封装 ### 1. Shape 的基类设计 所有 Shape 都继承自 `BaseShape`,它统一管理了 Shape 的生命周期(创建、更新、销毁)、属性解析、动画、事件绑定等。你只需关注如何实现 `render` 方法即可。 **核心抽象:** ```js import { CustomElement } from '@antv/g'; abstract class BaseShape extends CustomElement { // 生命周期管理、属性解析、动画等... public abstract render(attributes, container): void; } ``` ### 2. 复合 Shape 层级结构示意 一个节点通常包含多个子 Shape,例如: ``` 节点(Node) ├── keyShape(主图形) ├── label(标签,辅助信息) │ ├── text(文本) │ └── rect(背景) ├── icon(图标) │ ├── text(文本) │ └── image(图片) ├── badge(徽标) │ ├── text(文本) │ └── rect(背景) └── port(锚点) │ ├── circle(圆形) ``` ### 3. Label Shape 的实现 Label 是一个典型的复合 Shape,由文本(Text)和可选的背景(Rect)组成。其实现思路如下: - **属性分离**:Label 的样式属性分为文本样式和背景样式,分别传递给 Text 和 Rect。 - **智能布局**:背景自动根据文本内容、内边距、圆角等动态调整尺寸和位置。 - **复用 upsert**:通过 `upsert` 方法自动管理子 Shape 的创建、更新、销毁。 **Label 主要代码片段:** ```js import { Text, Rect } from '@antv/g'; // 引入原子图形 export class Label extends BaseShape { public render(attributes = this.parsedAttributes, container= this): void { this.upsert('text', Text, this.getTextStyle(attributes), container); this.upsert('background', Rect, this.getBackgroundStyle(attributes), container); } // ... 省略样式提取方法 } ``` - `getTextStyle`、`getBackgroundStyle` 分别提取文本和背景的样式属性,避免相互干扰。 - `upsert` 方法保证了 Shape 的自动增删改查,极大提升了复用性和健壮性。 ### 4. 完整自定义 Shape 示例 下面以自定义一个带特殊装饰的标签为例,演示 Shape 的完整定义、注册与使用: ```js import { BaseShape, ExtensionCategory, Circle } from 'g6'; import { Text, Rect, Circle } from '@antv/g'; class FancyLabel extends BaseShape { render(attributes = this.parsedAttributes, container = this) { // 主文本 this.upsert('text', Text, this.getTextStyle(attributes), container); // 背景 this.upsert('background', Rect, this.getBackgroundStyle(attributes), container); // 额外装饰:左侧小圆点 this.upsert('dot', Circle, { x: -8, y: 0, r: 3, fill: '#faad14', }, container); } // ...实现 getTextStyle/getBackgroundStyle } // 注册自定义 Shape register(ExtensionCategory.SHAPE, 'fancy-label-shape', FancyLabel); // 定义自定义节点 class CustomCircle extends Circle { public drawFancyLabelShape(attributes, container) { this.upsert('fancy-label', 'fancy-label-shape', this.getFancyLabelStyle(attributes), container); } render(attributes = this.parsedAttributes, container) { super.render(attributes, container); this.drawFancyLabelShape(attributes, container); } } // 注册自定义节点 register(ExtensionCategory.Node, 'fancy-label-node', CustomCircle); ``` ## 二、样式属性的前缀分离 G6 中节点、边、Combo 等元素往往包含多个子 Shape(如主图形、标签、徽标、锚点等)。为了让每个子 Shape 的样式互不干扰,G6 采用了**样式属性前缀分离**的设计。 ### 1. 前缀分离的意义 - **解耦**:每个子 Shape 只关心属于自己的样式属性,避免样式污染。 - **易扩展**:新增子 Shape 只需定义新的前缀,无需修改原有逻辑。 - **配置直观**:用户在配置节点/边/Combo 时,可以一目了然地设置各部分样式。 ### 2. 代码实现 以 Label 为例: ```ts import { RectStyleProps, TextStyleProps } from '@antv/g'; type PrefixKey

= `${P}${Capitalize}`; type Prefix

= { [K in keyof T as K extends string ? PrefixKey : never]?: T[K]; }; interface LabelStyleProps extends TextStyleProps, Prefix<'background', RectStyleProps> { background?: boolean; } ``` - `Prefix<'background', RectStyleProps>` 表示所有以 `background` 开头的属性都属于标签背景样式。 - 在实际渲染时,通过 `subStyleProps`、`subObject` 等工具函数,自动提取带前缀的样式,传递给对应的 Shape。 **Label 背景样式提取示例** ```js protected getBackgroundStyle(attributes: Required) { if (attributes.background === false) return false; const style = this.getGraphicStyle(attributes); const backgroundStyle = subStyleProps(style, 'background'); // ...省略布局计算 return backgroundStyle; } ``` **样式配置示例** ```json { "text": "label", "fontSize": 12, "fontFamily": "system-ui, sans-serif", "wordWrap": true, "maxLines": 1, "wordWrapWidth": 128, "textOverflow": "...", "textBaseline": "middle", "background": true, "backgroundOpacity": 0.75, "backgroundZIndex": -1, "backgroundLineWidth": 0 } ``` ## 三、Label 与 keyShape 的关系 - **keyShape** 是节点/边/Combo 的主图形,决定交互拾取、包围盒、主样式等。 - **Label**、icon、badge、port 等通常作为辅助 Shape 存在,不会作为 keyShape。 - 你可以在自定义节点时通过 `drawKeyShape` 或类似方法指定 keyShape,Label 只负责展示文本信息,不影响节点的交互主控。 ## 四、如何在元素中应用自定义 Shape 以节点为例,节点基类 `BaseNode` 已经内置了对多种子 Shape 的支持(keyShape、label、icon、badge、port、halo 等)。你只需专注于 keyShape 的绘制,其他子 Shape 可以通过配置和样式前缀自动管理。 ### 1. 节点渲染流程 ```js protected drawLabelShape(attributes: Required, container: Group): void { const style = this.getLabelStyle(attributes); this.upsert('label', Label, style, container); } public render(attributes = this.parsedAttributes, container: Group = this) { // 1. 绘制 keyShape(主图形) this._drawKeyShape(attributes, container); if (!this.getShape('key')) return; // 2. 绘制 halo this.drawHaloShape(attributes, container); // 3. 绘制 icon this.drawIconShape(attributes, container); // 4. 绘制 badges this.drawBadgeShapes(attributes, container); // 5. 绘制 label this.drawLabelShape(attributes, container); // 6. 绘制 ports this.drawPortShapes(attributes, container); } ``` - 每个子 Shape 的样式都通过前缀分离自动提取,传递给对应的 Shape 实例。 - 你可以通过配置项灵活控制每个子 Shape 的显示与样式。 ### 2. 应用 Label 的示例 假设你要为节点添加带背景的标签,只需在节点数据中配置 label 相关属性: ```js { label: true, labelText: '我是标签', labelFill: '#333', labelFontSize: 14, labelBackground: true, labelBackgroundFill: '#fffbe6', labelBackgroundRadius: 6, labelPadding: [4, 8], } ``` - `labelText`、`labelFill`、`labelFontSize` 等会被自动提取并传递给 Label 的文本部分。 - `labelBackground`、`labelBackgroundFill`、`labelBackgroundRadius`、`labelPadding` 等会被自动提取并传递给 Label 的背景部分。 你无需手动管理 Label 的创建、更新、销毁,G6 会自动完成。 ## 五、常见问题与调试建议 ### 1. 为什么 label 样式没有生效? - 检查样式属性前缀是否正确(如 `labelFill`、`labelBackgroundFill`)。 - 确认节点/边/Combo 的 `label` 配置为 `true`,且 `labelText` 已设置。 - 检查是否被其他样式覆盖。 ### 2. 如何调试自定义 Shape 的渲染? - 使用浏览器控制台查看 `shapeMap`,确认各子 Shape 是否被正确创建。 ### 3. 如何让 Label 响应节点状态(如 hover、selected)? - 直接在图配置中设置节点状态样式(推荐) ```js const graph = new Graph({ node: { style: { label: false, }, state: { hover: { label: true, labelText: 'show when hovered', }, }, }, }); ``` - 或者在 Label 的实现中监听状态变化,动态调整样式。可以通过 data 获取到当前的状态值 --- 如需更深入了解,建议阅读源码 [`base-shape.ts`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/shapes/base-shape.ts)、[`base-node.ts`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/shapes/base-node.ts)。 #### 下载图片 - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/download-image/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/download-image.md - Description: 下载图片 --- title: "下载图片" description: "下载图片" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/download-image/" version: "5.1.1" --- G6 5.0 仅提供导出画布为 Base64 图片的 API([toDataURL](/zh/api/export-image/#graphtodataurloptions)),如果需要下载图片,可以使用以下方法: ```typescript async function downloadImage() { const dataURL = await graph.toDataURL(); const [head, content] = dataURL.split(','); const contentType = head.match(/:(.*?);/)![1]; const bstr = atob(content); let length = bstr.length; const u8arr = new Uint8Array(length); while (length--) { u8arr[length] = bstr.charCodeAt(length); } const blob = new Blob([u8arr], { type: contentType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'graph.png'; a.click(); } ``` :::warning{title=注意} 导出的图片内容可能不会包含完整的画布内容,导出范围仅包含 Graph 画布中的内容。部分插件使用了自定义的容器、画布等,这部分内容不会出现在导出的图片中。 ::: #### 详细教程 - Canonical page: https://g6.antv.antgroup.com/zh/manual/getting-started/step-by-step/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/getting-started/step-by-step.md - Description: 详细教程 --- title: "详细教程" description: "详细教程" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/getting-started/step-by-step/" version: "5.1.1" --- 本教程将引导你从头开始完成一个 G6 图表开发,并在过程中了解和学习 G6 的主要概念。 ## 创建应用 我们将使用 Vite 来创建一个简单的前端应用。 ### 初始化 首先创建一个空目录: ```bash mkdir g6-tutorial cd g6-tutorial ``` 初始化项目: ```bash npm init -y ``` 安装 G6: ```bash npm install @antv/g6 --save ``` Vite 是一个新型的前端构建工具,它基于 ESModule,可以快速启动项目。 安装 Vite: ```bash npm install vite --save-dev ``` 在 `package.json` 中添加启动脚本: ```json { "scripts": { "dev": "vite" } } ``` ### 创建文件 创建 `index.html` 和 `main.ts` 文件,内容如下: **index.html**: ```html @antv/g6 Tutorial

``` **main.ts**: ```typescript alert('Hello, G6!'); ``` ### 启动项目 ```bash npm run dev ``` 打开浏览器访问终端中输出的地址(通常为:http://127.0.0.1:5173/ ),你将看到一个弹窗显示 "Hello, G6!"。 ## 创建一个简单的图表 接下来,我们将使用 G6 创建一个简单的图表。 ### 准备数据 G6 使用 JSON 格式的数据来描述图,通常包括节点和边。我们将使用下面准备的数据: ```js const data = { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }; ``` 数据中包括两个节点和一条边,节点的 `id` 属性是必须的,并在 `style` 设置了每个节点的位置。边的 `source` 和 `target` 属性分别表示边的起始节点 `id` 和结束节点 `id`。 ### 创建并绘制图表 创建一个图表实例,传入一个配置对象,包括容器和数据,然后调用 `render` 方法渲染图表: ```typescript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, }); graph.render(); ``` 如下所示,可以看到图表已经顺利绘制出来: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, }); graph.render(); ``` ### 元素 接下来将介绍如何配置画布中的元素样式和种类。 G6 提供了多种机制来配置元素样式,可以在数据中进行配置,也可以在图表实例中进行配置。前面的示例中,我们在数据中配置了节点的位置,接下来我们在图配置项中配置节点和边的样式: ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, node: { style: { fill: 'pink', }, }, edge: { style: { stroke: 'lightgreen', }, }, }); graph.render(); ``` 正如代码所示,我们在图表实例中配置了节点的填充颜色为粉色,边的描边颜色为浅绿色。你可以在下面的示例中看到效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, node: { style: { fill: 'pink', }, }, edge: { style: { stroke: 'lightgreen', }, }, }); graph.render(); ``` 其中的关键部分是 `node.style` 和 `edge.style` 配置项,分别用来配置节点和边的样式。 > 在后续的代码示例中,我们仅展示配置项的部分代码,本项目的完整代码请查看 [完整示例](https://codesandbox.io/s/g6-tutorial)。 下面我们将通过设置节点的类型来展示更多的节点种类: ```js { node: { type: (datum) => datum.id === 'node-1' ? 'circle' : 'rect', style: { fill: 'pink', size: 20 } } } ``` 上面的代码中,我们设置了节点的 `type` 属性,其值可以是一个字符串,也可以是一个函数。当 `type` 是一个函数时,函数的参数是当前节点的数据对象,函数的返回值是节点的类型。 > 同样的,元素中 `style` 样式下的每个属性都可以是一个函数,函数的参数是当前元素的数据对象。 > 你甚至可以将整个 `style` 属性设置为一个函数,这样你可以根据数据对象动态设置元素的样式。 圆形节点(`circle`)是 G6 的默认节点类型,这里我们将第一个节点的类型设置为圆形,第二个节点的类型设置为矩形。 同时我们还将节点的大小设置为 20,因此第一个节点是一个半径为 10 的圆形,第二个节点是一个边长为 20 的正方形。 > 如果你想将矩形节点的大小设置为 20x10,可以将 `size` 设置为一个数组 `[20, 10]`。 你可以在下面的示例中看到效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 100, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, node: { type: (datum) => (datum.id === 'node-1' ? 'circle' : 'rect'), style: { fill: 'pink', size: 20, }, }, edge: { style: { stroke: 'lightgreen', }, }, }); graph.render(); ``` ### 交互 在上面的例子中提供的图表是静态的,接下来我们将添加一些交互行为。 G6 提供了多种交互行为,我们添加几个常用的交互,使得用户可以拖拽、缩放画布,拖拽节点。 ```js { behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element']; } ``` 尝试在下面的示例中拖拽节点和画布,并使用滚轮缩放画布: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 200, data: { nodes: [ { id: 'node-1', style: { x: 50, y: 50 } }, { id: 'node-2', style: { x: 150, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }, node: { type: (datum) => (datum.id === 'node-1' ? 'circle' : 'rect'), style: { fill: 'pink', size: 20, }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }); graph.render(); ``` ### 布局 在上面的示例中,我们手动设置了节点的位置。但当节点数量较多时,这会变得非常困难。 布局算法可以基于一定的规则自动调整节点的位置,G6 提供了多种布局算法,例如树形布局、力导向布局等。 首先生成一组不包括位置信息的数据: ```js const data = { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}` })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }; ``` 默认情况下,如果节点没有位置信息,G6 会将节点放置在左上角,即 `(0, 0)`。 接下来我们使用 `d3-force` 布局算法,它是一种力导向布局算法,可以模拟节点之间的引力和斥力,使得节点自动调整到合适的位置。 ```js { layout: { type: 'd3-force', }, } ``` 查看下面的示例,可以看到节点已经自动调整到合适的位置:
完整代码 ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}` })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }, node: { style: { size: 20, fill: 'pink', }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'd3-force', }, }); graph.render(); ```
```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, data: { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}` })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }, node: { style: { size: 20, fill: 'pink', }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'd3-force', }, }); graph.render(); ``` ### 色板 同样的,当节点数量较多时,手动设置节点的颜色也会变得困难。G6 提供了色板机制,可以便捷地为元素设置颜色。 色板通常会基于数据的某个字段为元素设置颜色,例如节点的类型、边的权重等。 下面我们在数据中的添加 `category` 字段: ```js const data = { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}`, data: { category: i === 0 ? 'central' : 'around' }, })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }; ``` 然后使用 `tableau` 色板为节点设置颜色,`field` 属性指定了数据中的字段,`color` 属性指定了色板的名称。 ```js { node: { palette: { field: 'category', color: 'tableau', } } } ``` > 需要注意将 `node.style` 中的 `fill` 样式移除,因为其优先级高于色板分配的颜色。 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, data: { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}`, data: { category: i === 0 ? 'central' : 'around' }, })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }, node: { style: { size: 20, }, palette: { field: 'category', color: 'tableau', }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'd3-force', }, }); graph.render(); ``` ### 插件 插件机制是 G6 的一个重要特性,可以通过插件扩展 G6 的功能。G6 提供了丰富的内置插件,例如 `tooltip`、`legend` 等,也支持用户自定义插件。 下面我们将使用 `grid-line` 插件为画布添加网格线: ```js { plugins: ['grid-line'], } ``` 可以看到画布已经添加了网格线: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, data: { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}`, data: { category: i === 0 ? 'central' : 'around' }, })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }, node: { style: { size: 20, }, palette: { field: 'category', color: 'tableau', }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'd3-force', }, plugins: ['grid-line'], }); graph.render(); ``` 上面的插件配置项中使用了简写形式,大部分的插件都支持传递额外的参数,例如 `grid-line` 插件可以配置 `follow` 属性来指定拖拽画布时网格线是否跟随画布移动。 ```js { plugins: [{ type: 'grid-line', follow: true }]; } ``` 尝试在下面的示例中拖拽画布,可以看到网格线跟随画布移动: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, data: { nodes: Array.from({ length: 10 }).map((_, i) => ({ id: `node-${i}`, data: { category: i === 0 ? 'central' : 'around' }, })), edges: Array.from({ length: 9 }).map((_, i) => ({ source: `node-0`, target: `node-${i + 1}` })), }, node: { style: { size: 20, }, palette: { field: 'category', color: 'tableau', }, }, edge: { style: { stroke: 'lightgreen', }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'd3-force', }, plugins: [{ type: 'grid-line', follow: true }], }); graph.render(); ``` ## 小结 在本教程中,我们从头开始创建了一个 G6 图表,并了解了 G6 的主要概念。我们学习了如何创建一个简单的图表,如何配置元素的样式和种类,如何添加交互行为,如何使用布局算法,如何使用色板,如何使用插件。 关于 G6 更加详细的概念介绍可以在 [核心概念](/zh/manual/graph/graph/) 中查看。 图的 API 详细说明可以在 [API](/zh/api/graph/) 中查看。 #### 环形布局 Circular - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/CircularLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/CircularLayout.md - Description: 环形布局 Circular --- title: "环形布局 Circular" description: "环形布局 Circular" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/CircularLayout/" version: "5.1.1" --- ## 概述 环形布局是一种把节点均匀或者按间隔放置在圆上的布局,也支持通过配置 startRadius 和 endRadius 为不一样的值实现螺旋状布局。参考更多环形布局[样例](/zh/examples/layout/circular/)或[源码](https://github.com/antvis/layout/blob/v5/packages/layout/src/circular.ts)。 ## 使用场景 **环形布局**: - 适用于平等关系网络、无层级结构的图 **螺旋状布局**: - 适用于隐式层级或时间序列图(如组织架构、传播网络) ## 基本用法 其余均使用默认配置(布局宽高默认是整个画布容器) ```js const graph = new Graph({ // 其他配置 layout: { type: 'circular', }, }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------- | ----------------------------------------------------------------------------------- | --------------------------------------------- | -------------------------------- | ---- | | type | 布局类型 | circular | - | ✓ | | angleRatio | 从第一个节点到最后节点之间相隔多少个 2\*PI | number | 1 | | | center | 布局的中心 | [number, number]\|[number, number, number] | [`布局宽度` / 2, `布局高度` / 2] | | | clockwise | 是否顺时针排列 | boolean | true | | | divisions | 节点在环上的分段数(几个段将均匀分布,在 endRadius - startRadius != 0 时生效) | number | 1 | | | nodeSize | 节点大小(直径)。用于防止节点重叠时的碰撞检测 | Size \| ((nodeData: Node) => Size) | 10 | | | nodeSpacing | 环与环之间最小间距,用于调整半径 | number \| ((nodeData: Node) => number) | 10 | | | ordering | 节点在环上排序的依据,[说明](#ordering) | `topology` \| `topology-directed` \| `degree` | - | | | radius | 圆的半径,设置了则螺旋状布局的配置`startRadius`、`endRadius`不生效,[说明](#radius) | number | - | | | startAngle | 布局的开始角度 | number | 0 | | | endAngle | 布局的结束角度 | number | 2 \* Math.PI | | | startRadius | 螺旋状布局的开始半径,[用法](#螺旋状布局) | number | - | | | endRadius | 螺旋状布局的结束半径 | number | - | | | width | 布局的宽度 | number | 画布宽度 | | | height | 布局的高度 | number | 画布高度 | | ### ordering 节点在环上排序的依据 - `topology`: 按照拓扑排序 - `topology-directed`: 按照拓扑排序(有向图) - `degree`: 按照度数大小排序 不配置(`null`)则直接使用数组中的顺序 ### radius 如果radius、startRadius、endRadius都没配置,则默认为最终计算出来的`Math.min(布局宽度, 布局高度) / 2`,即布满整个布局区域 ## 代码示例 ### 基础环形布局 ```javascript const graph = new Graph({ // 其他配置 layout: { type: 'circular', }, }); ``` ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 螺旋状布局 ```javascript const graph = new Graph({ // 其他配置 layout: { type: 'circular', startRadius: 10, endRadius: 300, }, }); ``` ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', startRadius: 10, endRadius: 300, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` #### 上下文菜单 Contextmenu - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Contextmenu/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Contextmenu.md - Description: 上下文菜单 Contextmenu --- title: "上下文菜单 Contextmenu" description: "上下文菜单 Contextmenu" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Contextmenu/" version: "5.1.1" --- ## 概述 上下文菜单(Contextmenu),也被称为右键菜单,是当用户在某个特定区域上点击后出现的一个菜单。支持在点击前后,触发自定义事件。通过上下文菜单,可以将一些具体元素的操作集成在其中,方便对某一项来进行需要时的单独控制。 ## 使用场景 这一插件主要用于: - 元素的各种交互:查看节点、查看边、删除节点等等交互操作 ## 基本用法 以下是一个简单的 Contextmenu 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'contextmenu', // 只在节点上开启右键菜单,默认全部元素都开启 enable: (e) => e.targetType === 'node', getItems: () => { return [{ name: '查看详情', value: 'detail' }]; }, onClick: (value) => { if (value === 'detail') console.log('展示节点详情'); }, }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------- | ---- | | className | 给菜单的 DOM 追加的类名 | string | `g6-contextmenu` | | | trigger | 如何触发右键菜单:`contextmenu` 表示右键触发,`click` 表示点击触发 | `click` \| `contextmenu` | `contextmenu` | | | offset | 菜单显式 X、Y 方向的偏移量 | [number, number] | [4, 4] | | | onClick | 当菜单被点击后,触发的回调方法,[示例](#onclick) | (value: string, target: HTMLElement, current: Element) => void | - | | | getItems | 返回菜单的项目列表,支持 `Promise` 类型的返回值。是 `getContent` 的快捷配置 | (event: IElementEvent) => [Item](#item)[] \| Promise<[Item](#item)[]> | - | | | getContent | 返回菜单的内容,支持 `Promise` 类型的返回值,也可以使用 `getItems` 进行快捷配置 | (event: IElementEvent) => HTMLElement \| string \| Promise<HTMLElement \| string> | - | | | loadingContent | 当 `getContent` 返回一个 `Promise` 时,使用的菜单内容 | HTMLElement \| string | - | | | enable | 是否可用,通过参数判断是否支持右键菜单,默认是全部可用 | boolean \| (event: IElementEvent) => boolean | true | | ### Item 每个菜单项目 (Item) 包含以下属性: | 属性 | 描述 | 类型 | 必选 | | ----- | ---------------- | -------- | ---- | | name | 菜单项显示的名字 | `string` | ✓ | | value | 菜单项对应的值 | `string` | ✓ | ### onClick 点击菜单项后会触发该函数,函数有三个参数: - value: 对应菜单项的 value - target: 对应菜单项容器的 dom 节点 - current: 对应触发菜单项的元素,例如是节点则可以通过 `current` 来获取到节点的信息(id)等,或者来对元素进行修改 ## 代码示例 ### 基础右键菜单 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, layout: { type: 'grid' }, plugins: [ { type: 'contextmenu', trigger: 'contextmenu', // 'click' or 'contextmenu' onClick: (value, target, current) => { alert('You have clicked the「' + v + '」item'); }, getItems: () => { return [ { name: '查看详情', value: 'detail' }, { name: '删除', value: 'delete' }, ]; }, }, ], }); ``` ### 边的右键菜单 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, layout: { type: 'grid' }, plugins: [ { type: 'contextmenu', trigger: 'contextmenu', getItems: () => { return [{ name: '变更起点', value: 'change' }]; }, onClick: (value) => { if (value === 'change') console.log('这里执行变更起点操作'); }, // 仅在边上开启右键菜单 enable: (e) => e.targetType === 'edge', }, ], }); ``` ### 异步加载菜单项 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, layout: { type: 'grid' }, plugins: [ { type: 'contextmenu', trigger: 'contextmenu', getItems: async () => { // 可以从服务器或其他异步源获取工具栏配置 const response = await fetch('/api/contextmenu-config'); const items = await response.json(); return items; }, // 仅在边上开启右键菜单 enable: (e) => e.targetType === 'node', }, ], }); ``` ### 动态控制菜单项 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, layout: { type: 'grid' }, plugins: [ { type: 'contextmenu', trigger: 'contextmenu', getItems: (e) => { if (e.target.id === 'node-1') { return [ { name: '删除节点', value: 'delete', }, ]; } if (e.target.type === 'edge') { return [ { name: '移动边', value: 'move', }, ]; } return []; }, }, ], }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'contextmenu', trigger: 'contextmenu', // 'click' or 'contextmenu' onClick: (v) => { alert('You have clicked the「' + v + '」item'); }, getItems: () => { return [ { name: '展开一度关系', value: 'spread' }, { name: '查看详情', value: 'detail' }, ]; }, enable: (e) => e.targetType === 'node', }, ], }); graph.render(); ``` #### 色板 - Canonical page: https://g6.antv.antgroup.com/zh/manual/theme/palette/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/theme/palette.md - Description: 色板 --- title: "色板" description: "色板" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/theme/palette/" version: "5.1.1" --- ## 概述 色板(Palette)是指一组预定义的颜色集合,用于帮助用户更方便的选择颜色。在 G6 中,色板是一种常见的配置项,用户可以通过色板来配置节点、边、连线等元素的颜色。 色板分为`离散色板`和`连续色板`两种类型。 离散色板是一组颜色数组,用于将元素中的离散值映射到不同的颜色上,例如节点的类型、边的关系等。下面是一个简单的离散色板示例: ```typescript ['#5B8FF9', '#61DDAA', '#F6BD16', '#F6903D', '#F08BB4']; ``` 连续色板是一个插值器,输入 0~1 的值,返回对应的颜色,用于将元素中的连续值映射到不同的颜色上,例如节点的度数、边的权重等。下面是一个简单的连续色板示例: ```typescript (value: number) => `rgb(${value * 255}, 0, 0)`; ``` ## 注册色板 你可以直接使用内置色板,如果想使用其他色板,需要先进行注册: ```typescript import { register, ExtensionCategory } from '@antv/g6'; import { CustomPalette } from 'package-name/or/path-to-your-custom-palette'; register(ExtensionCategory.PALETTE, 'custom-palette', CustomPalette); ``` :::warning\{title=注意\} 在注册色板过程中并不会区分离散色板和连续色板,使用色板过程中需要自行保证色板类型和数据类型的一致性。 ::: ### 内置色板 目前 G6 内置了 5 套常用的离散色板,用户可以直接使用: - spectral - tableau - oranges - greens - blues ## 配置色板 目前开放色板配置的地方主要以元素为主,以节点为例: ### 离散色板 1. 默认配置,直接配置 `palette` 的值为色板名,会默认为每个节点分配不同的颜色 ```typescript { node: { palette: 'spectral', // spectral 为色板名 } } ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 100, data: { nodes: new Array(30).fill(0).map((_, i) => ({ id: `node-${i}` })), }, layout: { type: 'grid', cols: 10, rows: 3 }, node: { palette: 'spectral', }, }); graph.render(); ``` > 当元素数量超过色板颜色数量时,会循环使用色板中的颜色 2. 标准配置,离散色板配置属性包括:`type: 'group'`,`field`,`color`,`invert` 其中 `type: 'group'` 显式指定了当前色板类型为离散色板;`field` 指定元素数据中的分组字段;`color` 为色板名;`invert` 为是否反转色板。 给定一组示例数据: ```json { "nodes": [ { "id": "node-1", "data": { "category": "A" } }, { "id": "node-2", "data": { "category": "B" } }, { "id": "node-3", "data": { "category": "C" } }, { "id": "node-4", "data": { "category": "A" } }, { "id": "node-5", "data": { "category": "B" } }, { "id": "node-6", "data": { "category": "C" } } ] } ``` 数据中 `node-1`,`node-4` 属于 A 类别,`node-2`,`node-5` 属于 B 类别,`node-3`,`node-6` 属于 C 类别。 通过以下方式配置节点的颜色,使得同类别的节点颜色相同: ```typescript { node: { palette: { type: 'group', // 指定色板类型为分类色板 field: 'category', // 指定数据中的分组字段 color: 'tableau', // 使用 tableau 色板 } } } ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 50, data: { nodes: new Array(6).fill(0).map((_, i) => ({ id: `node-${i}`, data: { category: ['A', 'B', 'C'][i % 3] } })), }, layout: { type: 'grid', cols: 6 }, node: { palette: { type: 'group', field: 'category', color: 'tableau', }, }, }); graph.render(); ``` ### 连续色板 连续色板只支持标准方式配置,配置属性包括:`type: 'value'`,`field`,`color`,`invert`。 给定一组示例数据: ```json { "nodes": [ { "id": "node-1", "data": { "value": 0 } }, { "id": "node-2", "data": { "value": 20 } }, { "id": "node-3", "data": { "value": 40 } }, { "id": "node-4", "data": { "value": 60 } }, { "id": "node-5", "data": { "value": 80 } }, { "id": "node-6", "data": { "value": 100 } } ] } ``` 现在创建一个插值器,将最大值映射为红色(`rgb(255, 0, 0)`),最小值映射为黑色(`rgb(0, 0, 0)`): ```typescript (value) => `rgb(${value * 255}, 0, 0)`; ``` 通过以下配置使得节点的颜色根据数据中的 `value` 字段的值映射到不同的颜色: ```typescript { node: { palette: { type: 'value', // 指定色板类型为连续色板 field: 'value', // 指定数据中的数值字段 color: (value) => `rgb(${value * 255}, 0, 0)`, // 使用插值器 } } } ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 50, data: { nodes: new Array(6).fill(0).map((_, i) => ({ id: `node-${i}`, data: { value: (i + 1) * 20 } })), }, layout: { type: 'grid', cols: 6 }, node: { palette: { type: 'value', field: 'value', color: (value) => `rgb(${value * 255}, 0, 0)`, }, }, }); graph.render(); ``` :::warning\{title=注意\} 内置连续色板不支持指定值域范围,如果有更复杂的颜色映射需求,可以在样式映射中自定义 ::: ## 自定义色板 如果内置色板无法满足需求,可以自定义色板,具体请参考[自定义色板](/zh/manual/theme/custom-palette/)。 ## 优先级 色板会基于元素类型生成样式,对于节点和组合,会将颜色映射到 `fill` 属性;对于边,会将颜色映射到 `stroke` 属性。 如果同时配置了色板和样式映射,样式映射会覆盖色板颜色。下面的例子中,节点的颜色始终为红色: ```typescript { node: { style: { fill: 'red', }, palette: 'spectral', } } ``` #### 平行边 ProcessParallelEdges - Canonical page: https://g6.antv.antgroup.com/zh/manual/transform/ProcessParallelEdges/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/transform/ProcessParallelEdges.md - Description: 平行边 ProcessParallelEdges --- title: "平行边 ProcessParallelEdges" description: "平行边 ProcessParallelEdges" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/transform/ProcessParallelEdges/" version: "5.1.1" --- ## 概述 平行边(Parallel Edges)是指在图结构中,两个节点之间存在多条边。这些边共享相同的源节点和目标节点,但可能代表不同的关系或属性。为了避免边的重叠和混淆,提供了两种处理平行边的方式: - 捆绑模式(bundle):将平行边捆绑在一起,通过改变曲率与其他边分开 - 合并模式(merge):将平行边合并为一条聚合 ## 使用场景 下面为常见使用场景举例: - 双向数据流,比如客户端发送请求,服务端返回响应 - 多依赖关系,即一个节点通过多种方式依赖另一个节点,比如微服务架构中,服务 A 调用服务 B的两个不同 API - 多链路,比如高可用架构中,主链路(实线,状态正常)与备份链路(灰色虚线,状态待机)同时展示 ## 基本用法 **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... transforms: ['process-parallel-edges'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... transforms: [ { type: 'process-parallel-edges', key: 'process-parallel-edges', mode: 'bundle', // 默认就是捆绑模式了 distance: 30, // 配置捆绑模式下边之间的距离为30 }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------- | -------------------------------------------------- | --------------------------------------------------------------------------------------- | ----------------------- | ---- | | type | 数据处理类型 | process-parallel-edges | - | ✓ | | distance | 边之间的距离,仅在捆绑模式下有效 | number | 15 | | | edges | 考虑要处理的边,默认为全部边 | string[] | - | | | mode | 处理模式,[配置项](#mode) | `'bundle'` | `'merge'` \| `'bundle'` | | | style | 合并边的样式,仅在合并模式下有效,[配置项](#style) | PathStyleProps \| ((prev: [EdgeData](/zh/manual/data/#边数据edgedata)[]) => PathStyleProps) | - | | ### mode 提供了两种处理模式: - `'merge'`: 将平行边合并为一条边,适用于不需要区分平行边的情况,[示例](#合并模式) `merge` 使用的是内置的直线( [`line`](/zh/manual/element/edge/Line/) )来展示合并边。 - `'bundle'`: 每条边都会与其他所有平行边捆绑在一起,并通过改变曲率与其他边分开。如果一组平行边的数量是奇数,那么中心的边将被绘制为直线,其他的边将被绘制为曲线,[示例](#捆绑模式) `bundle` 使用的是内置的二次贝塞尔曲线( [`quadratic`](/zh/manual/element/edge/Quadratic/) )来实现,数据处理过程会强制把每个 `edgeDatum.type` 改为 `quadratic`,并计算每条线的曲率。 :::warning\{title=注意\} 禁止在创建 Graph 实例时配置 `edge.type` 即默认的边类型,因为它的优先级比 `edgeDatum.type` 要高,会导致 `bundle` 模式的处理无法生效。 ::: ### style 合并边的样式,仅在合并模式下有效 #### PathStyleProps 下表列出了常用的属性,更多属性请参考 [PathStyleProps](https://g.antv.antgroup.com/api/basic/path#pathstyleprops)。 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ------------------------- | ----------------------------- | --------- | ---- | | fill | 填充色 | string | `#1783FF` | | fillOpacity | 填充色透明度 | number \| string | 1 | | lineCap | 描边端点样式 | `round` \| `square` \| `butt` | `butt` | | lineDash | 描边虚线样式 | number[] | - | | lineDashOffset | 描边虚线偏移量 | number | - | | lineJoin | 描边连接处样式 | `round` \| `bevel` \| `miter` | `miter` | | lineWidth | 描边宽度 | number | 1 | | opacity | 透明度 | number \| string | 1 | | shadowBlur | 阴影模糊度 | number | - | | shadowColor | 阴影颜色 | string | - | | shadowOffsetX | 阴影在 x 轴方向上的偏移量 | number \| string | - | | shadowOffsetY | 阴影在 y 轴方向上的偏移量 | number \| string | - | | shadowType | 阴影类型 | `inner` \| `outer` | `outer` | | stroke | 描边色 | string | `#000` | | strokeOpacity | 描边色透明度 | number \| string | 1 | | visibility | 图形是否可见 | `visible` \| `hidden` | `visible` | ## 代码示例 ### 捆绑模式 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'A', style: { x: 50, y: 350 } }, { id: 'B', style: { x: 250, y: 150 } }, { id: 'C', style: { x: 450, y: 350 } }, ], edges: [ { source: 'A', target: 'C' }, { source: 'C', target: 'A' }, ...Array.from({ length: 10 }).map((_, i) => ({ id: `edge:A-B${i}`, source: 'A', target: 'B', data: { label: `A->B:${i}`, }, })), ...Array.from({ length: 5 }).map((_, i) => ({ id: `edge:B-C${i}`, source: 'B', target: 'C', data: { label: `B->C:${i}`, }, })), ], }; const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { ports: [{ placement: 'center' }], labelText: (d) => d.id, }, }, edge: { style: { labelText: (d) => d?.data?.label || `${d.source}->${d.target}`, }, }, behaviors: ['drag-element'], transforms: ['process-parallel-edges'], }); graph.render(); ``` ### 合并模式 下面是一个简单的合并模式的例子,需要注意: - 不需要合并(即两个节点间只有一条边)的边,合并样式不会在这条边上生效,比如例子中的 **A->C** - 合并样式实际上是赋值给 `datum.style` ,也就是优先级会比实例化 Graph 时配置的默认样式低( `edge.style` ),所以例子中合并样式的 `startArrow` 没有生效 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'A', style: { x: 50, y: 350 } }, { id: 'B', style: { x: 250, y: 150 } }, { id: 'C', style: { x: 450, y: 350 } }, ], edges: [ { source: 'A', target: 'B' }, { source: 'B', target: 'A' }, { id: 'B-C:1', source: 'B', target: 'C' }, { id: 'B-C:2', source: 'B', target: 'C' }, { source: 'A', target: 'C' }, ], }; const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelText: (d) => d.id, }, }, edge: { style: { labelText: (d) => d?.data?.label || `${d.source}->${d.target}`, startArrow: false, }, }, transforms: [ { type: 'process-parallel-edges', mode: 'merge', style: { halo: true, haloOpacity: 0.2, haloStroke: 'red', startArrow: true, }, }, ], }); graph.render(); ``` #### 展开/收起元素 CollapseExpand - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/CollapseExpand/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/CollapseExpand.md - Description: 展开/收起元素 CollapseExpand --- title: "展开/收起元素 CollapseExpand" description: "展开/收起元素 CollapseExpand" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/CollapseExpand/" version: "5.1.1" --- ## 概述 CollapseExpand 是 G6 中用于实现节点或组合(Combo)展开/收起功能的内置交互。通过双击(默认)或单击操作,用户可以灵活控制图元素的展开与收起状态,有效管理图结构的可视化层次,降低视觉复杂度。 ## 使用场景 这一交互主要用于: - 管理大型层次结构图,实现树状图或网络图的分层浏览 - 简化复杂图的展示,按需展开关注区域 - 隐藏暂时不需要查看的分支节点,聚焦于重要信息 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } }, ], edges: [], combos: [ { id: 'combo1', combo: 'combo2' }, { id: 'combo2', style: {} }, ], }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, behaviors: [ { type: 'collapse-expand', key: 'collapse-expand', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { const options = { key: 'collapse-expand', type: 'collapse-expand', animation: true, enable: true, }; const optionFolder = gui.addFolder('CollapseExpand Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'collapse-expand', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一 behavior: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['collapse-expand'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'collapse-expand', key: 'collapse-expand-1', trigger: 'click', // 修改触发方式为单击 animation: true, // 启用动画效果 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ---------- | ------------------------------ | ------------------------------------------------------------------------- | ----------------- | ---- | | type | 交互类型名称 | `collapse-expand` \| string | `collapse-expand` | ✓ | | animation | 是否启用展开/收起动画效果 | boolean | true | | | enable | 是否启用展开/收起功能 | boolean \| ((event: [IPointerEvent](/zh/api/event/#事件对象属性)) => boolean) | true | | | trigger | 触发方式,可选单击或双击 | `click` \| `dblclick` | `dblclick` | | | onCollapse | 完成收起时的回调函数 | (id: string) => void | - | | | onExpand | 完成展开时的回调函数 | (id: string) => void | - | | | align | 是否对准目标元素,避免视图偏移 | boolean | true | | ## 代码示例 ### 基础展开/收起功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['collapse-expand'], // 其他配置... }); ``` ### 使用单击触发展开/收起 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'collapse-expand', trigger: 'click', // 将默认的双击触发改为单击触发 }, ], }); ``` ### 自定义展开/收起回调 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'collapse-expand', onCollapse: (id) => { console.log(`节点 ${id} 已收起`); // 执行自定义逻辑 }, onExpand: (id) => { console.log(`节点 ${id} 已展开`); // 执行自定义逻辑 }, }, ], }); ``` ### 条件性启用展开/收起功能 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'collapse-expand', // 只有当目标是节点类型时才启用展开/收起功能 enable: (event) => event.targetType === 'node', }, ], }); ``` ### 关闭动画效果 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'collapse-expand', animation: false, // 关闭展开/收起动画效果 }, ], }); ``` ## 常见问题 ### 1. 如何判断一个节点是否处于收起状态? 可以通过检查节点数据中的 `collapsed` 属性: ```javascript const isCollapsed = (nodeId) => { const nodeData = graph.getNodeData(nodeId); return nodeData?.style?.collapsed === true; }; ``` ### 2. 如何以编程方式展开或收起节点? 除了通过用户交互触发,你还可以使用 [collapseElement](/zh/api/element/#graphcollapseelementid-options) 或 [expandElement](/zh/api/element/#graphexpandelementid-options) 直接控制: ```javascript // 收起节点 graph.collapseElement('nodeId', { animation: true }); // 展开节点 graph.expandElement('nodeId', { animation: true }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 300, y: 100 } }, { id: 'node2', combo: 'combo1', style: { x: 300, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 100, y: 100 } }, { id: 'node4', combo: 'combo2', style: { x: 50, y: 150 } }, { id: 'node5', combo: 'combo2', style: { x: 150, y: 150 } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node3', target: 'node4' }, { source: 'node3', target: 'node5' }, ], combos: [ { id: 'combo1', style: { labelText: '双击折叠', collapsed: true } }, { id: 'combo2', style: { labelText: '单击折叠', collapsed: false } }, ], }, behaviors: [ { type: 'collapse-expand', trigger: 'dblclick', enable: (event) => event.targetType === 'combo' && event.target.id === 'combo1', }, { type: 'collapse-expand', trigger: 'click', enable: (event) => event.targetType === 'combo' && event.target.id === 'combo2', }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 数据 Data - Canonical page: https://g6.antv.antgroup.com/zh/manual/data/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/data.md - Description: 数据 Data --- title: "数据 Data" description: "数据 Data" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/data/" version: "5.1.1" --- ## 概述 G6 是一款数据驱动的图可视化引擎,数据是 G6 中最重要的概念之一。 G6 使用标准的 JSON 格式描述图数据结构。以下是一个基础的图数据示例: ```javascript {4-7} import { Graph } from '@antv/g6'; const graph = new Graph({ data: { nodes: [{ id: 'node1' }, { id: 'node2' }], edges: [{ source: 'node1', target: 'node2' }], }, }); ``` ## 数据结构 图数据包含三部分:`nodes`(节点数据)、`edges`(边数据)、`combos`(组合数据)。每一部分对应图中的不同元素,它们的类型和数据决定了图如何展示。 ### 图数据(GraphData) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------- | --------------------------------- | ------ | ---- | | nodes | 节点数据 | [NodeData](#节点数据nodedata)[] | - | | | edges | 边数据 | [EdgeData](#边数据edgedata)[] | - | | | combos | 组合数据 | [ComboData](#组合数据combodata)[] | - | | ### 节点数据(NodeData) 节点是图中的基本构成单元,它代表图中的实体。每个节点都有一个唯一的 `id`,用于标识节点,同时节点也可以有数据、样式和状态。 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------- | -------------------------------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 节点的唯一标识符,用于区分不同的节点 | string | - | ✓ | | type | 节点类型,内置节点类型名称或者自定义节点的名称 | string | - | | | data | 节点数据,用于存储节点的自定义数据,例如节点的名称、描述等。可以在样式映射中通过回调函数获取 | object | - | | | style | 节点样式,包括位置、大小、颜色等视觉属性 | object | - | | | states | 节点初始状态,如选中、激活、悬停等 | string[] | - | | | combo | 所属的组合 ID,用于组织节点的层级关系,如果没有则为 null | string \| null | - | | | children | 子节点 ID 集合,仅在树图场景下使用 | string[] | - | | **示例:** ```json { "id": "node-1", "type": "circle", "data": { "name": "alice", "role": "Admin" }, "style": { "x": 100, "y": 200, "size": 32, "fill": "violet" }, "states": ["selected"], "combo": null } ``` ### 边数据(EdgeData) 边是连接节点的元素,表示节点之间的关系。每条边都与两个节点(起始节点和目标节点)关联,并且边本身可以有数据、样式和状态。边的数据常用于表示节点之间的逻辑或关系,如社交网络中的用户关系、流程图中的步骤流转等。 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | ---------------------------------------------------------------- | -------- | ------ | ---- | | source | 边起始节点 ID | string | - | ✓ | | target | 边目标节点 ID | string | - | ✓ | | id | 边的唯一标识符 | string | - | | | type | 边类型,内置边类型名称或者自定义边的名称 | string | - | | | data | 边数据,用于存储边的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 边样式,包括线条颜色、宽度、箭头等视觉属性 | object | - | | | states | 边初始状态 | string[] | - | | **示例:** ```json { "source": "alice", "target": "bob", "type": "line", "data": { "relationship": "friend", "strength": 5 }, "style": { "stroke": "green", "lineWidth": 2 }, "states": ["hover"] } ``` ### 组合数据(ComboData) 通过组合,可以为多个节点创建一个逻辑单元,用于图形的分层、分组或其他结构化需求。组合可以包含子节点或其他组合,从而形成嵌套层次。 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | -------------------------------------------------------------------- | -------------- | ------ | ---- | | id | 组合的唯一标识符 | string | - | ✓ | | type | 组合类型,内置组合类型名称或者自定义组合名称 | string | - | | | data | 组合数据,用于存储组合的自定义数据,可以在样式映射中通过回调函数获取 | object | - | | | style | 组合样式 | object | - | | | states | 组合初始状态 | string[] | - | | | combo | 组合的父组合 ID。如果没有父组合,则为 null | string \| null | - | | **示例:** ```json { "id": "combo1", "type": "circle", "data": { "groupName": "Group A" }, "style": { "fill": "lightblue", "stroke": "blue", "collapsed": true }, "states": [], "combo": null } ``` ## 数据操作 G6 提供了丰富的 API 来操作图数据,下面展示一些常见的数据操作示例。 ### 数据初始化 在创建图实例时,可以直接传入数据: ```javascript const graph = new Graph({ data: { nodes: [ { id: 'node1', data: { label: '节点1' } }, { id: 'node2', data: { label: '节点2' } }, ], edges: [{ source: 'node1', target: 'node2', data: { label: '关系' } }], }, }); ``` 或者通过 `setData` 方法设置数据: ```javascript graph.setData({ nodes: [ { id: 'node3', data: { label: '节点3' } }, { id: 'node4', data: { label: '节点4' } }, ], edges: [{ source: 'node3', target: 'node4', data: { label: '新关系' } }], }); ``` ### 数据增删改查 #### 添加节点和边 ```javascript // 添加单个节点 graph.addNodeData([ { id: 'node5', data: { label: '新节点', category: 'person', }, style: { fill: '#6395F9', stroke: '#5B8FF9', }, }, ]); // 批量添加多个节点 graph.addNodeData([ { id: 'node6', data: { label: '批量节点1' } }, { id: 'node7', data: { label: '批量节点2' } }, ]); // 添加连接新节点的边 graph.addEdgeData([ { source: 'node1', target: 'node5', data: { label: '连接到新节点', weight: 2, }, style: { stroke: '#F6BD16', lineWidth: 3, }, }, ]); ``` #### 更新数据 ```javascript // 更新单个节点 graph.updateNodeData([ { id: 'node1', data: { label: '已更新的节点1', status: 'updated', }, style: { fill: '#F6BD16', stroke: '#EBEBEB', lineWidth: 2, }, }, ]); // 更新多个节点 graph.updateNodeData([ { id: 'node2', style: { size: 40, fill: '#5AD8A6' }, }, { id: 'node3', data: { importance: 'high' }, }, ]); // 更新边 graph.updateEdgeData([ { source: 'node1', target: 'node2', style: { stroke: '#5B8FF9', lineWidth: 2, lineDash: [5, 5], }, }, ]); ``` #### 删除数据 ```javascript // 删除单个节点(以及与该节点相连的所有边) graph.removeNodeData(['node7']); // 删除多个节点 graph.removeNodeData(['node5', 'node6']); // 删除边 graph.removeEdgeData(['node1-node2']); ``` #### 查询数据 ```javascript // 获取所有节点数据 const nodes = graph.getNodeData(); // 获取所有边数据 const edges = graph.getEdgeData(); // 获取特定节点数据 const node1 = graph.getNodeData('node1'); // 获取特定边数据 const edge1 = graph.getEdgeData('node1-node2'); ``` ### 复杂数据结构操作 #### 嵌套组合(Combo) 下面是创建和操作嵌套组合的示例: ```javascript import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', data: { label: '节点1' }, combo: 'combo1' }, { id: 'node2', data: { label: '节点2' }, combo: 'combo1' }, { id: 'node3', data: { label: '节点3' }, combo: 'combo2' }, { id: 'node4', data: { label: '节点4' }, combo: 'combo2' }, { id: 'node5', data: { label: '节点5' }, combo: 'combo3' }, ], edges: [ { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node4' }, { source: 'node4', target: 'node5' }, ], combos: [ { id: 'combo1', data: { label: '组1' } }, { id: 'combo2', data: { label: '组2' } }, { id: 'combo3', data: { label: '组3' }, combo: 'combo1' }, // 嵌套组合 ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'force', }, }); // 添加新的组合 graph.addComboData([ { id: 'combo4', data: { label: '新组' }, combo: 'combo2', // 添加到现有组合中 }, ]); // 将节点移动到不同的组合 graph.updateNodeData([ { id: 'node5', combo: 'combo4', // 将节点5移动到新组合 }, ]); // 展开/折叠组合 graph.updateComboData([ { id: 'combo1', style: { collapsed: true }, // 折叠组合1 }, ]); graph.render(); ``` #### 树形结构数据 对于树形结构,G6 支持使用 `children` 属性表示层次关系: ```javascript // 树形结构数据 import { Graph, treeToGraphData } from '@antv/g6'; const treeData = { id: 'root', children: [ { id: 'child1', children: [{ id: 'grandchild1' }], }, { id: 'child2', children: [{ id: 'grandchild2' }], }, ], }; const data = treeToGraphData(treeData); const graph = new Graph({ container: 'container', data, layout: { type: 'dendrogram', // 或 'compactBox', 'mindmap' 等树布局 direction: 'TB', // 从上到下布局 nodeSep: 50, // 节点间距 rankSep: 100, // 层级间距 }, }); graph.render(); ``` 通过 `treeToGraphData` 方法,可以将树形结构数据转换为 G6 的标准数据结构,实际传入到 `data` 中的数据结构如下: ```json { "nodes": [ { "id": "root", "depth": 0, "children": ["child1", "child2"] }, { "id": "child1", "depth": 1, "children": ["grandchild1"] }, { "id": "grandchild1", "depth": 2 }, { "id": "child2", "depth": 1, "children": ["grandchild2"] }, { "id": "grandchild2", "depth": 2 } ], "edges": [ { "source": "root", "target": "child1" }, { "source": "root", "target": "child2" }, { "source": "child1", "target": "grandchild1" }, { "source": "child2", "target": "grandchild2" } ] } ``` ## 数据组织与最佳实践 为了确保图的正确渲染和交互,建议按照 G6 标准数据结构组织数据。每个元素(节点、边、组合)应包含一个 `data` 字段,用于存放业务数据和自定义属性。 - **避免使用与 G6 内部字段名称相同的标识符**,如 `id`、`type`、`style` 等,防止发生命名冲突。 - 将业务数据(如用户信息、社交网络关系等)存储在 `data` 字段中,这样可以确保数据的灵活性和可扩展性。 - **使用样式映射**来根据业务数据动态设置视觉属性,而不是直接修改样式对象。 ### 数据与样式分离 良好的做法是将数据和样式分离,通过映射函数将数据属性转换为视觉属性: ```javascript import { Graph } from '@antv/g6'; // 使用数据驱动样式 const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node1', data: { value: 10, category: 'A' } }, { id: 'node2', data: { value: 5, category: 'B' } }, ], }, node: { style: { // 根据数据中的 value 字段动态设置节点大小 size: (node) => 20 + node.data.value * 2, // 根据数据中的 category 字段设置不同颜色 fill: (node) => { const categoryColors = { A: '#F6BD16', B: '#5B8FF9' }; return categoryColors[node.data.category] || '#CCC'; }, }, }, }); ``` ## API G6 提供了一系列的 API 来访问和操作数据,包括: - [getData](/zh/api/data/#graphgetdata) - [setData](/zh/api/data/#graphsetdata) - [getNodeData](/zh/api/data/#graphgetnodedata) - [getEdgeData](/zh/api/data/#graphgetedgedata) - [getComboData](/zh/api/data/#graphgetcombodata) - [addData](/zh/api/data/#graphadddata) - [addNodeData](/zh/api/data/#graphaddnodedata) - [addEdgeData](/zh/api/data/#graphaddedgedata) - [addComboData](/zh/api/data/#graphaddcombodata) - [updateData](/zh/api/data/#graphupdatedata) - [updateNodeData](/zh/api/data/#graphupdatenodedata) - [updateEdgeData](/zh/api/data/#graphupdateedgedata) - [updateComboData](/zh/api/data/#graphupdatecombodata) - [removeData](/zh/api/data/#graphremovedata) - [removeNodeData](/zh/api/data/#graphremovenodedata) - [removeEdgeData](/zh/api/data/#graphremoveedgedata) - [removeComboData](/zh/api/data/#graphremovecombodata) 通过不同的 API,你可以方便地访问和操作图数据,实现图的增删改查等操作。 ## 使用远程数据 G6 并不提供数据的获取和解析功能,对于本地 JSON 数据,你可以直接引入使用: ```typescript import data from './path/to/data.json' assert { type: 'json' }; ``` 对于远程数据,你可以使用 `fetch` 或者其他网络请求库来获取数据: ```typescript fetch('https://path/to/data.json') .then((res) => res.json()) .then((data) => { // 使用 data const graph = new Graph({ container: 'container', data, }); // 触发布局和渲染 graph.render(); }) .catch((error) => { console.error('加载数据失败:', error); }); ``` #### 自定义 Combo - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/combo/custom-combo/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/combo/custom-combo.md - Description: 自定义 Combo --- title: "自定义 Combo" description: "自定义 Combo" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/combo/custom-combo/" version: "5.1.1" --- G6 提供了两种 [内置组合](/zh/manual/element/combo/BaseCombo/) 类型:圆形组合和矩形 Combo 。但在复杂的业务场景中,你可能需要创建具有特定样式、交互效果或行为逻辑的自定义 Combo 。 ## 开始之前:了解 Combo 的基本构成 在 G6 中,一个完整的 Combo 通常由以下几个部分组成: - `key` : Combo 的主图形,表示 Combo 的主要形状,如圆形、矩形等; - `label` :文本标签,通常用于展示 Combo 的名称或描述; - `halo` :主图形周围展示的光晕效果的图形; ### Combo 的特殊性 Combo 不同于普通节点,它具有以下特性: 1. **包含性**: Combo 可以包含节点和其他 Combo ,形成层级结构 2. **两种状态**:展开(Expanded)和收起(Collapsed)状态 3. **自适应大小**:根据内部元素动态调整大小 4. **拖拽行为**:支持整体拖拽及内部元素拖入/拖出 ## 自定义 Combo 的方式 **选择合适的方式** 创建自定义 Combo 的方式有两种途径: ### 1. 继承现有 Combo 类型 **推荐** 这是最常用的方式,你可以选择继承以下类型之一: - [`BaseCombo`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/combos/base-combo.ts) - 最基础的 Combo 类,提供 Combo 的核心功能 - [`Circle`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/combos/circle.ts) - 圆形 Combo - [`Rect`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/combos/rect.ts) - 矩形 Combo **为什么选择这种方式?** - 📌 **代码量少**:复用现有 Combo 的属性和方法,只需专注于新增功能 - 📌 **开发迅速**:适合大多数项目需求,快速实现业务目标 - 📌 **易于维护**:代码结构清晰,继承关系明确 :::tip\{title=立即开始\} 如果你选择继承现有组合类型(推荐),可以直接跳到 [三步创建你的第一个自定义 Combo](#三步创建你的第一个自定义-combo) 开始实践。大部分用户都会选择这种方式! ::: ### 2. 基于 G 图形系统从零开发 **高级用法** 如果现有 Combo 类型都不满足需求,你可以基于 G 的底层图形系统从零创建 Combo。 **为什么选择这种方式?** - 📌 **最大自由度**:完全控制 Combo 的每个细节,实现任意复杂效果 - 📌 **特殊需求**:现有 Combo 类型无法满足的高度定制场景 - 📌 **性能优化**:针对特定场景的性能优化 :::warning\{title=注意事项\} 从零开发的自定义 Combo 需要自行处理所有细节,包括图形绘制、事件响应、状态变化、展开/收起逻辑等,开发难度较大。这里可以直接参考 [源码](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/combos/base-combo.ts) 进行实现。 ::: ## 三步创建你的第一个自定义 Combo 让我们从继承 `BaseCombo` 开始,实现一个自定义六边形 Combo : ```ts import { Graph, register, BaseCombo, ExtensionCategory } from '@antv/g6'; // 定义收起状态的按钮路径 const collapse = (x, y, r) => { return [ ['M', x - r, y], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0], ['M', x - r + 4, y], ['L', x + r - 4, y], ]; }; // 定义展开状态的按钮路径 const expand = (x, y, r) => { return [ ['M', x - r, y], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0], ['M', x - r + 4, y], ['L', x - r + 2 * r - 4, y], ['M', x - r + r, y - r + 4], ['L', x, y + r - 4], ]; }; class HexagonCombo extends BaseCombo { // 获取六边形的路径 getKeyPath(attributes) { const [width, height] = this.getKeySize(attributes); const padding = 10; const size = Math.min(width, height) + padding; // 计算六边形的顶点 const points = []; for (let i = 0; i < 6; i++) { const angle = (Math.PI / 3) * i; const x = (size / 2) * Math.cos(angle); const y = (size / 2) * Math.sin(angle); points.push([x, y]); } // 构建SVG路径 const path = [['M', points[0][0], points[0][1]]]; for (let i = 1; i < 6; i++) { path.push(['L', points[i][0], points[i][1]]); } path.push(['Z']); return path; } // 获取主图形样式 getKeyStyle(attributes) { const style = super.getKeyStyle(attributes); return { ...style, d: this.getKeyPath(attributes), fill: attributes.collapsed ? '#FF9900' : '#F04864', fillOpacity: attributes.collapsed ? 0.5 : 0.2, stroke: '#54BECC', lineWidth: 2, }; } // 绘制主图形 drawKeyShape(attributes, container) { return this.upsert('key', 'path', this.getKeyStyle(attributes), container); } // 绘制展开/收起按钮,使用路径实现更精细的控制 drawCollapseButton(attributes) { const { collapsed } = attributes; const [width] = this.getKeySize(attributes); const btnR = 8; const x = width / 2 + btnR; const d = collapsed ? expand(x, 0, btnR) : collapse(x, 0, btnR); // 创建点击区域和按钮图形 const hitArea = this.upsert('hit-area', 'circle', { cx: x, r: 8, fill: '#fff', cursor: 'pointer' }, this); this.upsert('button', 'path', { stroke: '#54BECC', d, cursor: 'pointer', lineWidth: 1.4 }, hitArea); } // 重写render方法,添加更多自定义图形 render(attributes, container) { super.render(attributes, container); this.drawCollapseButton(attributes, container); } // 使用生命周期钩子添加事件监听 onCreate() { this.shapeMap['hit-area'].addEventListener('click', () => { const id = this.id; const collapsed = !this.attributes.collapsed; const { graph } = this.context; if (collapsed) graph.collapseElement(id); else graph.expandElement(id); }); } } // 注册自定义 Combo register(ExtensionCategory.COMBO, 'hexagon-combo', HexagonCombo); // 创建图实例并使用自定义 Combo const graph = new Graph({ container: 'container', height: 250, data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 100, y: 100 } }, { id: 'node2', combo: 'combo1', style: { x: 150, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 300, y: 100 } }, { id: 'node4', combo: 'combo2', style: { x: 350, y: 150 } }, ], combos: [ { id: 'combo1', data: { label: 'Hexagon 1' } }, { id: 'combo2', data: { label: 'Hexagon 2' }, style: { collapsed: true } }, ], }, node: { style: { fill: '#91d5ff', stroke: '#1890ff', lineWidth: 1, }, }, combo: { type: 'hexagon-combo', style: { padding: 20, showCollapseButton: true, labelText: (d) => d.data?.label, labelPlacement: 'top', }, }, behaviors: ['drag-element'], }); graph.render(); ``` ### 第一步:编写自定义 Combo 类 ```typescript import { BaseCombo } from '@antv/g6'; import type { BaseComboStyleProps } from '@antv/g6'; // 定义按钮路径生成函数 const collapse = (x, y, r) => { return [ ['M', x - r, y], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0], ['M', x - r + 4, y], ['L', x + r - 4, y], ]; }; const expand = (x, y, r) => { return [ ['M', x - r, y], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0], ['M', x - r + 4, y], ['L', x - r + 2 * r - 4, y], ['M', x - r + r, y - r + 4], ['L', x, y + r - 4], ]; }; class HexagonCombo extends BaseCombo { // 获取六边形的路径 protected getKeyPath(attributes: Required) { const [width, height] = this.getKeySize(attributes); const padding = 10; const size = Math.min(width, height) + padding; // 计算六边形的顶点 const points = []; for (let i = 0; i < 6; i++) { const angle = (Math.PI / 3) * i; const x = (size / 2) * Math.cos(angle); const y = (size / 2) * Math.sin(angle); points.push([x, y]); } // 构建 SVG 路径 const path = [['M', points[0][0], points[0][1]]]; for (let i = 1; i < 6; i++) { path.push(['L', points[i][0], points[i][1]]); } path.push(['Z']); return path; } // 获取主图形样式,直接使用路径数据 protected getKeyStyle(attributes: Required) { const style = super.getKeyStyle(attributes); return { ...style, d: this.getKeyPath(attributes), fill: attributes.collapsed ? '#FF9900' : '#F04864', fillOpacity: attributes.collapsed ? 0.5 : 0.2, stroke: '#54BECC', lineWidth: 2, }; } // 绘制主图形,使用 path 类型直接传入样式对象 protected drawKeyShape(attributes: Required, container: Group) { return this.upsert('key', 'path', this.getKeyStyle(attributes), container); } // 绘制收起/展开按钮,使用 SVG 路径实现更精细的控制 protected drawCollapseButton(attributes: Required) { const { collapsed } = attributes; const [width] = this.getKeySize(attributes); const btnR = 8; const x = width / 2 + btnR; const d = collapsed ? expand(x, 0, btnR) : collapse(x, 0, btnR); // 创建点击区域和按钮图形 const hitArea = this.upsert('hit-area', 'circle', { cx: x, r: 8, fill: '#fff', cursor: 'pointer' }, this); this.upsert('button', 'path', { stroke: '#54BECC', d, cursor: 'pointer', lineWidth: 1.4 }, hitArea); } // 使用生命周期钩子方法绑定事件 onCreate() { this.shapeMap['hit-area'].addEventListener('click', () => { const id = this.id; const collapsed = !this.attributes.collapsed; const { graph } = this.context; if (collapsed) graph.collapseElement(id); else graph.expandElement(id); }); } } ``` ### 第二步:注册自定义 Combo ```js import { ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.COMBO, 'hexagon-combo', HexagonCombo); ``` ### 第三步:应用自定义 Combo ```js const graph = new Graph({ // ...其他配置 combo: { type: 'hexagon-combo', // 使用注册时的名称 style: { padding: 20, showCollapseButton: true, labelText: (d) => d.data?.label, labelPlacement: 'top', }, }, // 由于我们自己实现了折叠展开功能,这里只需要拖拽行为 behaviors: ['drag-element'], }); ``` 🎉 恭喜!你已经创建了第一个自定义 Combo 。 ## 更进一步:理解 Combo 绘制的原理 ### Combo 与节点的区别 虽然 Combo 继承自 `BaseNode`,但有一些关键区别: 1. **自适应大小**: Combo 会根据内部元素自动计算合适的大小 2. **展开/收起状态**: Combo 有两种显示状态,并需要处理状态切换 3. **层级结构**: Combo 可以嵌套,形成层级关系 4. **内部元素管理**: Combo 需要管理其包含的节点和子 Combo ### 原子图形 G6 的 Combo 是由 [G 图形系统](https://g.antv.antgroup.com/) 提供的图形原子单元绘制而成。原子图形的介绍请参考 [元素 - 图形(可选)](/zh/manual/element/shape/overview/) 文档。 所有这些图形都可通过 `upsert()` 动态创建或更新,并自动管理图形状态和生命周期。 ### 元素基类 开始自定义 Combo 之前,你需要了解 G6 元素基类中的一些重要属性和方法: #### 属性 | 属性 | 类型 | 描述 | | ---------- | ----------------------------- | -------------------------- | | shapeMap | Record<string, DisplayObject> | 当前元素下所有图形的映射表 | | animateMap | Record<string, IAnimation> | 当前元素下所有动画的映射表 | #### 方法 #### `upsert(name, Ctor, style, container, hooks)`: 图形创建/更新 在创建自定义 Combo 时,你会频繁用到 `upsert` 方法。它是 "update or insert" 的缩写,负责添加或更新元素中的图形: ```typescript upsert(key: string, Ctor: { new (...args: any[]): DisplayObject }, style: Record, container: DisplayObject); ``` | 参数 | 类型 | 描述 | | --------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | key | string | 图形的 key,即 `shapeMap` 中对应的 key。内置的 key 包括 `'key'` `'label'` `'halo'` `'icon'` `'port'` `'badge'`
key 不应使用特殊符号,会基于该值转化为驼峰形式调用 `getXxxStyle` 和 `drawXxxShape` 方法(见 [元素约定](#元素约定)) | | Ctor | \{ new (...args: any[]): DisplayObject \} | 图形类 | | style | Record<string, any> | 图形样式 | | container | DisplayObject | 挂载图形的容器 | 例如,插入一个固定位置的紫色圆形: ```js this.upsert( 'element-key', // 元素的唯一标识 'circle', // 图形类型,如 'rect', 'circle' 等 { x: 100, y: 100, fill: '#a975f3' }, // 样式配置对象 container, // 父容器 ); ``` 为什么要使用 `upsert` 而不直接通过 `container.appendChild()` 创建图形?因为: 1. **性能更好**:当状态变化或数据更新时,会智能地复用已有图形,而不是删除再重建,大大提高了渲染性能 2. **代码更简洁**:不需要手动判断元素是否存在 3. **便于管理**:所有通过 `upsert` 创建的图形都会被记录在节点的 `shapeMap` 中,你可以通过 `this.getShape(key)` 轻松获取 #### `render(attributes, container)`: 渲染组合的主入口 每个自定义 Combo 类都必须实现 `render(attributes, container)` 方法,它定义了该组合如何被"绘制"出来。你可以在这里使用各种原子图形,组合出你想要的结构。 ```typescript render(style: Record, container: Group): void; ``` | 参数 | 类型 | 描述 | | --------- | ------------------- | -------- | | style | Record<string, any> | 元素样式 | | container | Group | 容器 | #### `getShape(name)`: 获取已创建的图形 有时,你需要在创建后修改某个子图形的属性,或者让子图形之间有交互关联。这时,`getShape` 方法可以帮你获取之前通过 `upsert` 创建的任何图形: **⚠️ 注意**:图形的顺序很重要,如果图形 B 依赖图形 A 的位置,必须确保 A 先创建 ### 元素约定 - **使用约定属性** 组合中约定的元素属性包括: - 通过 `this.getKeySize(attributes)` 获取组合的尺寸,考虑折叠状态和子元素 - 通过 `this.getContentBBox(attributes)` 获取内容区域的边界盒 - 通过 `this.getComboPosition(attributes)` 获取组合的当前位置,基于状态和子元素 - **采用 `getXxxStyle` 和 `drawXxxShape` 配对的方式进行图形绘制** `getXxxStyle` 用于获取图形样式,`drawXxxShape` 用于绘制图形。通过该方式创建的图形支持自动执行动画。 > 其中 `Xxx` 是调用 [upsert](#方法) 方法时传入的 key 的驼峰形式。 - **可通过 `this.context` 访问 Graph 上下文** ### 生命周期钩子 提供了以下生命周期钩子函数,你可以在自定义 Combo 中重写这些方法,在关键时刻执行特定逻辑: | 钩子函数 | 触发时机 | 典型用途 | | ----------- | -------------------------- | -------------------------------------------- | | `onCreate` | 当组合创建后完成入场动画时 | 绑定交互事件、初始化组合状态、添加外部监听器 | | `onUpdate` | 当组合更新后完成更新动画时 | 更新依赖数据、调整相关元素、触发联动效果 | | `onDestroy` | 当组合完成退场动画并销毁后 | 清理资源、移除外部监听器、执行销毁通知 | ### 状态响应 G6 元素设计中最强大的一点,是可以将 **"状态响应"** 与 **"绘制逻辑"** 分离。 你可以在组合配置中定义每种状态下的样式: ```js combo: { type: 'custom-combo', style: { fill: '#f0f2f5', stroke: '#d9d9d9' }, state: { selected: { stroke: '#1890ff', lineWidth: 2, shadowColor: 'rgba(24,144,255,0.2)', shadowBlur: 15, }, hover: { fill: '#e6f7ff', }, }, } ``` 切换状态的方法: ```js graph.setElementState(comboId, ['selected']); ``` 这个状态会传入到 `render()` 方法的 `attributes` 中,由内部系统合并后的结果自动应用在图形上。 也可以根据状态自定义渲染逻辑: ```typescript protected getKeyStyle(attributes: Required) { const style = super.getKeyStyle(attributes); // 根据状态调整样式 if (attributes.states?.includes('selected')) { return { ...style, stroke: '#1890ff', lineWidth: 2, shadowColor: 'rgba(24,144,255,0.2)', shadowBlur: 15, }; } return style; } ``` #### 垂直三次贝塞尔曲线边 CubicVertical - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/CubicVertical/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/CubicVertical.md - Description: 垂直三次贝塞尔曲线边 CubicVertical --- title: "垂直三次贝塞尔曲线边 CubicVertical" description: "垂直三次贝塞尔曲线边 CubicVertical" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/CubicVertical/" version: "5.1.1" --- ## 概述 垂直三次贝塞尔曲线是一种平滑的曲线,其控制点主要沿垂直方向分布,适合在垂直方向上连接节点。 使用场景: - 适用于垂直布局的图,如组织结构图、树状图。 - 当需要强调垂直方向的连接关系时使用。 **特别注意,计算控制点时主要考虑 y 轴上的距离,忽略 x 轴的变化** ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }, { id: 'node6' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4', text: 'cubic-vertical' }, { source: 'node1', target: 'node5' }, { source: 'node1', target: 'node6' }, ], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, port: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }, }, edge: { type: 'cubic-vertical', style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, }, }, behaviors: ['drag-canvas', 'drag-element'], layout: { type: 'antv-dagre', rankdir: 'TB', nodesep: 25, ranksep: 80, }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { gui.add({ type: 'cubic-vertical' }, 'type').disable(); const options = { curveOffset: 20, curvePosition: 0.5, }; const optionFolder = gui.addFolder('cubic-vertical.style'); optionFolder.add(options, 'curveOffset', 0, 100); optionFolder.add(options, 'curvePosition', 0, 1); optionFolder.onChange(({ property, value }) => { graph.updateEdgeData((prev) => prev.map((edge) => ({ ...edge, style: { [property]: value } }))); graph.render(); }); }, ); ``` 设置 `edge.type` 为 `cubic-vertical` 以使用垂直方向的三次贝塞尔曲线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | ---------------------------------------------------- | ---------------------- | --------- | ---- | | curvePosition | 控制点在两端点连线上的相对位置,范围为`0-1` | number | number[] | [0.5,0.5] | | | curveOffset | 控制点距离两端点连线的距离,可理解为控制边的弯曲程度 | number | number[] | [0,0] | | ## 示例 ### 内置垂直三次贝塞尔曲线边效果 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { port: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }, }, edge: { type: 'cubic-vertical', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, }, }, layout: { type: 'antv-dagre', begin: [50, 50], rankdir: 'TB', nodesep: 20, ranksep: 120, }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 甜甜圈节点 Donut - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Donut/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Donut.md - Description: 甜甜圈节点 Donut --- title: "甜甜圈节点 Donut" description: "甜甜圈节点 Donut" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Donut/" version: "5.1.1" --- ## 概述 甜甜圈节点是一个环形几何形状,由内外两个同心圆组成。 适用场景: - 用于表示比例数据,如完成进度、占比分析。 - 适合表示多层数据,如嵌套的环形图。 - 常用于数据可视化、仪表盘、进度图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [ { id: 'node1', style: { fill: 'transparent', size: 60, donuts: [30, 30, 20, 20], donutPalette: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }, }, ], }, node: { type: 'donut' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'donut' }, 'type').disable(); const options = { size: 60, innerR: 50, donutPalette: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }; const optionFolder = gui.addFolder('donut.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'innerR', 0, 100, 1).name('innerR(%)'); optionFolder.add(options, 'donutPalette', ['spectral', 'tableau', ['#1783FF', '#00C9C9', '#F08F56', '#D580FF']]); optionFolder.onChange(({ property, value }) => { if (property === 'innerR') value = value + '%'; graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `donut` 以使用甜甜圈节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------- | ------------------------------ | ------------------------------------------- | --------- | ---- | | donutFill | 填充色 | string | `#1783FF` | | | donutFillOpacity | 填充色透明度 | number \| string | 1 | | | donutLineCap | 描边端点样式 | `round` \| `square` \| `butt` | `butt` | | | donutLineDash | 描边虚线样式 | number[] | - | | | donutLineDashOffset | 描边虚线偏移量 | number | - | | | donutLineJoin | 描边连接处样式 | `round` \| `bevel` \| `miter` | `miter` | | | donutLineWidth | 描边宽度 | number | 1 | | | donutOpacity | 透明度 | number \| string | 1 | | | donutPalette | 颜色或者色板名 | string | string[] | `tableau` | | | donuts | 圆环数据 | number[] | [DonutRound](#donutround)[] | - | | | donutShadowBlur | 阴影模糊度 | number | - | | | donutShadowColor | 阴影颜色 | string | - | | | donutShadowOffsetX | 阴影在 x 轴方向上的偏移量 | number \| string | - | | | donutShadowOffsetY | 阴影在 y 轴方向上的偏移量 | number \| string | - | | | donutShadowType | 阴影类型 | `inner` \| `outer` | `outer` | | | donutStroke | 描边色 | string | `#000` | | | donutStrokeOpacity | 描边色透明度 | number \| string | 1 | | | donutVisibility | 图形是否可见 | `visible` \| `hidden` | `visible` | | | innerR | 内环半径,使用百分比或者像素值 | string | number | 50% | | ### DonutRound | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ------------------------- | ----------------------------- | --------- | ---- | | color | 颜色 | string | - | | | fill | 填充色 | string | `#1783FF` | | | fillOpacity | 填充色透明度 | number \| string | 1 | | | lineCap | 描边端点样式 | `round` \| `square` \| `butt` | `butt` | | | lineDash | 描边虚线样式 | number[] | - | | | lineDashOffset | 描边虚线偏移量 | number | - | | | lineJoin | 描边连接处样式 | `round` \| `bevel` \| `miter` | `miter` | | | lineWidth | 描边宽度 | number | 1 | | | opacity | 透明度 | number \| string | 1 | | | shadowBlur | 阴影模糊度 | number | - | | | shadowColor | 阴影颜色 | string | - | | | shadowOffsetX | 阴影在 x 轴方向上的偏移量 | number \| string | - | | | shadowOffsetY | 阴影在 y 轴方向上的偏移量 | number \| string | - | | | shadowType | 阴影类型 | `inner` \| `outer` | `outer` | | | stroke | 描边色 | string | `#000` | | | strokeOpacity | 描边色透明度 | number \| string | 1 | | | value | 数值,用于计算比例 | number | - | ✓ | | visibility | 图形是否可见 | `visible` \| `hidden` | `visible` | | ## 示例 ### 内置甜甜圈节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default', index: 0 }, { id: 'halo', index: 1 }, { id: 'badges', index: 2 }, { id: 'ports', index: 3 }, { id: 'active', states: ['active'], index: 4, }, { id: 'selected', states: ['selected'], index: 5, }, { id: 'highlight', states: ['highlight'], index: 6, }, { id: 'inactive', states: ['inactive'], index: 7, }, { id: 'disabled', states: ['disabled'], index: 8, }, ], }; const graph = new Graph({ container: 'container', animation: false, data, node: { type: 'donut', style: { size: 80, fill: '#DB9D0D', innerR: 20, donuts: (item) => { const { index } = item; if (index === 0) return [1, 2, 3]; // donuts数据类型为number[]时,根据值的大小决定环的占比 if (index === 1) { return [ { value: 50, color: 'red' }, { value: 150, color: 'green' }, { value: 100, color: 'blue' }, ]; } if (index === 4) { return [ { value: 150, fill: 'pink', stroke: '#fff', lineWidth: 1 }, { value: 250, stroke: '#fff', lineWidth: 1 }, { value: 200, stroke: '#fff', lineWidth: 1 }, ]; } return [100, 200, 100, 200]; }, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 使用 iconfont - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/iconfont/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/iconfont.md - Description: 使用 iconfont --- title: "使用 iconfont" description: "使用 iconfont" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/iconfont/" version: "5.1.1" --- ## 概述 为什么使用 iconfont? 兼容性好、种类多、多色等。在此不做过多介绍,请直接移步 [阿里巴巴-iconfont 平台](https://www.iconfont.cn)。 ![iconfont](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*rJ3lQa0HR-wAAAAAAAAAAABkARQnAQ) ## 使用 ### 下载字体图标 首先,你需要从 [iconfont](https://www.iconfont.cn) 网站下载所需的图标字体。创建一个项目并选择所需的图标,然后下载生成的图标文件。 ### 添加字体图标 下载完成后,将包含图标字体文件的目录(通常包括 `.eot`、`.woff`、`.ttf` 和 `.svg` 文件,以及 `iconfont.css` 样式文件)放入你的项目中。 引入方式可自行选择,下面为在 HTML 中引入的例子: ```html ``` ### 使用字体 ```js { node: { style: { iconFontFamily: 'iconfont', // 对应 iconfont.css 中的 `font-family` 属性值 iconText: '\ue7f1', // 对应 iconfont.css 中的 `content` 属性值,注意加 `u` iconFill: '#7863FF' } } } ``` ### 工具函数 `getIcon()` 为了更方便地获取图标,可以创建一个工具函数 `getIcon`。该函数会从图标文件 `iconfont.json` 中读取图标信息并返回相应的 Unicode 字符。这里注意,手动拼接 unicode 是不行的(`\\u${icon.unicode}`)。详细参考 [MDN String.fromCodePoint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)。 首先,确保你有一个 `iconfont.json` 文件,包含图标的详细信息。 ```js import fonts from 'path-to-iconfont/iconfont.json'; const icons = fonts.glyphs.map((icon) => { return { name: icon.font_class, unicode: String.fromCodePoint(icon.unicode_decimal), // `\\u${icon.unicode}`, }; }); const getIcon = (type: string) => { const matchIcon = icons.find((icon) => { return icon.name === type; }) || { unicode: '', name: 'default' }; return matchIcon.unicode; }; ``` 在项目中使用: ```js { node: { style: { iconFontFamily: "iconfont", iconText: getIcon('logo') } } } ``` #### 内置扩展 - Canonical page: https://g6.antv.antgroup.com/zh/manual/graph/extensions/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/graph/extensions.md - Description: 内置扩展 --- title: "内置扩展" description: "内置扩展" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/graph/extensions/" version: "5.1.1" --- G6 内置扩展及注册扩展类型如下: ## 动画 | 扩展 | 注册类型 | 描述 | | ------------- | ---------------- | -------- | | ComboCollapse | 'combo-collapse' | 组合收起 | | ComboExpand | 'combo-expand' | 组合展开 | | NodeCollapse | 'node-collapse' | 节点收起 | | NodeExpand | 'node-expand' | 节点展开 | | PathIn | 'path-in' | 路径进入 | | PathOut | 'path-out' | 路径退出 | | Fade | 'fade' | 渐变 | | Translate | 'translate' | 平移 | 配置方式: 在 `GraphOptions.[node|edge|combo].animation.[stage]` 中使用,示例: ```ts const graph = new Graph({ // ... 其他配置 node: { animation: { update: 'translate', // 更新阶段仅使用平移动画 }, }, }); ``` ## 交互 | 扩展 | 注册类型 | 描述 | | ------------------------- | ----------------------------- | ---------------------- | | BrushSelect | 'brush-select' | 框选 | | ClickSelect | 'click-select' | 点击选中 | | CollapseExpand | 'collapse-expand' | 展开/收起元素 | | CreateEdge | 'create-edge' | 创建边 | | DragCanvas | 'drag-canvas' | 拖拽画布 | | DragElementForce | 'drag-element-force' | 力导向拖拽元素 | | DragElement | 'drag-element' | 拖拽元素 | | FixElementSize | 'fix-element-size' | 缩放画布时固定元素大小 | | FocusElement | 'focus-element' | 聚焦元素 | | HoverActivate | 'hover-activate' | 悬停激活 | | LassoSelect | 'lasso-select' | 套索选择 | | OptimizeViewportTransform | 'optimize-viewport-transform' | 操作画布时隐藏元素 | | ScrollCanvas | 'scroll-canvas' | 滚动画布 | | ZoomCanvas | 'zoom-canvas' | 缩放画布 | 配置方式: 在 `GraphOptions.behaviors` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }); ``` ## 元素 ### 节点 | 扩展 | 注册类型 | 描述 | | -------- | -------- | ---------- | | circle | Circle | 圆形节点 | | diamond | Diamond | 菱形节点 | | ellipse | Ellipse | 椭圆节点 | | hexagon | Hexagon | 六边形节点 | | html | HTML | HTML节点 | | image | Image | 图片节点 | | rect | Rect | 矩形节点 | | star | Star | 星形节点 | | donut | Donut | 甜甜圈节点 | | triangle | Triangle | 三角形节点 | 配置方式: 1. 在 `GraphOptions.data.nodes[number].type` 中配置; 2. 在 `GraphOptions.node.type` 中配置; ```ts const graph = new Graph({ // ... 其他配置 data: { nodes: [{ id: 'node-1', type: 'circle' }], }, node: { type: 'circle', }, }); ``` ### 边 | 扩展 | 注册类型 | 描述 | | --------------- | ------------------ | ------------------ | | Cubic | 'cubic' | 三次贝塞尔曲线 | | Line | 'line' | 直线 | | Polyline | 'polyline' | 折线 | | Quadratic | 'quadratic' | 二次贝塞尔曲线 | | CubicHorizontal | 'cubic-horizontal' | 水平三次贝塞尔曲线 | | CubicVertical | 'cubic-vertical' | 垂直三次贝塞尔曲线 | | CubicRadial | 'cubic-radial' | 径向三次贝塞尔曲线 | 配置方式同 `节点`: 1. 在 `GraphOptions.data.edges[number].type` 中配置; 2. 在 `GraphOptions.edge.type` 中配置; ### 组合 | 扩展 | 注册类型 | 描述 | | ----------- | -------- | -------- | | CircleCombo | 'circle' | 圆形组合 | | RectCombo | 'rect' | 矩形组合 | 配置方式同 `节点`: 1. 在 `GraphOptions.data.combos[number].type` 中配置; 2. 在 `GraphOptions.combo.type` 中配置; ## 布局 | 扩展 | 注册类型 | 描述 | | ------------------- | ---------------- | ---------------------- | | AntVDagreLayout | 'antv-dagre' | AntV Dagre 布局 | | ComboCombinedLayout | 'combo-combined' | 组合布局 | | CompactBoxLayout | 'compact-box' | 紧凑树 | | ForceAtlas2Layout | 'force-atlas2' | ForceAlas2 力导向布局 | | CircularLayout | 'circular' | 环形布局 | | ConcentricLayout | 'concentric' | 同心圆布局 | | D3ForceLayout | 'd3-force' | D3 力导向布局 | | DagreLayout | 'dagre' | Dagre 布局 | | DendrogramLayout | 'dendrogram' | 生态树 | | ForceLayout | 'force' | 力导向布局 | | FruchtermanLayout | 'fruchterman' | Fruchterman 力导向布局 | | GridLayout | 'grid' | 网格布局 | | IndentedLayout | 'indented' | 缩进树 | | MDSLayout | 'mds' | 高维数据降维布局 | | MindmapLayout | 'mindmap' | 脑图树 | | RadialLayout | 'radial' | 径向布局 | | RandomLayout | 'random' | 随机布局 | 配置方式: 在 `GraphOptions.layout` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 layout: { type: 'force', }, }); ``` ## 色板 - spectral
- tableau
- oranges
- greens
- blues
配置方式: 在 `GraphOptions.[node|edge|combo].palette` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 node: { palette: 'tableau', }, }); ``` ## 主题 | 注册类型 | 描述 | | -------- | -------- | | dark | 深色主题 | | light | 浅色主题 | 配置方式: 在 `GraphOptions.theme` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 theme: 'dark', }); ``` ## 插件 | 扩展 | 注册类型 | 描述 | | -------------- | ------------------ | ---------- | | BubbleSets | 'bubble-sets' | 气泡集 | | EdgeFilterLens | 'edge-filter-lens' | 边过滤镜 | | GridLine | 'grid-line' | 网格线 | | Background | 'background' | 背景 | | Contextmenu | 'contextmenu' | 上下文菜单 | | Fisheye | 'fisheye' | 鱼眼放大镜 | | Fullscreen | 'fullscreen' | 全屏展示 | | History | 'history' | 历史记录 | | Hull | 'hull' | 轮廓包围 | | Legend | 'legend' | 图例 | | Minimap | 'minimap' | 小地图 | | Snapline | 'snapline' | 对齐线 | | Timebar | 'timebar' | 时间条 | | Toolbar | 'toolbar' | 工具栏 | | Tooltip | 'tooltip' | 提示框 | | Watermark | 'watermark' | 水印 | 配置方式: 在 `GraphOptions.plugins` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 plugins: ['minimap', 'contextmenu'], }); ``` ## 数据转换 | 扩展 | 注册类型 | 描述 | | -------------------- | ------------------------ | -------- | | ProcessParallelEdges | 'process-parallel-edges' | 平行边 | | PlaceRadialLabels | 'place-radial-labels' | 径向标签 | 配置方式: 在 `GraphOptions.transforms` 中配置,示例: ```ts const graph = new Graph({ // ... 其他配置 transform: ['process-parallel-edges', 'place-radial-labels'], }); ``` ## 图形 | 注册类型 | 描述 | | -------- | ------ | | circle | 圆形 | | ellipse | 椭圆 | | group | 分组 | | html | HTML | | image | 图片 | | line | 直线 | | path | 路径 | | polygon | 多边形 | | polyline | 折线 | | rect | 矩形 | | text | 文本 | | label | 标签 | | badge | 徽标 | 使用方式: 自定义图形时,元素类成员方法 [upsert](/zh/manual/element/node/custom-node/) 方法第二个参数传入: ```ts this.upsert('shape-key', 'text', { text: 'label', fontSize: 16 }, this); ``` #### 复合布局 ComboCombined - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/ComboCombinedLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/ComboCombinedLayout.md - Description: 复合布局 ComboCombined --- title: "复合布局 ComboCombined" description: "复合布局 ComboCombined" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/ComboCombinedLayout/" version: "5.1.1" --- ## 概述 ComboCombined 复合布局适用于复合分组结构的图数据展示场景,支持灵活配置 Combo 内部元素的布局以及最外层 Combo 和节点之间的布局。 默认情况内部元素采用 Concentric 同心圆布局,外部布局采用 gForce 力导向布局,兼顾布局效果与整体稳定性。参考更多 ComboCombined 复合布局[样例](/zh/examples/layout/combo-layout/)和[源码](https://github.com/antvis/layout/blob/v5/packages/layout/src/combo-combined.ts) ## 使用场景 - 用户画像分析: 分析用户行为与商品关系,将用户兴趣圈层作为 Combo,内部节点展示具体商品和行为标签,帮助运营人员识别用户消费路径。 - 供应链管理图:供应商、制造商、仓储、分销商按角色或区域划分 Combo,内部节点展示资源、人员或设备,清晰展示供应链各环节内部结构。 ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------ | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------ | ---- | | type | 布局类型 | `combo-combined` | - | ✓ | | center | 布局中心 | [`PointTuple`](https://github.com/antvis/layout/blob/v5/packages/layout/src/types.ts#L829) | 图中心 | | | layout | 布局配置。可固定指定,也可根据 `comboId` 动态返回 | `string` \| `object` \| `(comboId?: string) => string \| object` | - | | | nodeSize | 节点大小(直径)。用于碰撞检测 | `number` \| `number[]` \| (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | - | | | nodeSpacing | 节点间距 | `number` \| (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | - | | | comboSpacing | Combo 之间的间距 | `number` \| (d?: unknown) => number | - | | | comboPadding | Combo 内部的 padding 值,不用于渲染,仅用于计算力。推荐设置为与视图上 Combo 内部 padding 值相同的值 | `((d?: unknown) => number)` \| `number` \| `number[]` \| `undefined` | - | | ### layout > _`string | object | (comboId?: string) => string | object`_ 5.1 中推荐使用单个 `layout` 字段为不同层级选择布局,而不是分别配置 `innerLayout` 和 `outerLayout`。 **示例**: ```ts new Graph({ layout: { type: 'combo-combined', layout: (comboId) => (comboId ? { type: 'grid' } : { type: 'force' }), }, }); ``` ## 示例代码 ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/combo.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, layout: { type: 'combo-combined', comboPadding: 2, }, node: { style: { size: 20, labelText: (d) => d.id, }, palette: { type: 'group', field: (d) => d.combo, }, }, edge: { style: (model) => { const { size, color } = model.data; return { stroke: color || '#99ADD1', lineWidth: size || 1, }; }, }, behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas'], autoFit: 'view', }); graph.render(); }); ``` #### 边绑定 EdgeBundling - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/EdgeBundling/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/EdgeBundling.md - Description: 边绑定 EdgeBundling --- title: "边绑定 EdgeBundling" description: "边绑定 EdgeBundling" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/EdgeBundling/" version: "5.1.1" --- ## 概述 边绑定(Edge Bundling)是一种图可视化技术,用于减少复杂网络图中的视觉混乱,并展示图中的高级别模式和结构。其目的是将相邻的边捆绑在一起。 G6 中提供的边绑定插件是基于 [FEDB(Force-Directed Edge Bundling for Graph Visualization)](https://classes.engineering.wustl.edu/cse557/readings/holten-edgebundling.pdf)论文的实现:将边建模为可以相互吸引的柔性弹簧,通过自组织的方式进行捆绑。 ## 使用场景 边绑定插件主要适用于以下场景: - 减少复杂网络图中的视觉混乱 - 揭示图中的高级别模式和结构 - 提高大规模图数据的可读性和美观性 ## 基本用法 以下是一个简单的 EdgeBundling 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'edge-bundling', bundleThreshold: 0.6, cycles: 6, divisions: 3, divRate: 2, iterations: 90, iterRate: 2 / 3, K: 0.1, lambda: 0.1, }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | -------------------------------------------------------------------------------------------------- | ------ | --------------- | ---- | | type | 插件类型,用于标识该插件为边捆绑插件 | string | `edge-bundling` | ✓ | | key | 插件的唯一标识,可用于获取插件实例或更新插件选项 | string | - | | | bundleThreshold | 边兼容性阈值,该值决定了哪些边应该被绑定在一起,值越大,绑定的边越少,[示例](#bundlethreshold) | number | 0.6 | | | cycles | 模拟周期数,控制边捆绑模拟的执行轮数 | number | 6 | | | divisions | 初始切割点数,在后续的周期中,切割点数将根据 divRate 逐步递增,影响边的细分程度 | number | 1 | | | divRate | 切割点数增长率,决定了每一轮周期中切割点数的增长幅度 | number | 2 | | | iterations | 指定在第一个周期中执行的迭代次数,在后续的周期中,迭代次数将根据 iterRate 逐步递减,影响模拟的精度 | number | 90 | | | iterRate | 迭代次数递减率,控制每一轮周期中迭代次数的减少比例 | number | 2\/3 | | | K | 边的强度,影响边之间的吸引力和排斥力,[示例](#k) | number | 0.1 | | | lambda | 初始步长,在后续的周期中,步长将双倍递增,影响边捆绑过程中节点移动的幅度 | number | 0.1 | | ### bundleThreshold 边兼容性阈值,该值决定了哪些边应该被绑定在一起。值越大,绑定的边越少,反之则绑定的边越多。 - 较低的 bundleThreshold 值(如 0.4)会使更多的边被绑定在一起,形成更明显的捆绑效果。 ```js const graph = new Graph({ plugins: [ { type: 'edge-bundling', bundleThreshold: 0.4, // 较低的边兼容性阈值 }, ], }); ``` 效果如下: 较低的边兼容性阈值 - 较高的 bundleThreshold 值(如 0.8)会使较少的边被绑定在一起,保持更多的独立边。 ```js const graph = new Graph({ plugins: [ { type: 'edge-bundling', bundleThreshold: 0.8, // 较高的边兼容性阈值 }, ], }); ``` 效果如下: 较高的边兼容性阈值 ### K 边的强度,影响边之间的吸引力和排斥力。较高的 K 值会使边之间的吸引力更强,从而形成更紧密的捆绑效果。 - 较低的 K 值(如 0.05)会使边之间的吸引力较弱,边的捆绑效果较弱。 ```js const graph = new Graph({ plugins: [ { type: 'edge-bundling', K: 0.05, // 较低的边强度 }, ], }); ``` 效果如下: 较低的边强度 - 较高的 K 值(如 0.2)会使边之间的吸引力较强,边的捆绑效果更明显。 ```js const graph = new Graph({ plugins: [ { type: 'edge-bundling', K: 0.2, // 较高的边强度 }, ], }); ``` 效果如下: 较高的边强度 ## 代码示例 ### 基础边绑定 最简单的方式是直接使用预设配置: ```js const graph = new Graph({ // 其他配置... plugins: ['edge-bundling'], }); ``` ### 自定义样式 您可以根据需要自定义边绑定的参数: ```js const graph = new Graph({ // 其他配置... plugins: [ { type: 'edge-bundling', bundleThreshold: 0.8, // 更高的边兼容性阈值 cycles: 8, // 更多模拟周期 K: 0.2, // 更强的边强度 }, ], }); ``` ### 动态更新边绑定 使用 key 标识符可以在运行时动态更新边绑定属性: ```js // 初始化配置 const graph = new Graph({ // 其他配置... plugins: [ { type: 'edge-bundling', key: 'my-edge-bundling', bundleThreshold: 0.6, }, ], }); // 后续动态更新 graph.updatePlugin({ key: 'my-edge-bundling', bundleThreshold: 0.8, // 更新边兼容性阈值 cycles: 10, // 更新模拟周期数 }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, layout: { type: 'circular', }, node: { style: { size: 20 } }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { key: 'edge-bundling', type: 'edge-bundling', bundleThreshold: 0.1, }, ], }); graph.render(); }); ``` #### 自定义色板 - Canonical page: https://g6.antv.antgroup.com/zh/manual/theme/custom-palette/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/theme/custom-palette.md - Description: 自定义色板 --- title: "自定义色板" description: "自定义色板" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/theme/custom-palette/" version: "5.1.1" --- ## 概述 [色板](/zh/manual/theme/palette/) 中提到,G6 支持离散色板和连续色板,其中离散色板本质上是一个颜色数组,而连续色板是一个颜色插值器。 因此自定义色板也采用这两种方式,下面分别介绍如何自定义离散色板和连续色板。 ## 实现色板 ### 离散色板 直接定义一个包含颜色值的字符串数组即可,颜值值支持:RGB 色值、16 进制、颜色名,下面是一组离散色板示例: ```typescript const hex = ['#FF0000', '#00FF00', '#0000FF']; const color = ['red', 'green', 'blue']; const rgb = ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(0, 0, 255)']; ``` ### 连续色板 连续色板需要定义一个颜色插值器,插值器是一个函数,接受一个数值参数,返回一个颜色值,下面是一个连续色板示例: ```typescript const color = (value: number) => `rgb(${value * 255}, 0, 0)`; ``` ## 注册色板 通过 G6 提供的 register 方法注册即可,详见[注册色板](/zh/manual/theme/palette/#注册色板) ## 非注册方式使用 除此之外,你也可以在需要使用色板的位置跳过注册机制直接传入色板值,例如: ```typescript { node: { palette: { type: 'group', field: 'category', color: ['#5B8FF9', '#61DDAA', '#F6BD16'], // 传入颜色数组 } }, edge: { palette: { type: 'value', field: 'value', color: (value) => `rgb(${value * 255}, 0, 0)`, // 传入插值器 } } } ``` #### 自定义数据处理 - Canonical page: https://g6.antv.antgroup.com/zh/manual/transform/custom-transform/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/transform/custom-transform.md - Description: 自定义数据处理 --- title: "自定义数据处理" description: "自定义数据处理" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/transform/custom-transform/" version: "5.1.1" --- ## 概述 自定义数据处理允许用户在业务实现过程中,把额外的数据处理封装起来,在渲染前或者布局后对数据进行进一步处理。用户通过自定义数据处理,实现部分数据处理解耦,更好地进行管理、编排代码以及提高代码可维护性。 ## 开始前 用户在进行自定义数据处理前,需要仔细阅读并掌握数据处理器的 [实现原理和执行时机](/zh/manual/transform/overview/#实现原理) 。 ## 代码示例 接下来将讲述两个可能的业务场景,并通过自定义数据处理来实现: ### 不展示游离节点 - **需求** 游离节点,即没有连线的节点,画布渲染时不展示游离节点 - **实现** ```typescript import type \{ DrawData, DrawContext \} from '@antv/g6'; import \{ Graph, BaseTransform, register, ExtensionCategory \} from '@antv/g6'; class HideFreeNode extends BaseTransform \{ public beforeDraw(input: DrawData, context: DrawContext): DrawData \{ const \{ model \} = this.context; const \{ add, update, remove \} = input; add.nodes.forEach((nodeData, nodeId) => \{ // 获取节点的相关连线 const edges = model.getRelatedEdgesData(nodeId); // 没有任何连线的的节点则从add里面移除,添加到remove里面 if (!edges.length) \{ add.nodes.delete(nodeId); remove.nodes.set(nodeId, nodeData); \} \}); return input; \} \} ``` ```ts import { BaseTransform, ExtensionCategory, Graph, register } from '@antv/g6'; class HideFreeNode extends BaseTransform { beforeDraw(input, context) { const { model } = this.context; const { add, update, remove } = input; add.nodes.forEach((nodeData, nodeId) => { // 获取节点的相关连线 const edges = model.getRelatedEdgesData(nodeId); // 没有任何连线的的节点则从add里面移除,添加到remove里面 if (!edges.length) { add.nodes.delete(nodeId); remove.nodes.set(nodeId, nodeData); } }); return input; } } register(ExtensionCategory.TRANSFORM, 'hide-free-node', HideFreeNode); const data = { nodes: [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }], edges: [ { source: '1', target: '2' }, { source: '2', target: '3' }, { source: '3', target: '5' }, ], }; const graph = new Graph({ container: 'container', width: 600, height: 400, autoFit: 'center', data, node: { style: { labelText: (d) => d.id, }, }, layout: { type: 'antv-dagre', rankdir: 'LR', }, transforms: ['hide-free-node'], }); graph.render(); ``` - **说明** 示例中总共有6个节点,id为1-6,id为4的节点没有连线,因此被移除了。 通过 `getRelatedEdgesData` 获取节点的相关连线,没有则把该节点放到 `remove.nodes` 里面去,并从 `add.nodes` 里面移除。 ### 环形布局径向label - **需求** 使用 [环形布局](/zh/manual/layout/CircularLayout/) 时,节点 label 的也需要像内置数据处理器 [PlaceRadialLabels](/zh/manual/transform/PlaceRadialLabels/) 一样实现径向展示(但 PlaceRadialLabels 只支持径向布局,环形布局不是径向布局) - **实现** ```typescript import type \{ RuntimeContext, DrawContext, Point, TransformArray, Vector2, Vector3 \} from '@antv/g6'; import \{ Graph, BaseTransform, register, ExtensionCategory, BaseTransformOptions \} from '@antv/g6'; // 目前circular布局没有暴露方法可以获取布局中心,这里简单处理先固定一个,配置circular布局时center与这里保持一致即可 const circularCenter = [300, 300]; // 下面的函数 G6 没有暴露出来,先自行声明 function subtract(a: Vector2 | Vector3, b: Vector2 | Vector3): Vector2 | Vector3 \{ return a.map((v, i) => v - b[i]) as Vector2 | Vector3; \} function rad(a: Vector2 | Vector3): number \{ const [x, y] = a; if (!x && !y) return 0; return Math.atan2(y, x); \} function rad2deg(rad: number): number \{ return rad * (180 / Math.PI); \} interface CircularRadialLabelsOptions extends BaseTransformOptions \{ offset?: number; // 偏移量 \} class CircularRadialLabels extends BaseTransform<CircularRadialLabelsOptions> \{ static defaultOptions = \{ offset: 5, \}; constructor(context: RuntimeContext, options: CircularRadialLabelsOptions) \{ super(context, Object.assign(\{\}, CircularRadialLabels.defaultOptions, options)); \} get center(): Point \{ return circularCenter; \} public afterLayout() \{ const \{ graph, model \} = this.context; const data = model.getData(); data.nodes?.forEach((datum) => \{ const radian = rad(subtract([datum.style.x, datum.style.y], this.center)); const isLeft = Math.abs(radian) > Math.PI / 2; const isLeaf = !datum.children || datum.children.length === 0; const nodeId = datum.id; const node = this.context.element?.getElement(nodeId); if (!node || !node.isVisible()) return; const nodeHalfWidth = graph.getElementRenderStyle(nodeId).size / 2; const offset = (isLeaf ? 1 : -1) * (nodeHalfWidth + this.options.offset); const labelTransform: TransformArray = [ ['translate', offset * Math.cos(radian), offset * Math.sin(radian)], ['rotate', isLeft ? rad2deg(radian) + 180 : rad2deg(radian)], ]; model.updateNodeData([ \{ id: datum.id, style: \{ labelTextAlign: isLeft === isLeaf ? 'right' : 'left', labelTextBaseline: 'middle', labelTransform, \}, \}, ]); \}); graph.draw(); \} \} ``` ```ts import { BaseTransform, ExtensionCategory, Graph, register } from '@antv/g6'; // 目前circular布局没有暴露方法可以获取布局中心,这里简单处理先固定一个 const circularCenter = [300, 300]; // 下面的函数 G6 没有暴露出来,先自行声明 function subtract(a, b) { return a.map((v, i) => v - b[i]); } function rad(a) { const [x, y] = a; if (!x && !y) return 0; return Math.atan2(y, x); } function rad2deg(rad) { return rad * (180 / Math.PI); } class CircularRadialLabels extends BaseTransform { static defaultOptions = { offset: 5, }; constructor(context, options) { super(context, Object.assign({}, CircularRadialLabels.defaultOptions, options)); } get center() { return circularCenter; } afterLayout() { const { graph, model } = this.context; const data = model.getData(); data.nodes?.forEach((datum) => { const radian = rad(subtract([datum.style.x, datum.style.y], this.center)); const isLeft = Math.abs(radian) > Math.PI / 2; const isLeaf = !datum.children || datum.children.length === 0; const nodeId = datum.id; const node = this.context.element?.getElement(nodeId); if (!node || !node.isVisible()) return; const nodeHalfWidth = graph.getElementRenderStyle(nodeId).size / 2; const offset = (isLeaf ? 1 : -1) * (nodeHalfWidth + this.options.offset); const labelTransform = [ ['translate', offset * Math.cos(radian), offset * Math.sin(radian)], ['rotate', isLeft ? rad2deg(radian) + 180 : rad2deg(radian)], ]; model.updateNodeData([ { id: datum.id, style: { labelTextAlign: isLeft === isLeaf ? 'right' : 'left', labelTextBaseline: 'middle', labelTransform, }, }, ]); }); graph.draw(); } } register(ExtensionCategory.TRANSFORM, 'circular-radial-labels', CircularRadialLabels); const data = { nodes: [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }, { id: '6' }], edges: [ { source: '1', target: '2' }, { source: '2', target: '3' }, { source: '3', target: '4' }, { source: '4', target: '5' }, { source: '5', target: '6' }, { source: '6', target: '1' }, ], }; const graph = new Graph({ container: 'container', width: 600, height: 400, autoFit: 'center', data, node: { style: { labelText: (d) => 'label' + d.id, size: 30, }, }, layout: { type: 'circular', width: 200, center: circularCenter, preLayout: false, // 不能是渲染前布局,否则不生效 }, transforms: ['circular-radial-labels'], }); graph.render(); ``` - **说明** 上面的实现基本是参考内置数据处理器 [PlaceRadialLabels](/zh/manual/transform/PlaceRadialLabels/) 来实现的,区别是这里的实现是通过拿到布局中心来计算偏移和旋转,具体可参考 PlaceRadialLabels 的 [源码](https://github.com/antvis/G6/blob/v5/packages/g6/src/transforms/place-radial-labels.ts) #### 创建边 CreateEdge - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/CreateEdge/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/CreateEdge.md - Description: 创建边 CreateEdge --- title: "创建边 CreateEdge" description: "创建边 CreateEdge" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/CreateEdge/" version: "5.1.1" --- ## 概述 CreateEdge 是 G6 中用于实现画布中交互式创建边(Edge)的内置交互。用户触发交互(点击或拖拽)后,边会随鼠标移动,连接到目标节点即完成创建,若取消则自动移除。 此外,该交互支持自定义边的样式,如颜色、线条样式、箭头等,以适应不同的可视化需求。 该交互支持连接的元素为 `node` 和 `combo`。 ## 使用场景 这一交互主要用于: - 需要交互式创建节点间连接关系的可视化场景,如流程图、知识图谱等 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } }, ], edges: [], combos: [ { id: 'combo1', combo: 'combo2' }, { id: 'combo2', style: {} }, ], }, node: { style: { fill: '#873bf4' } }, edge: { style: { stroke: '#8b9baf' } }, behaviors: [ { type: 'create-edge', key: 'create-edge', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { const options = { key: 'create-edge', type: 'create-edge', animation: true, enable: true, trigger: 'drag', }; const optionFolder = gui.addFolder('CollapseExpand Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'trigger', ['drag', 'click']); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'create-edge', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互 ```javascript // 使用默认配置 const graph = new Graph({ // 其他配置... behaviors: ['create-edge'], // 直接添加,使用默认配置 }); // 或使用自定义配置 const graph = new Graph({ // 其他配置 behaviors: [ { type: 'create-edge', trigger: 'click', // 交互配置,通过点击创建边 style: {}, // 边自定义样式 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | -------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------- | ---- | | type | 交互类型名称 | string | `create-edge` | √ | | trigger | 触发新建边的方式:`click` 表示点击触发;`drag` 表示拖拽触发 | `click` \| `drag` | `drag` | | | enable | 是否启用该交互 | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | onCreate | 创建边回调函数,返回边数据 | (edge: [EdgeData](/zh/manual/data/#边数据edgedata)) => [EdgeData](/zh/manual/data/#边数据edgedata) | - | | | onFinish | 成功创建边回调函数 | (edge: [EdgeData](/zh/manual/data/#边数据edgedata)) => void | - | | | style | 新建边的样式,[配置项](#style) | 见下面 | - | | ### style 配置新创建边的样式,详细配置项请参考 [元素 - 边 - 通用边属性 - 样式](/zh/manual/element/edge/BaseEdge/#style) ```json { "style": { "stroke": "red", "lineWidth": 2 } } ``` ## 代码示例 ### 基础创建边功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['create-edge'], }); ``` ### 自定义创建边功能 ```javascript const graph = new Graph({ // 其他配置, behaviors: [ { type: 'create-edge', style: { stroke: red, lineWidth: 3, }, }, ], }); ``` ### 使用点击创建边 ```javascript const graph = new Graph({ // 其他配置 behaviors: [ { type: 'create-edge', trigger: 'click', }, ], }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, layout: { type: 'grid', }, behaviors: [ { type: 'create-edge', trigger: 'drag', style: { fill: 'red', lineWidth: 2, }, }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 直线边 Line - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/Line/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/Line.md - Description: 直线边 Line --- title: "直线边 Line" description: "直线边 Line" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/Line/" version: "5.1.1" --- ## 概述 直线是最简单的边类型,直接连接两个节点,没有任何弯曲。 使用场景: - 适用于简单的图,如拓扑图、流程图。 - 当需要快速绘制且无需复杂视觉效果时使用。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node1' }, { id: 'node2' }], edges: [{ id: 'edge1', source: 'node1', target: 'node2', text: 'line' }], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, }, }, edge: { style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, }, }, behaviors: ['drag-canvas', 'drag-element'], layout: { type: 'grid', cols: 2 }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { gui.add({ type: 'line' }, 'type').disable(); }, ); ``` 设置 `edge.type` 为 `line` 以使用直线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) ## 示例 ### 内置直线边效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'line', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 椭圆形节点 Ellipse - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Ellipse/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Ellipse.md - Description: 椭圆形节点 Ellipse --- title: "椭圆形节点 Ellipse" description: "椭圆形节点 Ellipse" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Ellipse/" version: "5.1.1" --- ## 概述 椭圆是一个长轴和短轴不对称的几何形状。 适用场景: - 用于表示动态节点、非对称关系或特殊形状。 - 适合表示流程图、网络图或拓扑图。 - 常用于流程图、网络图、拓扑图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }] }, node: { type: 'ellipse' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'ellipse' }, 'type').disable(); const options = { 'size[0]': 80, 'size[1]': 40 }; const optionFolder = gui.addFolder('ellipse.style'); optionFolder.add(options, 'size[0]', 0, 100, 1); optionFolder.add(options, 'size[1]', 0, 100, 1); optionFolder.onChange(({ object }) => { graph.updateNodeData([{ id: 'node1', style: { size: [object['size[0]'], object['size[1]']] } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `ellipse` 以使用椭圆形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) ## 示例 ### 内置椭圆形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'ellipse', style: { size: [45, 35], labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 使用 3D - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/3d/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/3d.md - Description: 使用 3D --- title: "使用 3D" description: "使用 3D" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/3d/" version: "5.1.1" --- ## 安装依赖 在使用 3D 能力之前,请首先安装 3D 扩展包: ```bash npm install @antv/g6-extension-3d --save ``` 该扩展包导出了以下内容: - renderer:3D 渲染器 **元素** - Capsule:胶囊节点 - Cone:圆锥节点 - Cube:立方体节点 - Cylinder:圆柱节点 - Sphere:球体节点 - Torus:圆环节点 - Line3D:3D 线 **布局** - D3Force3DLayout:3D 力导向布局 **交互** - DragCanvas3D:拖拽画布 - ObserveCanvas3D:观察画布 - RollCanvas3D:旋转画布 - ZoomCanvas3D:缩放画布 **插件** - Light:光源 ## 注册扩展 其中下列扩展是必须的: - renderer - 至少一个 3D 节点 - Line3D - Light > renderer 无需注册,实例化 Graph 过程中传入即可。 使用如下方式进行注册: ```ts import { register, ExtensionCategory } from '@antv/g6'; import { Sphere, Line3D, Light } from '@antv/g6-extension-3d'; register(ExtensionCategory.NODE, 'sphere', Sphere); register(ExtensionCategory.EDGE, 'line3d', Line3D); register(ExtensionCategory.PLUGIN, 'light', Light); ``` ## 创建 3D 图 完成上述步骤后,即可创建 3D 图: ```ts import { Graph } from '@antv/g6'; import { renderer } from '@antv/g6-extension-3d'; const graph = new Graph({ // ... 其他配置 // 使用 3D 渲染器 renderer, node: { type: 'sphere', // 使用 3D 节点 style: { materialType: 'phong', // 使用 Phong 材质 }, }, edge: { type: 'line3d', // 使用 3D 边 }, plugins: [ { type: 'light', // 添加光源 // 配置方向光 directional: { direction: [0, 0, 1], }, }, ], }); graph.render(); ``` 你可以参考以下示例: - [精简太阳系](/zh/examples/feature/default/lite-solar-system/) - [3D 力导向布局](/zh/examples/layout/force-directed/3d-force/) ## 其他 `@antv/g6` 中内置注册了 `CameraSetting` 插件,可用于配置相机,具体可参考[插件](https://github.com/antvis/G6/blob/v5/packages/g6/src/plugins/camera-setting.ts)。 ```typescript { plugins: [ { type: 'camera-setting', projectionMode: 'perspective', near: 0.1, far: 1000, fov: 45, aspect: 1, }, ]; } ``` #### 紧凑树布局 CompactBox - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/CompactBoxLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/CompactBoxLayout.md - Description: 紧凑树布局 CompactBox --- title: "紧凑树布局 CompactBox" description: "紧凑树布局 CompactBox" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/CompactBoxLayout/" version: "5.1.1" --- ## 概述 紧凑树布局适用于结构化树形数据的展示,基于经典的 [Reingold–Tilford tidy 布局算法](http://emr.cs.iit.edu/~reingold/tidier-drawings.pdf) 演进而来,通过布局时综合考虑每个树节点的包围盒,有效保持树结构的紧凑性与层次清晰。参考更多 CompactBox 布局[样例](/zh/examples/layout/compact-box/)和[源码](https://github.com/antvis/hierarchy/blob/master/src/compact-box.js) CompactBox 紧凑树布局示例 ## 使用场景 - 决策树: 通过紧凑树布局可简单直观的图形化展示每个决策路径 - 知识图谱: 展示概念之间的层级关系和连接,紧凑布局可以在有限空间内呈现复杂的知识网络 ## 配置方式 ```js const graph = new Graph({ layout: { type: 'compact-box', direction: 'LR', getHeight: () => 16, getWidth: () => 16, getVGap: () => 16, getHGap: () => 40, }, }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------ | ---- | | type | 布局类型 | `compact-box` | - | ✓ | | direction | 布局方向,[可选值](#direction) | `LR` \| `RL` \| `TB` \| `BT` \| `H` \| `V` | `LR` | | | getSide | 设置节点排布在根节点的左侧/右侧,如未设置,则算法自动分配左侧/右侧。注意:该参数仅在 `H` 布局方向上生效 | (d: \{ data?: [NodeData](/zh/manual/data/#节点数据nodedata) \}) => string | | | | getId | 节点 id 的回调函数 | (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => string | | | | getWidth | 计算每个节点的宽度 | (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | | | | getHeight | 计算每个节点的高度 | (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | | | | getHGap | 计算每个节点的水平间隙 | (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | | | | getVGap | 计算每个节点的垂直间隙 | (d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number | | | | radial | 是否启用辐射状布局,[说明](#radial) | boolean | false | | ### direction > `LR` \| `RL` \| `TB` \| `BT` \| `H` \| `V` **Default:** `LR` 树布局方向 - `TB`:根节点在上,往下布局 垂直布局 - `BT`:根节点在下,往上布局 垂直布局 - `LR`:根节点在左,往右布局 水平布局 - `RL`:根节点在右,往左布局 水平布局 - `H`:根节点在中间,水平对称布局。可传入 `getSide` 方法指定每个节点的左右分布逻辑 水平布局 - `V`:根节点在中间,垂直对称布局 垂直布局 ### getSide > _(d: \{ data?: [NodeData](/zh/manual/data/#节点数据nodedata) \}) => string_ 设置节点排布在根节点的左侧/右侧。注意:该参数仅在 `direction` 为 `H` 时生效。如未设置,会默认将子节点前半部分放置在右侧,后半部分放置在左侧,参考 [getSide自动计算逻辑](https://github.com/antvis/hierarchy/blob/d786901874f59d96c47e2a5dfe17b373eefd72e3/src/layout/separate-root.js#L11)。 示例: ```javascript ({ data }) => { // data 是一个节点 if (data.id === 'test-child-id') return 'right'; return 'left'; }; ``` ### getId > _(d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => string_ 节点 id 的回调函数 示例: ```javascript (d) => { // d 是一个节点 return d.id + '_node'; }; ``` ### getWidth > _(d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number_ 每个节点的宽度 示例: ```javascript (d) => { // d 是一个节点 if (d.id === 'testId') return 50; return 100; }; ``` ### getHeight > _(d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number_ 每个节点的高度 示例: ```javascript (d) => { // d 是一个节点 if (d.id === 'testId') return 50; return 100; }; ``` ### getHGap > _(d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number_ 每个节点的水平间隙 示例: ```javascript (d) => { // d 是一个节点 if (d.id === 'testId') return 50; return 100; }; ``` ### getVGap > _(d?: [NodeData](/zh/manual/data/#节点数据nodedata)) => number_ 每个节点的垂直间隙 示例: ```javascript (d) => { // d 是一个节点 if (d.id === 'testId') return 50; return 100; }; ``` ### radial > _boolean_ 是否按照辐射状布局。若 `radial` 为 `true`,建议 `direction` 设置为 `'LR'` 或 `'RL'` img ## 代码示例 ```ts import { Graph, treeToGraphData } from '@antv/g6'; /** * If the node is a leaf node * @param {*} d - node data * @returns {boolean} - whether the node is a leaf node */ function isLeafNode(d) { return !d.children || d.children.length === 0; } fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], node: { style: { labelText: (d) => d.id, labelPlacement: (d) => (isLeafNode(d) ? 'right' : 'left'), labelBackground: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'compact-box', direction: 'LR', getHeight: function getHeight() { return 32; }, getWidth: function getWidth() { return 32; }, getVGap: function getVGap() { return 10; }, getHGap: function getHGap() { return 100; }, }, }); graph.render(); }); ``` #### 边过滤镜 EdgeFilterLens - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/EdgeFilterLens/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/EdgeFilterLens.md - Description: 边过滤镜 EdgeFilterLens --- title: "边过滤镜 EdgeFilterLens" description: "边过滤镜 EdgeFilterLens" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/EdgeFilterLens/" version: "5.1.1" --- ## 概述 边过滤镜插件可以将关注的边保留在过滤镜范围内,其他边将在该范围内不显示。这是一个重要的可视化探索工具,可以帮助用户聚焦于特定区域的边关系。 ## 使用场景 - 需要聚焦查看局部区域的边关系 - 在复杂网络中突出显示特定节点之间的连接 ## 基本用法 以下是一个简单的 EdgeFilterLens 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'edge-filter-lens', trigger: 'pointermove', // 跟随鼠标移动 r: 60, // 设置透镜半径 nodeType: 'both', // 边的显示条件 }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ // 上部疏散区域 { id: 'Myriel', style: { x: 207, y: 78, label: 'Myriel' } }, { id: 'Napoleon', style: { x: 127, y: 62, label: 'Napoleon' } }, { id: 'CountessdeLo', style: { x: 171, y: 47, label: 'CountessdeLo' } }, { id: 'Geborand', style: { x: 106, y: 81, label: 'Geborand' } }, { id: 'Champtercier', style: { x: 247, y: 58, label: 'Champtercier' } }, { id: 'Cravatte', style: { x: 152, y: 50, label: 'Cravatte' } }, // 中上部区域 { id: 'Mlle.Baptistine', style: { x: 205, y: 141, label: 'Mlle.Baptistine' } }, { id: 'Mme.Magloire', style: { x: 275, y: 120, label: 'Mme.Magloire' } }, { id: 'Labarre', style: { x: 246, y: 183, label: 'Labarre' } }, { id: 'Valjean', style: { x: 342, y: 221, label: 'Valjean' } }, { id: 'Marguerite', style: { x: 285, y: 171, label: 'Marguerite' } }, // 中部密集区域 { id: 'Tholomyes', style: { x: 379, y: 158, label: 'Tholomyes' } }, { id: 'Listolier', style: { x: 288, y: 80, label: 'Listolier' } }, { id: 'Fameuil', style: { x: 349, y: 89, label: 'Fameuil' } }, { id: 'Blacheville', style: { x: 381, y: 95, label: 'Blacheville' } }, { id: 'Favourite', style: { x: 264, y: 153, label: 'Favourite' } }, { id: 'Dahlia', style: { x: 323, y: 170, label: 'Dahlia' } }, { id: 'Zephine', style: { x: 306, y: 114, label: 'Zephine' } }, { id: 'Fantine', style: { x: 357, y: 187, label: 'Fantine' } }, // 右侧区域 { id: 'Bamatabois', style: { x: 411, y: 156, label: 'Bamatabois' } }, { id: 'Perpetue', style: { x: 454, y: 195, label: 'Perpetue' } }, { id: 'Simplice', style: { x: 406, y: 227, label: 'Simplice' } }, // 下部区域 { id: 'Cosette', style: { x: 343, y: 248, label: 'Cosette' } }, { id: 'Javert', style: { x: 388, y: 263, label: 'Javert' } }, { id: 'Fauchelevent', style: { x: 397, y: 276, label: 'Fauchelevent' } }, { id: 'Thenardier', style: { x: 317, y: 300, label: 'Thenardier' } }, { id: 'Eponine', style: { x: 268, y: 365, label: 'Eponine' } }, { id: 'Anzelma', style: { x: 234, y: 303, label: 'Anzelma' } }, { id: 'Woman2', style: { x: 304, y: 254, label: 'Woman2' } }, // 最右侧独立节点 { id: 'Gribier', style: { x: 457, y: 160, label: 'Gribier' } }, { id: 'Jondrette', style: { x: 510, y: 327, label: 'Jondrette' } }, ], edges: [ // 上部连接 { id: 'e1', source: 'Myriel', target: 'CountessdeLo' }, { id: 'e2', source: 'Napoleon', target: 'Myriel' }, { id: 'e3', source: 'Geborand', target: 'Napoleon' }, { id: 'e4', source: 'Champtercier', target: 'Myriel' }, { id: 'e5', source: 'Cravatte', target: 'CountessdeLo' }, // 中上部连接 { id: 'e6', source: 'Mlle.Baptistine', target: 'Mme.Magloire' }, { id: 'e7', source: 'Labarre', target: 'Valjean' }, { id: 'e8', source: 'Valjean', target: 'Marguerite' }, { id: 'e9', source: 'Marguerite', target: 'Mme.Magloire' }, // 中部密集连接 { id: 'e10', source: 'Tholomyes', target: 'Listolier' }, { id: 'e11', source: 'Listolier', target: 'Fameuil' }, { id: 'e12', source: 'Fameuil', target: 'Blacheville' }, { id: 'e13', source: 'Blacheville', target: 'Favourite' }, { id: 'e14', source: 'Favourite', target: 'Dahlia' }, { id: 'e15', source: 'Dahlia', target: 'Zephine' }, { id: 'e16', source: 'Zephine', target: 'Fantine' }, { id: 'e17', source: 'Tholomyes', target: 'Fantine' }, { id: 'e18', source: 'Valjean', target: 'Fantine' }, // 右侧连接 { id: 'e19', source: 'Bamatabois', target: 'Perpetue' }, { id: 'e20', source: 'Perpetue', target: 'Simplice' }, { id: 'e21', source: 'Bamatabois', target: 'Gribier' }, // 下部连接 { id: 'e22', source: 'Valjean', target: 'Cosette' }, { id: 'e23', source: 'Cosette', target: 'Javert' }, { id: 'e24', source: 'Javert', target: 'Fauchelevent' }, { id: 'e25', source: 'Fauchelevent', target: 'Thenardier' }, { id: 'e26', source: 'Thenardier', target: 'Eponine' }, { id: 'e27', source: 'Eponine', target: 'Anzelma' }, { id: 'e28', source: 'Woman2', target: 'Cosette' }, // 跨区域连接 { id: 'e29', source: 'Fantine', target: 'Bamatabois' }, { id: 'e30', source: 'Javert', target: 'Bamatabois' }, { id: 'e31', source: 'Simplice', target: 'Jondrette' }, { id: 'e32', source: 'Thenardier', target: 'Jondrette' }, { id: 'e33', source: 'Favourite', target: 'Valjean' }, { id: 'e34', source: 'Tholomyes', target: 'Cosette' }, ], }, node: { style: { label: true, size: 16, }, palette: { field: (datum) => Math.floor(datum.style?.y / 60), }, }, edge: { style: { label: true, labelText: (d) => d.data.value?.toString(), stroke: '#ccc', endArrow: true, endArrowType: 'triangle', }, }, plugins: [ { type: 'edge-filter-lens', key: 'edge-filter-lens', r: 80, trigger: 'pointermove', }, ], }, { width: 600, height: 400 }, (gui, graph) => { const TRIGGER_TYPES = ['pointermove', 'click', 'drag']; const NODE_TYPES = ['both', 'source', 'target', 'either']; const options = { type: 'edge-filter-lens', r: 80, // 透镜半径 trigger: 'pointermove', // 触发方式 nodeType: 'both', // 边显示条件 minR: 50, // 最小半径 maxR: 150, // 最大半径 scaleRBy: 'wheel', // 缩放方式 style: { fill: '#f0f5ff', fillOpacity: 0.4, stroke: '#1d39c4', strokeOpacity: 0.8, lineWidth: 1.5, }, nodeStyle: { size: 35, fill: '#d6e4ff', stroke: '#2f54eb', lineWidth: 2, labelFontSize: 14, labelFontWeight: 'bold', labelFill: '#1d39c4', }, edgeStyle: { stroke: '#1d39c4', lineWidth: 2, strokeOpacity: 0.8, }, }; const optionFolder = gui.addFolder('Edge Filter Lens Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'r', 50, 150, 5); optionFolder.add(options, 'trigger', TRIGGER_TYPES); optionFolder.add(options, 'nodeType', NODE_TYPES); optionFolder.add(options, 'minR', 20, 100, 5); optionFolder.add(options, 'maxR', 100, 200, 5); optionFolder.onChange(({ property, value }) => { if (property.includes('.')) { const [group, prop] = property.split('.'); graph.updatePlugin({ key: 'edge-filter-lens', [group]: { ...options[group], [prop]: value, }, }); } else { graph.updatePlugin({ key: 'edge-filter-lens', [property]: value, }); } graph.render(); }); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | ---- | | type | 插件类型 | string | `edge-filter-lens` | ✓ | | key | 插件的唯一标识,可用于获取插件实例或更新插件选项 | string | - | | | trigger | 移动透镜的方式:
- `pointermove`:透镜始终跟随鼠标移动
- `click`:点击画布时移动透镜到点击位置
- `drag`:通过拖拽方式移动透镜 | `pointermove` \| `click` \| `drag` | `pointermove` | | | r | 透镜的半径 | number | 60 | | | maxR | 透镜的最大半径 | number | 画布宽高最小值的一半 | | | minR | 透镜的最小半径 | number | 0 | | | scaleRBy | 缩放透镜半径的方式:`wheel`:通过滚轮缩放透镜的半径 | `wheel` | - | | | nodeType | 边显示的条件:
- `both`:只有起始节点和目标节点都在透镜中时,边才会显示
- `source`:只有起始节点在透镜中时,边才会显示
- `target`:只有目标节点在透镜中时,边才会显示
- `either`:只要起始节点或目标节点有一个在透镜中时,边就会显示 | `both` \| `source` \| `target` \| `either` | `both` | | | filter | 过滤出始终不在透镜中显示的元素 | (id: string, elementType: `node` \| `edge` \| `combo`) => boolean | () => true | | | style | 透镜的样式,[配置项](#style) | object | | | | nodeStyle | 在透镜中节点的样式 | [NodeStyle](/zh/manual/element/node/BaseNode/#style) \| ((datum: [NodeData](/zh/manual/data/#节点数据nodedata)) => [NodeStyle](/zh/manual/element/node/BaseNode/#style)) | `{ label: false }` | | | edgeStyle | 在透镜中边的样式 | [EdgeStyle](/zh/manual/element/edge/BaseEdge/#style) \| ((datum: [EdgeData](/zh/manual/data/#边数据edgedata)) => [EdgeStyle](/zh/manual/element/edge/BaseEdge/#style)) | `{ label: true }` | | | preventDefault | 是否阻止默认事件 | boolean | true | | ### style 圆形透镜的样式属性。 | 属性 | 描述 | 类型 | 默认值 | | ------------- | --------------- | ----------------------------- | ------ | | fill | 填充颜色 | string \| Pattern \| null | `#fff` | | stroke | 描边颜色 | string \| Pattern \| null | `#000` | | opacity | 整体透明度 | number \| string | 1 | | fillOpacity | 填充透明度 | number \| string | 0.8 | | strokeOpacity | 描边透明度 | number \| string | - | | lineWidth | 线宽度 | number \| string | 2 | | lineCap | 线段端点样式 | `butt` \| `round` \| `square` | - | | lineJoin | 线段连接处样式 | `miter` \| `round` \| `bevel` | - | | shadowColor | 阴影颜色 | string | - | | shadowBlur | 阴影模糊程度 | number | - | | shadowOffsetX | 阴影 X 方向偏移 | number | - | | shadowOffsetY | 阴影 Y 方向偏移 | number | - | 完整样式属性参考 [元素 -节点 - 内置节点 - 通用样式属性 - style](/zh/manual/element/node/BaseNode/#style) ## 代码示例 ### 基础用法 最简单的配置方式: ```js const graph = new Graph({ plugins: ['edge-filter-lens'], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 300, data: { nodes: [ // 上部疏散区域 { id: 'node1', style: { x: 150, y: 60, label: 'Node 1' } }, { id: 'node2', style: { x: 100, y: 40, label: 'Node 2' } }, { id: 'node3', style: { x: 200, y: 35, label: 'Node 3' } }, { id: 'node4', style: { x: 150, y: 30, label: 'Node 4' } }, // 中部区域 { id: 'node5', style: { x: 220, y: 140, label: 'Node 5' } }, { id: 'node6', style: { x: 280, y: 160, label: 'Node 6' } }, { id: 'node7', style: { x: 220, y: 120, label: 'Node 7' } }, { id: 'node8', style: { x: 260, y: 100, label: 'Node 8' } }, { id: 'node9', style: { x: 240, y: 130, label: 'Node 9' } }, { id: 'node10', style: { x: 300, y: 110, label: 'Node 10' } }, // 下部区域 { id: 'node11', style: { x: 240, y: 200, label: 'Node 11' } }, { id: 'node12', style: { x: 280, y: 220, label: 'Node 12' } }, { id: 'node13', style: { x: 300, y: 190, label: 'Node 13' } }, { id: 'node14', style: { x: 320, y: 210, label: 'Node 14' } }, ], edges: [ // 上部连接 { id: 'edge1', source: 'node1', target: 'node2' }, { id: 'edge2', source: 'node2', target: 'node3' }, { id: 'edge3', source: 'node3', target: 'node4' }, // 中部连接 { id: 'edge4', source: 'node5', target: 'node6' }, { id: 'edge5', source: 'node6', target: 'node7' }, { id: 'edge6', source: 'node7', target: 'node8' }, { id: 'edge7', source: 'node8', target: 'node9' }, { id: 'edge8', source: 'node9', target: 'node10' }, // 下部连接 { id: 'edge9', source: 'node11', target: 'node12' }, { id: 'edge10', source: 'node12', target: 'node13' }, { id: 'edge11', source: 'node13', target: 'node14' }, // 跨区域连接 { id: 'edge12', source: 'node4', target: 'node8' }, { id: 'edge13', source: 'node7', target: 'node11' }, { id: 'edge14', source: 'node10', target: 'node13' }, ], }, node: { style: { size: 20, }, }, plugins: ['edge-filter-lens'], }); graph.render(); ``` ### 自定义样式 可以自定义透镜的外观和行为: ```js const graph = new Graph({ plugins: [ { type: 'edge-filter-lens', r: 80, style: { fill: '#f0f5ff', // 透镜区域的填充颜色 fillOpacity: 0.6, // 填充区域的透明度 stroke: '#7e3feb', // 透镜边框改为紫色 strokeOpacity: 0.8, // 边框的透明度 lineWidth: 1.5, // 边框的线宽 }, nodeStyle: { size: 24, // 放大节点 fill: '#7e3feb', // 紫色填充 stroke: '#5719c9', // 深紫色描边 lineWidth: 1, // 细边框 label: true, // 显示标签 labelFill: '#ffffff', // 白色文字 labelFontSize: 14, // 放大文字 labelFontWeight: 'bold', // 文字加粗 }, edgeStyle: { stroke: '#8b9baf', // 灰色边 lineWidth: 2, // 加粗边线 label: true, // 显示标签 labelFill: '#5719c9', // 深紫色文字 opacity: 0.8, // 适当的透明度 }, }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 300, data: { nodes: [ // 上部疏散区域 { id: 'node1', style: { x: 150, y: 60, label: 'Node 1' } }, { id: 'node2', style: { x: 100, y: 40, label: 'Node 2' } }, { id: 'node3', style: { x: 200, y: 35, label: 'Node 3' } }, { id: 'node4', style: { x: 150, y: 30, label: 'Node 4' } }, // 中部区域 { id: 'node5', style: { x: 220, y: 140, label: 'Node 5' } }, { id: 'node6', style: { x: 280, y: 160, label: 'Node 6' } }, { id: 'node7', style: { x: 220, y: 120, label: 'Node 7' } }, { id: 'node8', style: { x: 260, y: 100, label: 'Node 8' } }, { id: 'node9', style: { x: 240, y: 130, label: 'Node 9' } }, { id: 'node10', style: { x: 300, y: 110, label: 'Node 10' } }, // 下部区域 { id: 'node11', style: { x: 240, y: 200, label: 'Node 11' } }, { id: 'node12', style: { x: 280, y: 220, label: 'Node 12' } }, { id: 'node13', style: { x: 300, y: 190, label: 'Node 13' } }, { id: 'node14', style: { x: 320, y: 210, label: 'Node 14' } }, ], edges: [ // 上部连接 { id: 'edge1', source: 'node1', target: 'node2' }, { id: 'edge2', source: 'node2', target: 'node3' }, { id: 'edge3', source: 'node3', target: 'node4' }, // 中部连接 { id: 'edge4', source: 'node5', target: 'node6' }, { id: 'edge5', source: 'node6', target: 'node7' }, { id: 'edge6', source: 'node7', target: 'node8' }, { id: 'edge7', source: 'node8', target: 'node9' }, { id: 'edge8', source: 'node9', target: 'node10' }, // 下部连接 { id: 'edge9', source: 'node11', target: 'node12' }, { id: 'edge10', source: 'node12', target: 'node13' }, { id: 'edge11', source: 'node13', target: 'node14' }, // 跨区域连接 { id: 'edge12', source: 'node4', target: 'node8' }, { id: 'edge13', source: 'node7', target: 'node11' }, { id: 'edge14', source: 'node10', target: 'node13' }, ], }, node: { style: { size: 20, }, }, edge: { style: { stroke: '#91d5ff', lineWidth: 1, }, }, plugins: [ { type: 'edge-filter-lens', r: 80, style: { fill: '#f0f5ff', // 透镜区域的填充颜色 fillOpacity: 0.6, // 填充区域的透明度 stroke: '#7e3feb', // 透镜边框改为紫色 strokeOpacity: 0.8, // 边框的透明度 lineWidth: 1.5, // 边框的线宽 }, nodeStyle: { size: 24, // 放大节点 fill: '#7e3feb', // 紫色填充 stroke: '#5719c9', // 深紫色描边 lineWidth: 1, // 细边框 label: true, // 显示标签 labelFill: '#ffffff', // 白色文字 labelFontSize: 14, // 放大文字 labelFontWeight: 'bold', // 文字加粗 }, edgeStyle: { stroke: '#8b9baf', // 灰色边 lineWidth: 2, // 加粗边线 label: true, // 显示标签 labelFill: '#5719c9', // 深紫色文字 opacity: 0.8, // 适当的透明度 }, }, ], }); graph.render(); ``` ## 实际案例 - [边过滤镜](/zh/examples/plugin/edge-filter-lens/basic/) ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 拖拽画布 DragCanvas - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/DragCanvas/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/DragCanvas.md - Description: 拖拽画布 DragCanvas --- title: "拖拽画布 DragCanvas" description: "拖拽画布 DragCanvas" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/DragCanvas/" version: "5.1.1" --- ## 概述 DragCanvas 是 G6 中用于实现画布拖拽功能的内置交互,支持通过鼠标或触摸屏幕拖动来平移整个画布。这是图可视化中最基础且常用的导航交互,让用户能够自由探索超出当前视口的图内容。 ## 使用场景 这一交互主要用于: - 导航和浏览大型图表,查看当前视口外的内容 - 调整视图焦点,将感兴趣的区域移动到视口中心 - 与缩放交互结合,实现完整的画布导航体验 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node-1' }] }, layout: { type: 'force' }, behaviors: [ { type: 'drag-canvas', key: 'drag-canvas', }, ], node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'drag-canvas', type: 'drag-canvas', enable: true, sensitivity: 1, trigger: 'Use cursor by default', }; const optionFolder = gui.addFolder('ZoomCanvas Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'enable'); optionFolder.add(options, 'sensitivity', 0, 10, 1); optionFolder.add(options, 'trigger', { 'Use cursor by default': [], 'Shift+Arrow Key': { up: ['Shift', 'ArrowUp'], down: ['Shift', 'ArrowDown'], left: ['Shift', 'ArrowLeft'], right: ['Shift', 'ArrowRight'], }, }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'drag-canvas', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-canvas'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-canvas', key: 'drag-canvas-1', direction: 'x', // 只允许水平方向拖拽 key: 'drag-behavior', // 为交互指定标识符,方便动态更新 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ---- | | type | 交互类型名称 | string | `drag-canvas` | ✓ | | enable | 是否启用该交互 | boolean \| ((event: [Event](/zh/api/event/#事件对象属性) \| [KeyboardEvent](https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent)) => boolean) | `(event) => 'eventType' in event ? event.targetType === 'canvas': true`(仅在点击画布时启用) | | | animation | 拖拽动画配置,仅在使用按键移动时有效 | [ViewportAnimationEffectTiming](/zh/api/graph/#viewportanimationeffecttiming) | - | | | direction | 允许的拖拽方向,可选值有:
- 设为 `'both'`(默认):允许在任意方向拖拽
- 设为 `'x'`:只允许水平方向拖拽
- 设为 `'y'`:只允许垂直方向拖拽 | `'x'` \| `'y'` \| `'both'` | `'both'` (不限制方向) | | | range | 可拖拽的视口范围(以视口大小为单位),[示例](#range) | number \| number[] | Infinity | | | sensitivity | 触发一次按键移动的距离 | number | 10 | | | trigger | 触发拖拽的键盘按键,[示例](#trigger) | object | - | | | onFinish | 拖拽完成时的回调函数 | () => void | - | | ### range `range` 用于控制画布可拖拽的范围: - 设置为单个数字:四个方向使用相同的值 - 设置为数组:分别指定 [上, 右, 下, 左] 四个方向的范围 例如: ```javascript range: 2; // 在任何方向上都可以拖拽2个视口的距离 range: [1, 2, 1, 2]; // 上下方向可拖拽1个视口,左右方向可拖拽2个视口 ``` 每个方向的取值范围是 [0, Infinity],0表示不能拖拽,Infinity表示无限拖拽。 ### trigger `trigger` 允许你配置键盘按键来控制画布移动: ```javascript { trigger: { up: ['ArrowUp'], // 向上移动的快捷键 down: ['ArrowDown'], // 向下移动的快捷键 left: ['ArrowLeft'], // 向左移动的快捷键 right: ['ArrowRight'] // 向右移动的快捷键 } } ``` 你也可以配置组合键: ```javascript { trigger: { up: ['Control', 'ArrowUp'], // Ctrl + 上箭头 down: ['Control', 'ArrowDown'], // Ctrl + 下箭头 left: ['Control', 'ArrowLeft'], // Ctrl + 左箭头 right: ['Control', 'ArrowRight'] // Ctrl + 右箭头 } } ``` ## 代码示例 ### 基础拖拽功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['drag-canvas'], }); ``` ### 只允许水平拖拽 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-canvas', direction: 'x', // 只允许水平拖拽 }, ], }); ``` ### 限制拖拽范围 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-canvas', range: 1.5, // 限制拖拽范围为1.5个视口大小 }, ], }); ``` ### 使用键盘方向键控制移动 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-canvas', trigger: { up: ['ArrowUp'], down: ['ArrowDown'], left: ['ArrowLeft'], right: ['ArrowRight'], }, animation: { duration: 100, // 添加平滑动画效果 }, }, ], }); ``` ## 常见问题 ### 1. DragCanvas与其他交互的区别 - `DragCanvas` 用于拖拽整个画布视图 - `DragElement` 用于拖拽单个图元素(节点/边/组合) - `ScrollCanvas` 用于滚轮滚动画布,不改变缩放比例 ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, behaviors: ['drag-canvas'], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 折线边 Polyline - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/Polyline/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/Polyline.md - Description: 折线边 Polyline --- title: "折线边 Polyline" description: "折线边 Polyline" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/Polyline/" version: "5.1.1" --- ## 概述 折线是由多条直线段组成的边,适合在复杂布局中绕过障碍物连接节点。 使用场景: - 适用于复杂布局的图,如电路图、管道图。 - 当需要绕过其他节点或障碍物时使用。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', style: { x: 150, y: 150 }, }, { id: 'node2', style: { x: 400, y: 150, labelText: 'Drag Me!', labelPadding: [1, 5], labelBackground: true, labelBackgroundRadius: 10, labelBackgroundFill: '#99add1', }, }, ], edges: [ { id: 'edge1', source: 'node1', target: 'node2', text: 'polyline', }, ], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, }, }, edge: { type: 'polyline', style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, router: { type: 'orth' }, }, }, behaviors: ['drag-canvas', 'drag-element'], plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { gui.add({ type: 'polyline' }, 'type').disable(); let index = 3; const options = { radius: 0, router: { type: 'orth', }, random: () => { const x = Math.floor(Math.random() * 600); const y = Math.floor(Math.random() * 300); graph.addNodeData([ { id: `node-${index}`, style: { size: 5, fill: '#7e3feb', x, y, }, }, ]); index++; graph.updateEdgeData((prev) => { const targetEdgeData = prev.find((edge) => edge.id === 'edge1'); const controlPoints = [...(targetEdgeData.style.controlPoints || [])]; controlPoints.push([x, y]); return [{ ...targetEdgeData, style: { ...targetEdgeData.style, controlPoints } }]; }); graph.render(); }, }; const optionFolder = gui.addFolder('polyline.style'); optionFolder.add(options, 'radius', 0, 100, 1); optionFolder.add(options, 'router'); optionFolder.add(options, 'random').name('Add random node as control points'); optionFolder.onChange(({ property, value }) => { if (property === 'random') return; graph.updateEdgeData([{ id: 'edge1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `edge.type` 为 `polyline` 以使用折线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | -------------------------------- | --------------------------------------------------------------------------------------- | ------ | ---- | | controlPoints | 控制点数组,用于定义折线的转折点 | [Point](#point)[] | [] | | | radius | 转折点圆角半径 | number | 0 | | | router | 是否启用路由 | false | [OrthRouter](#orthrouter) | [ShortestPathRouter](#shortestpathrouter) | false | | ### OrthRouter | 属性 | 描述 | 类型 | 默认值 | | ------- | ---------------------------------------------------------------------- | ------------------- | ------ | | type | 正交路由,通过在路径上添加额外的控制点,使得边的每一段都保持水平或垂直 | `'orth'` | - | | padding | 节点连接点与转角的最小距离 | [Padding](#padding) | `0` | ### ShortestPathRouter | 属性 | 描述 | 类型 | 默认值 | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------ | | type | 最短路径路由,是正交路由 `'orth'` 的智能版本。该路由由水平或垂直的正交线段组成。采用 A\* 算法计算最短路径,并支持自动避开路径上的其他节点(障碍) | `'shortest-path'` | - | | offset | 节点锚点与转角的最小距离 | [Padding](#padding) | 0 | | gridSize | grid 格子大小 | number | 0 | | maxAllowedDirectionChange | 支持的最大旋转角度(弧度) | number | 0 | | startDirections | 节点的可能起始方向 | [Direction](#direction)[] | 0 | | endDirections | 节点的可能结束方向 | [Direction](#direction)[] | 0 | | directionMap | 指定可移动的方向 | \{ [key in [Direction](#direction)]: \{ stepX: number; stepY: number \} \} | 0 | | penalties | 表示在路径搜索过程中某些路径的额外代价。key 为弧度值,value 为代价 | \{ [key: string]: number \} | 0 | | distFunc | 指定计算两点之间距离的函数 | (p1: [Point](#point), p2: [Point](#point)) => number | 0 | | maximumLoops | 最大迭代次数 | number | 0 | | enableObstacleAvoidance | 是否开启避障 | boolean | false | #### Direction ```typescript type Direction = 'left' | 'right' | 'top' | 'bottom'; ``` #### Point ```typescript type Point = [number, number] | [number, number, number] | Float32Array; ``` #### Padding ```typescript type Padding = number | [number, number] | [number, number, number, number]; ``` ## 示例 ### 内置折线边效果 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 200, y: 200 } }, { id: 'node-2', style: { x: 350, y: 120 } }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2', controlPoints: [[300, 190]], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'polyline', style: { controlPoints: (d) => d.controlPoints, }, }, behaviors: [{ type: 'drag-element' }], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 二次贝塞尔曲线边 Quadratic - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/Quadratic/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/Quadratic.md - Description: 二次贝塞尔曲线边 Quadratic --- title: "二次贝塞尔曲线边 Quadratic" description: "二次贝塞尔曲线边 Quadratic" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/Quadratic/" version: "5.1.1" --- ## 概述 二次贝塞尔曲线是一种平滑的曲线,其形状由起点、终点和一个控制点决定。 使用场景: - 适用于中等复杂度的图,如关系图、网络图。 - 当需要平滑连接节点且计算资源有限时使用。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node1' }, { id: 'node2' }], edges: [{ id: 'edge1', source: 'node1', target: 'node2', text: 'quadratic' }], }, node: { style: { fill: '#f8f8f8', stroke: '#8b9baf', lineWidth: 1, }, }, edge: { type: 'quadratic', style: { stroke: '#7e3feb', lineWidth: 2, labelText: (d) => d.text, labelBackground: true, labelBackgroundFill: '#f9f0ff', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 2, labelBackgroundStroke: '#7e3feb', labelPadding: [1, 10], labelBackgroundRadius: 4, }, }, behaviors: ['drag-canvas', 'drag-element'], layout: { type: 'grid', cols: 2 }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { gui.add({ type: 'quadratic' }, 'type').disable(); const options = { curveOffset: 30, curvePosition: 0.5, }; const optionFolder = gui.addFolder('quadratic.style'); optionFolder.add(options, 'curveOffset', 0, 100); optionFolder.add(options, 'curvePosition', 0, 1); optionFolder.onChange(({ property, value }) => { graph.updateEdgeData([{ id: 'edge1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `edge.type` 为 `quadratic` 以使用曲线。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseEdge](/zh/manual/element/edge/BaseEdge/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | -------------------------------------------------------------------------------------------------- | --------------- | ------ | ---- | | controlPoints | 控制点数组,用于定义曲线的形状。如果不指定,将会通过 `curveOffset` 和 `curvePosition` 来计算控制点 | [Point](#point) | - | | | curvePosition | 控制点在两端点连线上的相对位置,范围为`0-1` | number | 0.5 | | | curveOffset | 控制点距离两端点连线的距离,可理解为控制边的弯曲程度 | number | 30 | | #### Point ```typescript type Point = [number, number] | [number, number, number] | Float32Array; ``` ## 示例 ### 内置二次贝塞尔曲线边效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'quadratic', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 六边形节点 Hexagon - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Hexagon/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Hexagon.md - Description: 六边形节点 Hexagon --- title: "六边形节点 Hexagon" description: "六边形节点 Hexagon" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Hexagon/" version: "5.1.1" --- ## 概述 六边形是一个六边相等的几何形状,具有蜂窝状结构。 适用场景: - 用于表示蜂窝网络、分子结构或紧密排列的节点。 - 适合表示网络拓扑、分子图或游戏地图。 - 常用于网络图、拓扑图、游戏设计等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }] }, node: { type: 'hexagon' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'hexagon' }, 'type').disable(); const options = { size: 40, outerR: 0, }; const optionFolder = gui.addFolder('hexagon.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'outerR', 0, 100); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `hexagon` 以使用六边形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | ---------------------------------------- | ------ | ------------------------ | ---- | | outerR | 外半径,是指从六边形中心到任意顶点的距离 | number | 默认为宽高的最小值的一半 | | ## 示例 ### 内置六边形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'hexagon', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], outerR: 30, // 外半径 portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 项目打包 - Canonical page: https://g6.antv.antgroup.com/zh/manual/further-reading/bundle/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/further-reading/bundle.md - Description: 项目打包 --- title: "项目打包" description: "项目打包" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/further-reading/bundle/" version: "5.1.1" --- 通常情况下,如果你使用的现代构建工具,如 Webpack、Rollup 或 ESBuild,你可以很容易地构建依赖于 `@antv/g6` 的项目。 一些构建工具例如 Vite,其底层是使用 ESBuild,因此你可以参考 ESBuild 的配置。 下面是一些示例配置,你可以参考这些配置来构建你的项目。如果你发现这些配置无法正常工作,请确保你的构建工具版本较新。 ## 使用 Webpack 打包项目 1. 确保你的项目中已经安装了 `webpack` 和 `webpack-cli`: ```bash npm install webpack webpack-cli --save-dev ``` 2. 参考下面的 `webpack.config.js` 进行配置: ```js const path = require('path'); module.exports = { entry: './src/index.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js', }, mode: 'production', }; ``` 3. 执行构建命令: ```bash npx webpack ``` > 上述配置在:"webpack": "^5.94.0","webpack-cli": "^5.1.4" 可以正常工作。 :::error{title=Webpack4} ⚠️ 强烈建议项目使用 Webpack 5,如果你使用的是 Webpack 4,按以下步骤配置: 1. 安装相关依赖:babel-loader(<9)、@babel/preset-env、@open-wc/webpack-import-meta-loader > 如果你使用的 typescript,还需要安装 ts-loader ```bash npm install babel-loader@8 @babel/preset-env @open-wc/webpack-import-meta-loader --save-dev ``` 2. 修改 `webpack.config.js` 配置: ```js module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js', }, module: { rules: [ { test: /\.js$/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, { test: /\.js$/, loader: '@open-wc/webpack-import-meta-loader', }, ], }, mode: 'production', }; ``` ::: > 如果你使用的是 vue-cli,请移除 mode: 'production' 配置,否则可能会影响开发模式下的构建性能。 ## 使用 Rollup 打包项目 1. 首先,确保你的项目中已经安装了 `rollup` 及必要的插件: - `@rollup/plugin-commonjs`:用于加载 CommonJS 模块 - `@rollup/plugin-node-resolve`:用于加载 Node.js 模块 ```bash npm install rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve --save-dev ``` 2. 参考下面的 `rollup.config.js` 进行配置: ```js const commonjs = require('@rollup/plugin-commonjs'); const resolve = require('@rollup/plugin-node-resolve'); module.exports = { input: 'src/index.ts', output: { file: 'dist/index.js', format: 'umd', name: 'project', }, plugins: [resolve(), commonjs()], }; ``` 3. 执行构建命令: ```bash npx rollup -c ``` ## 使用 ESBuild 打包项目 1. 首先,确保你的项目中已经安装了 `esbuild`: ```bash npm install esbuild --save-dev ``` 2. 执行构建命令: ```bash npx esbuild src/index.ts --bundle --outfile=dist/index.js ``` #### 同心圆布局 Concentric - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/ConcentricLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/ConcentricLayout.md - Description: 同心圆布局 Concentric --- title: "同心圆布局 Concentric" description: "同心圆布局 Concentric" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/ConcentricLayout/" version: "5.1.1" --- ## 概述 同心圆布局是一种将节点根据某种排序规则分层,并以圆心为中心、沿圆周排列每层节点的布局方式。参考更多同心圆布局[样例](/zh/examples/layout/concentric/)或[源码](https://github.com/antvis/layout/blob/v5/packages/layout/src/circular.ts)。 ## 使用场景 - 分层数据可视化,如权限控制结构、组织架构图等,中心是顶级角色,外圈为下级节点。 - 排序分析结果可视化,高重要度放中心,低重要度放外围,快速表达图中节点的相对影响力。 ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ---------------- | ---- | | type | 布局类型 | `concentric` | - | ✓ | | center | 圆形布局的中心位置,默认为当前容器的中心位置 | [number, number] \| [number, number, number] | - | | | clockwise | 是否按照顺时针排列 | boolean | false | | equidistant | 环与环之间的距离是否相等 | boolean | false | | | width | 布局的宽度,默认使用容器宽度 | number | - | | | height | 布局的高度,默认使用容器高度 | number | - | | | sortBy | 指定排序的依据(节点属性名)
数值越高则该节点被放置得越中心。若为 degree,则会计算节点的度数,度数越高,节点将被放置得越中心 | string | `degree` | | | maxLevelDiff | 同一层节点的最大属性差值
若为 undefined,则将会被设置为 maxValue / 4 ,其中 maxValue 为最大的排序依据的属性值。例如,若 sortBy 为 'degree',则 maxValue 为所有节点中度数最大的节点的度数 | number | undefined | | | nodeSize | 节点大小(直径)。用于防止节点重叠时的碰撞检测 | number \| number[] \| ((nodeData: Node) => number) | 30 | | | nodeSpacing | 环与环之间最小间距,用于调整半径 | number \| number[] \| ((node?: Node) => number) | 10 | | | preventOverlap | 是否防止重叠
必须配合 nodeSize 属性或节点数据中的 data.size 属性,只有在数据中设置了 data.size 或在该布局中配置了与当前图节点大小相同的 nodeSize 值,才能够进行节点重叠的碰撞检测 | boolean | false | | | startAngle | 开始布局节点的弧度 | number | 3 / 2 \* Math.PI | | | sweep | 同一层中第一个节点与最后一个节点之间的弧度差
若为 undefined ,则将会被设置为 2 \* Math.PI \* (1 - 1 / \|level.nodes\|) ,其中 level.nodes 为该算法计算出的每一层的节点,\|level.nodes\| 代表该层节点数量 | number | undefined | | ## 代码示例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 500, height: 250, autoFit: 'view', data: { nodes: [ { id: 'center', data: { label: '中心', level: 0 } }, { id: 'level1-0', data: { label: 'L1-0', level: 1 } }, { id: 'level1-1', data: { label: 'L1-1', level: 1 } }, { id: 'level1-2', data: { label: 'L1-2', level: 1 } }, { id: 'level1-3', data: { label: 'L1-3', level: 1 } }, { id: 'level1-4', data: { label: 'L1-4', level: 1 } }, { id: 'level1-5', data: { label: 'L1-5', level: 1 } }, { id: 'level2-0', data: { label: 'L2-0', level: 2 } }, { id: 'level2-1', data: { label: 'L2-1', level: 2 } }, { id: 'level2-2', data: { label: 'L2-2', level: 2 } }, { id: 'level2-3', data: { label: 'L2-3', level: 2 } }, { id: 'level2-4', data: { label: 'L2-4', level: 2 } }, { id: 'level2-5', data: { label: 'L2-5', level: 2 } }, { id: 'level2-6', data: { label: 'L2-6', level: 2 } }, { id: 'level2-7', data: { label: 'L2-7', level: 2 } }, { id: 'level2-8', data: { label: 'L2-8', level: 2 } }, { id: 'level2-9', data: { label: 'L2-9', level: 2 } }, { id: 'level2-10', data: { label: 'L2-10', level: 2 } }, { id: 'level2-11', data: { label: 'L2-11', level: 2 } }, ], edges: [ { id: 'e-center-level1-0', source: 'center', target: 'level1-0' }, { id: 'e-center-level1-1', source: 'center', target: 'level1-1' }, { id: 'e-center-level1-2', source: 'center', target: 'level1-2' }, { id: 'e-center-level1-3', source: 'center', target: 'level1-3' }, { id: 'e-center-level1-4', source: 'center', target: 'level1-4' }, { id: 'e-center-level1-5', source: 'center', target: 'level1-5' }, { id: 'e-level1-0-level2-0', source: 'level1-0', target: 'level2-0' }, { id: 'e-level1-0-level2-1', source: 'level1-0', target: 'level2-1' }, { id: 'e-level1-1-level2-2', source: 'level1-1', target: 'level2-2' }, { id: 'e-level1-1-level2-3', source: 'level1-1', target: 'level2-3' }, { id: 'e-level1-2-level2-4', source: 'level1-2', target: 'level2-4' }, { id: 'e-level1-2-level2-5', source: 'level1-2', target: 'level2-5' }, { id: 'e-level1-3-level2-6', source: 'level1-3', target: 'level2-6' }, { id: 'e-level1-3-level2-7', source: 'level1-3', target: 'level2-7' }, { id: 'e-level1-4-level2-8', source: 'level1-4', target: 'level2-8' }, { id: 'e-level1-4-level2-9', source: 'level1-4', target: 'level2-9' }, { id: 'e-level1-5-level2-10', source: 'level1-5', target: 'level2-10' }, { id: 'e-level1-5-level2-11', source: 'level1-5', target: 'level2-11' }, ], }, layout: { type: 'concentric', nodeSize: 32, sortBy: 'degree', preventOverlap: true, }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], animation: false, }); graph.render(); ```
展开查看完整代码 ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', autoFit: 'view', data: { nodes: [ { id: 'center', data: { label: '中心', level: 0 } }, { id: 'level1-0', data: { label: 'L1-0', level: 1 } }, { id: 'level1-1', data: { label: 'L1-1', level: 1 } }, { id: 'level1-2', data: { label: 'L1-2', level: 1 } }, { id: 'level1-3', data: { label: 'L1-3', level: 1 } }, { id: 'level1-4', data: { label: 'L1-4', level: 1 } }, { id: 'level1-5', data: { label: 'L1-5', level: 1 } }, { id: 'level2-0', data: { label: 'L2-0', level: 2 } }, { id: 'level2-1', data: { label: 'L2-1', level: 2 } }, { id: 'level2-2', data: { label: 'L2-2', level: 2 } }, { id: 'level2-3', data: { label: 'L2-3', level: 2 } }, { id: 'level2-4', data: { label: 'L2-4', level: 2 } }, { id: 'level2-5', data: { label: 'L2-5', level: 2 } }, { id: 'level2-6', data: { label: 'L2-6', level: 2 } }, { id: 'level2-7', data: { label: 'L2-7', level: 2 } }, { id: 'level2-8', data: { label: 'L2-8', level: 2 } }, { id: 'level2-9', data: { label: 'L2-9', level: 2 } }, { id: 'level2-10', data: { label: 'L2-10', level: 2 } }, { id: 'level2-11', data: { label: 'L2-11', level: 2 } }, ], edges: [ { id: 'e-center-level1-0', source: 'center', target: 'level1-0' }, { id: 'e-center-level1-1', source: 'center', target: 'level1-1' }, { id: 'e-center-level1-2', source: 'center', target: 'level1-2' }, { id: 'e-center-level1-3', source: 'center', target: 'level1-3' }, { id: 'e-center-level1-4', source: 'center', target: 'level1-4' }, { id: 'e-center-level1-5', source: 'center', target: 'level1-5' }, { id: 'e-level1-0-level2-0', source: 'level1-0', target: 'level2-0' }, { id: 'e-level1-0-level2-1', source: 'level1-0', target: 'level2-1' }, { id: 'e-level1-1-level2-2', source: 'level1-1', target: 'level2-2' }, { id: 'e-level1-1-level2-3', source: 'level1-1', target: 'level2-3' }, { id: 'e-level1-2-level2-4', source: 'level1-2', target: 'level2-4' }, { id: 'e-level1-2-level2-5', source: 'level1-2', target: 'level2-5' }, { id: 'e-level1-3-level2-6', source: 'level1-3', target: 'level2-6' }, { id: 'e-level1-3-level2-7', source: 'level1-3', target: 'level2-7' }, { id: 'e-level1-4-level2-8', source: 'level1-4', target: 'level2-8' }, { id: 'e-level1-4-level2-9', source: 'level1-4', target: 'level2-9' }, { id: 'e-level1-5-level2-10', source: 'level1-5', target: 'level2-10' }, { id: 'e-level1-5-level2-11', source: 'level1-5', target: 'level2-11' }, ], }, layout: { type: 'concentric', nodeSize: 32, sortBy: 'degree', preventOverlap: true, }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], animation: false, }); graph.render(); ```
#### 鱼眼放大镜 Fisheye - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Fisheye/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Fisheye.md - Description: 鱼眼放大镜 Fisheye --- title: "鱼眼放大镜 Fisheye" description: "鱼眼放大镜 Fisheye" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Fisheye/" version: "5.1.1" --- ## 概述 鱼眼放大镜插件是为 focus+context 的探索场景设计的,它能够在放大关注区域的同时,保证上下文以及上下文与关注中心的关系不丢失,是一个重要的可视化探索工具。 ## 使用场景 - 在演示过程中需要突出展示某些区域内容 - 需要局部放大查看细节时,同时又不想失去整体视图 ## 基本用法 以下是一个简单的 Fisheye 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'fisheye', trigger: 'drag', // 通过拖拽移动鱼眼 d: 1.5, // 设置畸变因子 r: 120, // 设置鱼眼半径 showDPercent: true, // 显示畸变程度 }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ // 上部节点 { id: 'Myriel', style: { x: 197, y: 58 } }, { id: 'Napoleon', style: { x: 147, y: 22 } }, { id: 'Mlle.Baptistine', style: { x: 225, y: 141 } }, { id: 'Mme.Magloire', style: { x: 255, y: 120 } }, { id: 'CountessdeLo', style: { x: 151, y: -3 } }, { id: 'Geborand', style: { x: 136, y: 41 } }, { id: 'Champtercier', style: { x: 227, y: 8 } }, { id: 'Cravatte', style: { x: 172, y: -10 } }, { id: 'Count', style: { x: 172, y: 12 } }, { id: 'OldMan', style: { x: 198, y: -6 } }, // 中上部节点 { id: 'Labarre', style: { x: 266, y: 203 } }, { id: 'Marguerite', style: { x: 265, y: 171 } }, { id: 'Mme.deR', style: { x: 299, y: 133 } }, { id: 'Isabeau', style: { x: 282, y: 191 } }, { id: 'Gervais', style: { x: 334, y: 148 } }, { id: 'Simplice', style: { x: 286, y: 227 } }, { id: 'Scaufflaire', style: { x: 250, y: 231 } }, { id: 'Woman1', style: { x: 375, y: 202 } }, { id: 'Judge', style: { x: 370, y: 139 } }, { id: 'Champmathieu', style: { x: 404, y: 216 } }, // 中部主要节点 { id: 'Valjean', style: { x: 322, y: 221 } }, { id: 'Fantine', style: { x: 337, y: 187 } }, { id: 'Cosette', style: { x: 343, y: 248 } }, { id: 'Javert', style: { x: 368, y: 263 } }, { id: 'Thenardier', style: { x: 317, y: 300 } }, { id: 'Mme.Thenardier', style: { x: 283, y: 267 } }, { id: 'Eponine', style: { x: 268, y: 365 } }, { id: 'Gavroche', style: { x: 393, y: 380 } }, { id: 'Marius', style: { x: 336, y: 350 } }, { id: 'Enjolras', style: { x: 376, y: 371 } }, // 右侧和右上节点 { id: 'Gribier', style: { x: 437, y: 160 } }, { id: 'Jondrette', style: { x: 510, y: 327 } }, { id: 'Mme.Burgon', style: { x: 466, y: 368 } }, { id: 'Brevet', style: { x: 399, y: 183 } }, { id: 'Chenildieu', style: { x: 425, y: 194 } }, { id: 'Cochepaille', style: { x: 419, y: 148 } }, { id: 'Child1', style: { x: 361, y: 387 } }, { id: 'Child2', style: { x: 415, y: 432 } }, { id: 'Brujon', style: { x: 330, y: 394 } }, { id: 'Mme.Hucheloup', style: { x: 394, y: 450 } }, // 中部其他节点 { id: 'Favourite', style: { x: 284, y: 153 } }, { id: 'Dahlia', style: { x: 303, y: 170 } }, { id: 'Zephine', style: { x: 286, y: 94 } }, { id: 'Tholomyes', style: { x: 359, y: 158 } }, { id: 'Listolier', style: { x: 308, y: 80 } }, { id: 'Fameuil', style: { x: 329, y: 89 } }, { id: 'Blacheville', style: { x: 351, y: 95 } }, { id: 'Perpetue', style: { x: 234, y: 195 } }, { id: 'Woman2', style: { x: 304, y: 254 } }, { id: 'MotherInnocent', style: { x: 350, y: 214 } }, // 下部节点 { id: 'Pontmercy', style: { x: 375, y: 307 } }, { id: 'Boulatruelle', style: { x: 260, y: 279 } }, { id: 'Anzelma', style: { x: 234, y: 303 } }, { id: 'Gillenormand', style: { x: 338, y: 286 } }, { id: 'Magnon', style: { x: 277, y: 317 } }, { id: 'Mlle.Gillenormand', style: { x: 257, y: 306 } }, { id: 'Mme.Pontmercy', style: { x: 307, y: 318 } }, { id: 'Mlle.Vaubois', style: { x: 197, y: 325 } }, { id: 'Lt.Gillenormand', style: { x: 294, y: 296 } }, { id: 'Toussaint', style: { x: 306, y: 277 } }, { id: 'Gueulemer', style: { x: 344, y: 323 } }, { id: 'Babet', style: { x: 367, y: 319 } }, { id: 'Claquesous', style: { x: 303, y: 347 } }, { id: 'Montparnasse', style: { x: 322, y: 330 } }, // 最下部节点 { id: 'Combeferre', style: { x: 397, y: 416 } }, { id: 'Prouvaire', style: { x: 309, y: 426 } }, { id: 'Feuilly', style: { x: 314, y: 456 } }, { id: 'Courfeyrac', style: { x: 332, y: 435 } }, { id: 'Bahorel', style: { x: 343, y: 466 } }, { id: 'Bossuet', style: { x: 305, y: 382 } }, { id: 'Joly', style: { x: 371, y: 415 } }, { id: 'Grantaire', style: { x: 370, y: 466 } }, { id: 'MotherPlutarch', style: { x: 424, y: 461 } }, ], edges: [ // 主要连接 { id: 'e1', source: 'Valjean', target: 'Javert' }, { id: 'e2', source: 'Valjean', target: 'Cosette' }, { id: 'e3', source: 'Javert', target: 'Thenardier' }, { id: 'e4', source: 'Cosette', target: 'Marius' }, { id: 'e5', source: 'Eponine', target: 'Marius' }, { id: 'e6', source: 'Enjolras', target: 'Marius' }, { id: 'e7', source: 'Gavroche', target: 'Enjolras' }, { id: 'e8', source: 'Valjean', target: 'Fantine' }, { id: 'e9', source: 'Cosette', target: 'Thenardier' }, { id: 'e10', source: 'Eponine', target: 'Thenardier' }, // 上部连接 { id: 'e11', source: 'Myriel', target: 'Napoleon' }, { id: 'e12', source: 'Myriel', target: 'Mlle.Baptistine' }, { id: 'e13', source: 'Mlle.Baptistine', target: 'Mme.Magloire' }, { id: 'e14', source: 'CountessdeLo', target: 'Myriel' }, { id: 'e15', source: 'Geborand', target: 'Myriel' }, // 中部连接 { id: 'e16', source: 'Favourite', target: 'Tholomyes' }, { id: 'e17', source: 'Dahlia', target: 'Favourite' }, { id: 'e18', source: 'Zephine', target: 'Favourite' }, { id: 'e19', source: 'Tholomyes', target: 'Listolier' }, { id: 'e20', source: 'Fameuil', target: 'Blacheville' }, // 下部连接 { id: 'e21', source: 'Combeferre', target: 'Enjolras' }, { id: 'e22', source: 'Prouvaire', target: 'Combeferre' }, { id: 'e23', source: 'Feuilly', target: 'Courfeyrac' }, { id: 'e24', source: 'Bahorel', target: 'Bossuet' }, { id: 'e25', source: 'Joly', target: 'Grantaire' }, // 额外的中部连接 { id: 'e26', source: 'Gueulemer', target: 'Thenardier' }, { id: 'e27', source: 'Babet', target: 'Gueulemer' }, { id: 'e28', source: 'Claquesous', target: 'Montparnasse' }, { id: 'e29', source: 'Brujon', target: 'Babet' }, { id: 'e30', source: 'Child1', target: 'Gavroche' }, // 新增更多连接 { id: 'e31', source: 'Valjean', target: 'Simplice' }, { id: 'e32', source: 'Fantine', target: 'Simplice' }, { id: 'e33', source: 'Javert', target: 'Simplice' }, { id: 'e34', source: 'Marius', target: 'Gillenormand' }, { id: 'e35', source: 'Cosette', target: 'Gillenormand' }, { id: 'e36', source: 'Marius', target: 'Lt.Gillenormand' }, { id: 'e37', source: 'Gillenormand', target: 'Lt.Gillenormand' }, { id: 'e38', source: 'Cosette', target: 'Toussaint' }, { id: 'e39', source: 'Javert', target: 'Toussaint' }, { id: 'e40', source: 'Valjean', target: 'Toussaint' }, // 随机添加更多连接 ...Array.from({ length: 50 }, (_, i) => ({ // 从40增加到50个随机连接 id: `edge-${i + 41}`, source: [ 'Valjean', 'Javert', 'Cosette', 'Marius', 'Enjolras', 'Fantine', 'Thenardier', 'Eponine', 'Gavroche', 'Gueulemer', 'Babet', 'Claquesous', 'Favourite', 'Tholomyes', 'Simplice', ][Math.floor(Math.random() * 15)], target: [ 'Favourite', 'Dahlia', 'Tholomyes', 'Combeferre', 'Prouvaire', 'Feuilly', 'Courfeyrac', 'Bahorel', 'Bossuet', 'Montparnasse', 'Brujon', 'Child1', 'Simplice', 'Toussaint', 'Gillenormand', ][Math.floor(Math.random() * 15)], })), ], }, autoFit: 'view', node: { style: { size: (datum) => datum.id.length * 2 + 10, label: false, labelText: (datum) => datum.id, labelBackground: true, icon: false, iconFontFamily: 'iconfont', iconText: '\ue6f6', iconFill: '#fff', }, palette: { type: 'group', field: (datum) => datum.id, color: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }, }, edge: { style: { stroke: '#bfbfbf', }, }, behaviors: ['drag-canvas'], plugins: [ { type: 'fisheye', key: 'fisheye', r: 120, d: 1.5, nodeStyle: { label: true, icon: true, }, }, ], }, { width: 600, height: 300 }, (gui, graph) => { const TRIGGER_OPTIONS = ['pointermove', 'drag', 'click']; const SCALE_OPTIONS = ['wheel', 'drag', '-']; const options = { type: 'fisheye', trigger: 'pointermove', r: 120, d: 1.5, maxR: 200, minR: 50, maxD: 5, minD: 0.5, scaleRBy: '-', scaleDBy: '-', showDPercent: true, preventDefault: true, }; const optionFolder = gui.addFolder('Fisheye Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'trigger', TRIGGER_OPTIONS); optionFolder.add(options, 'r', 50, 200, 10); optionFolder.add(options, 'd', 0.5, 5, 0.1); optionFolder.add(options, 'scaleRBy', SCALE_OPTIONS); optionFolder.add(options, 'scaleDBy', SCALE_OPTIONS); optionFolder.add(options, 'showDPercent'); optionFolder.add(options, 'preventDefault'); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'fisheye', [property]: value === '-' ? undefined : value, }); graph.render(); }); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ---- | | type | 插件类型 | string | `fisheye` | ✓ | | key | 插件的唯一标识,可用于获取插件实例或更新插件选项 | string | - | | | trigger | 用于控制鱼眼放大镜的移动方式,支持以下三种配置:
- `pointermove`:鱼眼放大镜始终跟随鼠标移动
- `click`:点击画布时移动鱼眼放大镜到点击位置
- `drag`:通过拖拽方式移动鱼眼放大镜 | `pointermove` \| `drag` \| `click` | `pointermove` | | | r | 鱼眼放大镜半径 | number | 120 | | | maxR | 鱼眼放大镜可调整的最大半径 | number | 画布宽高的最小值的一半 | | | minR | 鱼眼放大镜可调整的最小半径 | number | 0 | | | d | 畸变因子 | number | 1.5 | | | maxD | 鱼眼放大镜可调整的最大畸变因子 | number | 5 | | | minD | 鱼眼放大镜可调整的最小畸变因子 | number | 0 | | | scaleRBy | 调整鱼眼放大镜范围半径的方式:
- `'wheel'`:滚轮调整
- `'drag'`:拖拽调整 | `wheel` \| `drag` | - | | | scaleDBy | 调整鱼眼放大镜畸变因子的方式:
- `'wheel'`:滚轮调整
- `'drag'`:拖拽调整 | `wheel` \| `drag` | - | | | showDPercent | 是否在鱼眼放大镜中显示畸变因子数值 | boolean | true | | | style | 鱼眼放大镜样式,[配置项](#style) | object | - | | | nodeStyle | 在鱼眼放大镜中的节点样式 | [NodeStyle](/zh/manual/element/node/BaseNode/#style) \| ((datum: [NodeData](/zh/manual/data/#节点数据nodedata)) => [NodeStyle](/zh/manual/element/node/BaseNode/#style)) | `{ label: true }` | | | preventDefault | 是否阻止默认事件 | boolean | true | | ### style 圆形样式属性,用于配置鱼眼放大镜的外观。 | 属性 | 描述 | 类型 | 默认值 | | ------------- | --------------- | ----------------------------- | ------ | | fill | 填充颜色 | string \| Pattern \| null | `#ccc` | | stroke | 描边颜色 | string \| Pattern \| null | `#000` | | opacity | 整体透明度 | number \| string | - | | fillOpacity | 填充透明度 | number \| string | 0.1 | | strokeOpacity | 描边透明度 | number \| string | - | | lineWidth | 线宽度 | number \| string | 2 | | lineCap | 线段端点样式 | `butt` \| `round` \| `square` | - | | lineJoin | 线段连接处样式 | `miter` \| `round` \| `bevel` | - | | shadowColor | 阴影颜色 | string | - | | shadowBlur | 阴影模糊程度 | number | - | | shadowOffsetX | 阴影 X 方向偏移 | number | - | | shadowOffsetY | 阴影 Y 方向偏移 | number | - | 完整样式属性参考 [元素 -节点 - 内置节点 - 通用样式属性 - style](/zh/manual/element/node/BaseNode/#style) ### 缩放控制 通过 `scaleRBy` 和 `scaleDBy` 可以分别控制鱼眼放大镜的半径和畸变因子的调整方式: ```js const graph = new Graph({ plugins: [ { type: 'fisheye', // 通过滚轮调整半径 scaleRBy: 'wheel', // 通过拖拽调整畸变因子 scaleDBy: 'drag', // 设置半径和畸变因子的范围 minR: 50, maxR: 200, minD: 1, maxD: 3, }, ], }); ``` 注意:当 `trigger`、`scaleRBy` 和 `scaleDBy` 同时设置为 `'drag'` 时,优先级顺序为 `trigger` > `scaleRBy` > `scaleDBy`,只会为优先级最高的配置项绑定拖拽事件。同理,如果 `scaleRBy` 和 `scaleDBy` 同时设置为 `'wheel'`,只会为 `scaleRBy` 绑定滚轮事件。 ## 代码示例 ### 基础用法 最简单的配置方式: ```js const graph = new Graph({ plugins: ['fisheye'], }); ``` ### 自定义样式 可以自定义鱼眼放大镜的外观和行为: ```js const graph = new Graph({ plugins: [ { type: 'fisheye', r: 150, d: 2, style: { fill: '#2f54eb', // 鱼眼区域的填充颜色 fillOpacity: 0.2, // 填充区域的透明度 stroke: '#1d39c4', // 鱼眼边框的颜色 strokeOpacity: 0.8, // 边框的透明度 lineWidth: 1.5, // 边框的线宽 shadowColor: '#1d39c4', // 阴影颜色 shadowBlur: 10, // 阴影的模糊半径 shadowOffsetX: 0, // 阴影的水平偏移 shadowOffsetY: 0, // 阴影的垂直偏移 cursor: 'pointer', // 鼠标悬停时的指针样式 }, nodeStyle: { // 节点基础样式 size: 40, // 节点大小 fill: '#d6e4ff', // 节点填充颜色 stroke: '#2f54eb', // 节点边框颜色 lineWidth: 2, // 节点边框宽度 shadowColor: '#2f54eb', // 节点阴影颜色 shadowBlur: 5, // 节点阴影模糊半径 cursor: 'pointer', // 鼠标悬停时的指针样式 // 标签样式 label: true, // 是否显示标签 labelFontSize: 14, // 标签字体大小 labelFontWeight: 'bold', // 标签字体粗细 labelFill: '#1d39c4', // 标签文字颜色 labelBackground: true, // 是否显示标签背景 labelBackgroundFill: '#fff', // 标签背景填充颜色 labelBackgroundStroke: '#1d39c4', // 标签背景边框颜色 labelBackgroundOpacity: 0.8, // 标签背景透明度 labelBackgroundPadding: [4, 8, 4, 8], // 标签背景内边距 [上,右,下,左] // 图标样式 icon: true, // 是否显示图标 iconFontFamily: 'iconfont', // 图标字体 iconText: '\ue6f6', // 图标的 Unicode 编码 iconFill: '#1d39c4', // 图标颜色 iconSize: 16, // 图标大小 iconFontWeight: 'normal', // 图标字体粗细 }, }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 300, data: { nodes: [ { id: 'node-1', style: { x: 150, y: 100 } }, { id: 'node-2', style: { x: 250, y: 100 } }, { id: 'node-3', style: { x: 200, y: 180 } }, { id: 'node-4', style: { x: 120, y: 180 } }, { id: 'node-5', style: { x: 280, y: 180 } }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2' }, { id: 'edge-2', source: 'node-1', target: 'node-3' }, { id: 'edge-3', source: 'node-2', target: 'node-3' }, { id: 'edge-4', source: 'node-3', target: 'node-4' }, { id: 'edge-5', source: 'node-3', target: 'node-5' }, ], }, node: { style: { size: 30, fill: '#e6f7ff', stroke: '#1890ff', lineWidth: 1, label: false, icon: false, }, }, edge: { style: { stroke: '#91d5ff', lineWidth: 1, }, }, plugins: [ { type: 'fisheye', key: 'fisheye', r: 100, d: 2, style: { fill: '#2f54eb', // 鱼眼区域的填充颜色 fillOpacity: 0.2, // 填充区域的透明度 stroke: '#1d39c4', // 鱼眼边框的颜色 strokeOpacity: 0.8, // 边框的透明度 lineWidth: 1.5, // 边框的线宽 shadowColor: '#1d39c4', // 阴影颜色 shadowBlur: 10, // 阴影的模糊半径 shadowOffsetX: 0, // 阴影的水平偏移 shadowOffsetY: 0, // 阴影的垂直偏移 cursor: 'pointer', // 鼠标悬停时的指针样式 }, nodeStyle: { // 节点基础样式 size: 40, // 节点大小 fill: '#d6e4ff', // 节点填充颜色 stroke: '#2f54eb', // 节点边框颜色 lineWidth: 2, // 节点边框宽度 shadowColor: '#2f54eb', // 节点阴影颜色 shadowBlur: 5, // 节点阴影模糊半径 cursor: 'pointer', // 鼠标悬停时的指针样式 // 标签样式 label: true, // 是否显示标签 labelFontSize: 14, // 标签字体大小 labelFontWeight: 'bold', // 标签字体粗细 labelFill: '#1d39c4', // 标签文字颜色 labelBackground: true, // 是否显示标签背景 labelBackgroundFill: '#fff', // 标签背景填充颜色 labelBackgroundStroke: '#1d39c4', // 标签背景边框颜色 labelBackgroundOpacity: 0.8, // 标签背景透明度 labelBackgroundPadding: [4, 8, 4, 8], // 标签背景内边距 [上,右,下,左] // 图标样式 icon: true, // 是否显示图标 iconFontFamily: 'iconfont', // 图标字体 iconText: '\ue6f6', // 图标的 Unicode 编码 iconFill: '#1d39c4', // 图标颜色 iconSize: 16, // 图标大小 iconFontWeight: 'normal', // 图标字体粗细 }, }, ], }); graph.render(); ``` ## 实际案例 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); fetch('https://assets.antv.antgroup.com/g6/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { size: (datum) => datum.id.length * 2 + 10, label: false, labelText: (datum) => datum.id, labelBackground: true, icon: false, iconFontFamily: 'iconfont', iconText: '\ue6f6', iconFill: '#fff', }, palette: { type: 'group', field: (datum) => datum.id, color: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }, }, edge: { style: { stroke: '#e2e2e2', }, }, plugins: [{ key: 'fisheye', type: 'fisheye', nodeStyle: { label: true, icon: true } }], }); graph.render(); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 升级到 5.0 - Canonical page: https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade.md - Description: 升级到 5.0 --- title: "升级到 5.0" description: "升级到 5.0" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade/" version: "5.1.1" --- 本文档将引导你从 G6 `4.x` 版本升级到 `5.x` 版本。如果你使用的是 `3.x` 版本,请先升级到 `4.x` 版本。 ## 升级前准备 1. 请确保当前 git 分支是干净的,没有未提交的代码。 2. 参考 [安装](/zh/manual/getting-started/installation/) 文档安装 `5.x` 版本,并移除 `4.x` 版本依赖。 ## 开始升级 ### 数据 新版本的数据格式有所变化,具体如下: 1. `nodes` `edges` `combos` 中所有样式属性都需要放在 `style` 中,`data` 中存放数据属性: ```typescript // 4.x const data = { nodes: [ { id: 'node1', label: 'node1', size: 20 }, { id: 'node2', label: 'node2', size: 20 }, ], edges: [{ source: 'node1', target: 'node2' }], }; // 5.x const data = { nodes: [ // label 为非样式属性,放在 data 中,可在样式映射函数中访问 // size 为样式属性,放在 style 中 { id: 'node1', data: { label: 'node1' }, style: { size: 20 } }, { id: 'node2', data: { label: 'node2' }, style: { size: 20 } }, ], edges: [{ source: 'node1', target: 'node2' }], }; ``` 由于我们重新设计实现了元素,新的元素配置项请参考相应文档进行修改: - [Node](/zh/manual/element/node/overview/) - [Edge](/zh/manual/element/edge/overview/) - [Combo](/zh/manual/element/combo/overview/) 2. 如果要在数据中指定元素类型,可以使用 `type` 属性: ```typescript { nodes: [ // 指定节点类型为 rect { id: 'node1', type: 'rect' }, ]; } ``` ### 配置项 **变更** **fitView / fitCenter / fitViewPadding** - `fitView` 和 `fitCenter` 配置项已经合并为 `autoFit` - 若要使用 `fitView`,可以配置为 `autoFit: 'view'` - 若要使用 `fitCenter`,可以配置为 `autoFit: 'center'` - 也可以传入对象进行完整配置: ```js autoFit: { type: 'view', options: { // ... } } ``` - `fitViewPadding` 已变更为 `padding` **移除** **linkCenter** 5.x 的边连接机制会按照如下顺序依次尝试连接到节点/Combo: 1. 连接桩 2. 轮廓 3. 中心 **移除** **groupByTypes** **移除** **autoPaint** 请手动调用 `render` 或 `draw` 方法进行绘制。 **变更** **modes** 5.x 已经移除交互模式,你可以通过设置 `behaviors` 来切换当前启用的交互行为。 ```typescript // 4.x { modes: { default: ['drag-canvas', 'zoom-canvas'], preview: ['drag-canvas'], }, } graph.setMode('preview'); ``` ```typescript // 5.x { behaviors: ['drag-canvas', 'zoom-canvas'], } graph.setBehaviors(['drag-canvas']); ``` **变更** **defaultNode / defaultEdge / defaultCombo** 元素样式已移至 `[element].style` 中,如 `defaultNode` 变更为 `node.style`: ```typescript // 4.x { defaultNode: { size: 20, fill: 'red', } } // 5.x { node: { style: { size: 20, fill: 'red', } } } ``` **变更** **nodeStateStyles / edgeStateStyles / comboStateStyle** 元素状态样式已移至 `[element].state` 中,如 `nodeStateStyles` 变更为 `node.stateStyles`: ```typescript // 4.x { nodeStateStyles: { selected: { fill: 'red', } } } // 5.x { node: { state: { selected: { fill: 'red', } } } } ``` **变更** **animate / animateCfg** - `animate` 配置项已变更为 `animation` - `animate` 和 `animateCfg` 已合并为 `animation` ```typescript // 4.x { animate: true, } // 5.x { animation: true, } { animation: { duration: 500, easing: 'easeLinear', } } ``` **变更** **minZoom / maxZoom** `minZoom` 和 `maxZoom` 已合并为 `zoomRange` ```typescript // 4.x { minZoom: 0.5, maxZoom: 2, } // 5.x { zoomRange: [0.5, 2], } ``` **变更** **renderer** G6 5.x 支持多层画布,默认使用 `canvas` 渲染。 renderer 不再支持字符串类型,变更为回调函数: ```typescript // 4.x var options = { renderer: 'svg', }; // 5.x import { Renderer } from '@antv/g-svg'; { renderer: () => new Renderer(), } ``` **移除** **enabledStack / maxStep** 5.x 已移除内置撤销重做功能,相关能力请使用插件实现。 ### API **变更** **data / save / read / changeData** 5.x 提供了全新的数据 API,详见 [数据 API](/zh/api/data/)。 - 4.x `data` `changeData` 方法使用 5.x `setData` 替代 - 4.x `save` 方法使用 5.x `getData` 替代 - 4.x `read` 方法使用 5.x `setData` + `render` 替代 **变更** **get / set** 若要访问 Graph options,请使用 `getOptions` 或者 `getXxx` API,例如 `getZoomRange` `getBehaviors` 等。 `set` 同理。 **变更** **getContainer** 暂不支持直接获取容器的 API,但可以通过 `graph.getCanvas().getContainer()` 获取。 > 绝大部分情况下,你都不需要直接操作容器。 **移除** **getGroup** **变更** **getMinZoom / getMaxZoom** 使用 `getZoomRange` 获取。 **变更** **setMinZoom / setMaxZoom** 使用 `setZoomRange` 方法设置。 **变更** **getWidth / getHeight** 使用 `getSize` 获取。 **变更** **changeSize** 使用 `setSize` 设置。 **变更** **zoom** 变更为 `zoomBy`。 **变更** **translate** 变更为 `translateBy`。 **变更** **moveTo** 变更为 `translateTo`。 **变更** **focusItem** 变更为 `focusElement`。 **移除** **addItem / updateItem / removeItem** 通过 `addData` / `updateData` / `removeData` 方法操作数据来添加或删除元素。 **移除** **refreshItem** **移除** **refreshPositions** **移除** **updateCombo** **移除** **updateCombos** **移除** **updateComboTree** **变更** **node / edge / combo** 使用 `setNode` / `setEdge` / `setCombo` 方法替代。 **变更** **showItem / hideItem** 使用 `setElementVisibility` 方法替代。 **移除** **getNodes / getEdges / getCombos / getComboChildren /getNeighbors /find /findById / findAll /findAllByState** 5.x 不支持直接获取元素实例。 - 若要获取元素数据,使用 `getData` `getNodeData` `getEdgeData` `getComboData` 方法,支持传入元素 id 进行查找。 - 获取子节点数据,使用 `getChildrenData` 方法。 - 获取邻居节点数据,使用 `getNeighborNodesData` 方法。 - 基于状态查找元素数据,使用 `getElementDataByState`。 **变更** **collapseCombo / expandCombo** 使用 `collapseElement` / `expandElement` 方法替代。 **移除** **collapseExpandCombo** **移除** **createCombo** 通过 `addData` / `addComboData` 方法添加 Combo。 **移除** **uncombo** 通过 `removeData` / `removeComboData` 方法移除 Combo。 **变更** **setItemState** 使用 `setElementState` 方法替代。 **移除** **clearItemStates** - 清除单个元素所有状态:`graph.setElementState(id, [])` - 清除多个元素所有状态:`graph.setElementState({ id1: [], id2: [] })` **移除** **priorityState** `setElementState` 时状态数组中靠后的状态优先级更高。 **移除** **setMode** 使用 `setBehaviors` 来设置当前交互。 **移除** **setCurrentMode** **变更** **layout** 不支持参数,如需配置布局,请使用 `setLayout`。 **变更** **updateLayout** 变更为 `setLayout`。 **移除** **destroyLayout** **变更** **addBehaviors / removeBehaviors** 使用 `setBehaviors` 替代。 **移除** **createHull / getHulls / removeHull / removeHulls** - 多个 `Hull` 需在 `plugins` 中配置多个 `hull` 插件,如: ```typescript { plugins: ['hull', 'hull'], }; ``` - `Hull` 的获取、更新、移除操作通过 `setPlugins`, `updatePlugin` 实现。 **暂未提供** **getNodeDegree** **暂未提供** **getShortestPathMatrix** **暂未提供** **getAdjMatrix** **移除** **pushStack / getUndoStack / getRedoStack / getStackData / clearStack** 所有撤销重做相关 API 请获取到对应插件后调用 API,例: ```typescript // 'history' 为使用插件时配置的 key const history = graph.getPluginInstance('history'); history.redo(); ``` **移除** **positionsAnimate / stopAnimate / isAnimating** 动画相关信息通过事件抛出: - 动画开始事件:`beforeanimate` - 动画结束事件:`afteranimate` - 停止动画: ```typescript graph.on('beforeanimate', (event) => { event.animation.stop(); }); ``` **变更** **getPointByClient / getClientByPoint / getPointByCanvas / getCanvasByPoint / getGraphCenterPoint / getViewPortCenterPoint** G6 5.x 采用了与 4.x 不同的坐标系,详见 [坐标系](/zh/manual/further-reading/coordinate/)。 **移除** **setTextWaterMarker / setImageWaterMarker** 要使用水印功能,请参考 [水印](/zh/manual/plugin/Watermark/)插件。 **变更** **toFullDataURL** 使用 `toDataURL` 替代,指定参数为:`mode: 'overall'` ```typescript graph.toDataURL({ mode: 'overall' }); ``` **移除** **downloadFullImage / downloadImage** 仅提供导出为 `DataURL` 的能力,如需下载图片,请参考如下实例代码: ```typescript async function downloadImage() { const dataURL = await graph.toDataURL(); const [head, content] = dataURL.split(','); const contentType = head.match(/:(.*?);/)![1]; const bstr = atob(content); let length = bstr.length; const u8arr = new Uint8Array(length); while (length--) { u8arr[length] = bstr.charCodeAt(length); } const blob = new Blob([u8arr], { type: contentType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'graph.png'; a.click(); } ``` **移除** **clear** 使用 `setData` + `draw` 清空数据和画布。 ### 扩展注册 与 G6 4.x 不同,G6 5.x 使用的统一的扩展注册函数(register),你可以参考 [注册扩展](/zh/manual/graph/extension/#注册扩展) 来注册 G6 扩展。 下列 G6 4.x 的注册函数已经废除: - registerNode - registerEdge - registerCombo - registerLayout - registerBehavior ### 事件 与 G6 4.x 相比,G6 5.x 的事件但存下如下差异: - 移除了 `mouse` 和 `touch` 事件,统一使用 `pointer` 事件 - 生命周期事件名命名格式通常为: `before/after` + `对象/属性` + `操作`,例如:`beforeelementcreate` 表示在创建元素前触发 - 下列事件已被移除: - afteractivaterelations - afteradditem - aftercreateedge - aftergraphrefresh - aftergraphrefreshposition - afteritemrefresh - aftermodechange - afterremoveitem - afterupdateitem - beforeadditem - beforecreateedge - beforegraphrefresh - beforegraphrefreshposition - beforeitemrefresh - beforemodechange - beforeremoveitem - beforeupdateitem - dragnodeend - nodeselectchange - stackchange - tooltipchange - 下列元素变更事件被移除,但你仍可通过 `beforeelementupdate` 和 `afterelementupdate` 获取: - afteritemstatechange - afteritemstatesclear - afteritemvisibilitychange - beforeitemstatechange - beforeitemstatesclear - beforeitemvisibilitychange - 下列事件有所变更: - graphstatechange 事件变更为 beforeelementstatechange / afterelementstatechange - viewportchange 事件变更为 beforetransform / aftertransform 完整的事件列表请参考 [事件](/zh/api/event/)。 #### 拖拽元素 DragElement - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/DragElement/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/DragElement.md - Description: 拖拽元素 DragElement --- title: "拖拽元素 DragElement" description: "拖拽元素 DragElement" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/DragElement/" version: "5.1.1" --- ## 概述 DragElement 是 G6 中用于实现 **元素拖拽** 功能的内置交互。它具有以下核心特性: 1. **多元素类型支持**:可以同时支持节点(Node)和组合(Combo)的拖拽 2. **智能多选**:支持同时拖拽多个选中状态的元素 3. **视觉反馈**:提供幽灵节点、边的显隐、鼠标样式等多种视觉反馈机制 4. **灵活的拖拽效果**:支持移动、链接、自由拖拽等多种拖拽操作效果 5. **父子关系处理**:自动处理拖拽过程中的元素层级关系,特别是在处理 Combo 结构时 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } }, ], edges: [], combos: [ { id: 'combo1', combo: 'combo2' }, { id: 'combo2', style: {} }, ], }, node: { style: { fill: '#873bf4' } }, edge: { style: { stroke: '#8b9baf' } }, behaviors: [ { type: 'drag-element', key: 'drag-element', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 400 }, (gui, graph) => { const options = { key: 'drag-element', type: 'drag-element', animation: true, enable: 'node,combo', dropEffect: 'move', state: 'selected', hideEdge: 'none', shadow: false, }; const optionFolder = gui.addFolder('DragElement Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable', { 'node,combo': (event) => ['node', 'combo'].includes(event.targetType), node: (event) => ['node'].includes(event.targetType), combo: (event) => ['combo'].includes(event.targetType), none: false, }); optionFolder.add(options, 'dropEffect', ['link', 'move', 'none']); optionFolder.add(options, 'hideEdge', ['none', 'all', 'in', 'out', 'both']); optionFolder.add(options, 'shadow'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'drag-element', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-element'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-element', key: 'drag-element-1', enableAnimation: true, dropEffect: 'move', shadow: true, // 启用拖拽幽灵节点 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------- | ---- | | type | 交互类型名称 | string | `drag-element` | ✓ | | key | 交互唯一标识符,用于后续操作交互 | string | - | | | enable | 是否启用拖拽功能,默认可以拖拽节点和 Combo | boolean \| ((event: IElementDragEvent) => boolean) | `['node', 'combo'].includes(event.targetType)` | | | animation | 是否启用拖拽动画 | boolean | true | | | state | 节点选中状态的标识,启用多选时会基于该状态查找选中的节点 | string | `selected` | | | dropEffect | 定义拖拽结束后的操作效果,可选值有:
- `link`: 将拖拽元素设置为目标元素的子元素
- `move`: 移动元素并自动更新父元素(如 Combo)的尺寸
- `none`: 仅更新拖拽目标的位置,不执行其他操作 | `link` \| `move` \| `none` | `move` | | | hideEdge | 控制拖拽过程中边的显示状态,可选值有:
- `none`: 不隐藏任何边
- `out`: 隐藏以当前节点为源节点的边
- `in`: 隐藏以当前节点为目标节点的边
- `both`: 隐藏与当前节点相关的所有边
- `all`: 隐藏图中所有边
⚠️ 注意:当启用 `shadow`(幽灵节点)时,`hideEdge` 配置将不生效。 | `none` \| `all` \| `in` \| `out` \| `both` | `none` | | | shadow | 是否启用幽灵节点,即用一个图形代替节点跟随鼠标移动。[自定义幽灵节点样式](#shadow-样式配置) ⚠️注意:React 节点不支持启用 | boolean | false | | | cursor | 自定义鼠标样式,[配置项](#cursor) | \{ default?: Cursor; grab: Cursor; grabbing: Cursor \} | - | | | trigger | 同时按下快捷键才能拖拽元素 **按键参考:** _MDN Key Values_ 。若设为**空数组**时则表示不需要按下其他按键配合
⚠️ 注意,`trigger` 设置为 `['drag']` 时会导致 `drag-canvas` 行为失效。两者不可同时配置。 | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | [] | | ### cursor `cursor` 用于自定义拖拽过程中的鼠标指针样式: - `default`: 默认状态下的指针样式 - `grab`: 鼠标悬停在可拖拽元素上时的指针样式 - `grabbing`: 正在拖拽时的指针样式 可选值有:`auto` | `default` | `none` | `context-menu` | `help` | `pointer` | `progress` | `wait` | `cell` | `crosshair` | `text` | `vertical-text` | `alias` | `copy` | `move` | `no-drop` | `not-allowed` | `grab` | `grabbing` | `all-scroll` | `col-resize` | `row-resize` | `n-resize` | `e-resize` | `s-resize` | `w-resize` | `ne-resize` | `nw-resize` | `se-resize` | `sw-resize` | `ew-resize` | `ns-resize` | `nesw-resize` | `nwse-resize` | `zoom-in` | `zoom-out` 示例配置: ```js cursor: { default: 'default', // 默认使用普通指针 grab: 'grab', // 可拖拽时显示抓取指针 grabbing: 'grabbing' // 拖拽中显示抓取中指针 } ``` ### shadow 样式配置 当启用 `shadow: true` 时,可以通过以下属性自定义幽灵节点的样式: | 配置项 | 说明 | 类型 | 默认值 | | -------------------- | ---------------------- | ----------------------------------- | -------------------- | | shadowFill | 幽灵节点填充色 | string | `#F3F9FF` | | shadowFillOpacity | 幽灵节点填充色透明度 | number | 0.5 | | shadowStroke | 幽灵节点描边颜色 | string | `#1890FF` | | shadowStrokeOpacity | 幽灵节点描边透明度 | number | 0.9 | | shadowLineDash | 幽灵节点虚线配置 | number[] | [5, 5] | | shadowZIndex | 幽灵节点渲染层级 | number | 100 | | shadowWidth | 幽灵节点宽度 | number | 目标元素的包围盒宽度 | | shadowHeight | 幽灵节点高度 | number | 目标元素的包围盒高度 | | shadowOpacity | 幽灵节点整体透明度 | number | | | shadowLineWidth | 幽灵节点线宽度 | number | | | shadowLineCap | 幽灵节点线段端点样式 | `'butt'` \| `'round'` \| `'square'` | | | shadowLineJoin | 幽灵节点线段连接处样式 | `'miter'` \| `'round'` \| `'bevel'` | | | shadowLineDashOffset | 幽灵节点虚线偏移量 | number | | | shadowCursor | 幽灵节点鼠标样式 | string | | | shadowVisibility | 幽灵节点可见性 | `'visible'` \| `'hidden'` | | 示例配置: ```javascript { type: 'drag-element', shadow: true, // 自定义幽灵节点样式 shadowFill: '#E8F3FF', shadowFillOpacity: 0.4, shadowStroke: '#1890FF', shadowStrokeOpacity: 0.8, shadowLineDash: [4, 4], shadowZIndex: 99 } ``` > 注意:幽灵节点样式继承自 [BaseStyleProps](/zh/manual/element/shape/properties/#baseshapestyle),上述配置项是在属性名前添加 `shadow` 前缀得到的。 ## 代码示例 ### 多选推拽 需要配合 `click-select` 行为实现多选,然后通过 `state` 参数关联选中状态: ```javascript const graph = new Graph({ behaviors: [ { type: 'click-select', multiple: true, state: 'selected', }, { type: 'drag-element', state: 'selected', // 拖拽时会同时移动所有 selected 状态的节点 }, ], }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 自定义边 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/edge/custom-edge/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/edge/custom-edge.md - Description: 自定义边 --- title: "自定义边" description: "自定义边" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/edge/custom-edge/" version: "5.1.1" --- G6 提供了多种[内置边](/zh/manual/element/edge/BaseEdge/)类型,包含 [line(直线边)](/zh/manual/element/edge/Line/)、[polyline(折线边)](/zh/manual/element/edge/Polyline/)、[quadratic(二次贝塞尔曲线边)](/zh/manual/element/edge/Quadratic/)、[cubic(三次贝塞尔曲线边)](/zh/manual/element/edge/Cubic/)、[cubic-horizontal(水平三次贝塞尔曲线边)](/zh/manual/element/edge/CubicHorizontal/)、[cubic-vertical(垂直三次贝塞尔曲线边)](/zh/manual/element/edge/CubicVertical/) 等。这些内置边能够满足大部分基础场景需求。 但在实际项目中,你可能会遇到这些基础边无法满足的需求。这时,你需要创建自定义边。别担心,这比你想象的要简单! ## 开始之前:了解边的基本构成 在 G6 中,一条完整的边通常由以下几个部分组成: - `key` :边的主图形,表示边的主要形状,例如直线、折线等; - `label` :文本标签,通常用于展示边的名称或描述; - `arrow` :箭头,用于表示边的方向; - `halo` :主图形周围展示的光晕效果的图形。 ## 自定义边的方式 **选择合适的方式** 创建自定义边的方式主要有两种途径: ### 1. 继承现有边类型 **推荐** 这是最常用的方式,你可以选择继承以下类型之一: - [`BaseEdge`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/base-edge.ts) - 最基础的边类,提供边的核心功能 - [`Line`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/line.ts) - 直线边 - [`Polyline`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/polyline.ts) - 折线边 - [`Quadratic`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/quadratic.ts) - 二次贝塞尔曲线边 - [`Cubic`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/cubic.ts) - 三次贝塞尔曲线边 - [`CubicVertical`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/cubic-vertical.ts) - 垂直三次贝塞尔曲线边 - [`CubicHorizontal`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/cubic-horizontal.ts) - 水平三次贝塞尔曲线边 **为什么选择这种方式?** - 📌 **代码量少**:复用现有边的属性和方法,只需专注于新增功能 - 📌 **开发迅速**:适合大多数项目需求,快速实现业务目标 - 📌 **易于维护**:代码结构清晰,继承关系明确 :::tip\{title=立即开始\} 如果你选择继承现有边类型(推荐),可以直接跳到 [三步创建你的第一个自定义边](#三步创建你的第一个自定义边) 开始实践。大部分用户都会选择这种方式! ::: ### 2. 基于 G 图形系统从零开发 **高级用法** 如果现有边类型都不满足需求,你可以基于 G 的底层图形系统从零创建边。 **为什么选择这种方式?** - 📌 **最大自由度**:完全控制边的每个细节,实现任意复杂效果 - 📌 **特殊需求**:现有边类型无法满足的高度定制场景 - 📌 **性能优化**:针对特定场景的性能优化 :::warning\{title=注意事项\} 从零开发的自定义边需要自行处理所有细节,包括图形绘制、事件响应、状态变化等,开发难度较大。这里可以直接参考 [源码](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/edges/base-edge.ts) 进行实现。 ::: ## 三步创建你的第一个自定义边 让我们从最基础的 `BaseEdge` 开始,实现一个自定义直线边: ```ts import { Graph, register, BaseEdge, ExtensionCategory } from '@antv/g6'; class MyLineEdge extends BaseEdge { getKeyStyle(attributes) { return { ...super.getKeyStyle(attributes), lineWidth: 2, stroke: '#A4D3EE' }; } getKeyPath(attributes) { const { sourceNode, targetNode } = this; const [x1, y1] = sourceNode.getPosition(); const [x2, y2] = targetNode.getPosition(); return [ ['M', x1, y1], ['L', x2, y2], ]; } } register(ExtensionCategory.EDGE, 'my-line-edge', MyLineEdge); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'node1', style: { x: 100, y: 50 } }, { id: 'node2', style: { x: 300, y: 120 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, node: { style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, }, }, edge: { type: 'my-line-edge', style: { zIndex: 3, }, }, }); graph.render(); ``` ### 第一步:编写自定义边类 ```typescript import { BaseEdge } from '@antv/g6'; import type { BaseEdgeStyleProps } from '@antv/g6'; class MyLineEdge extends BaseEdge { // 定义边的样式,可以添加或覆盖默认样式 protected getKeyStyle(attributes: Required) { // 调用父类方法获取基础样式,然后添加自定义样式 return { ...super.getKeyStyle(attributes), lineWidth: 2, stroke: '#A4D3EE' }; } // 实现抽象方法:定义边的路径 // 这是 BaseEdge 的抽象方法,所有子类必须实现 protected getKeyPath(attributes) { // 获取源节点和目标节点 const { sourceNode, targetNode } = this; // 获取节点的位置坐标 const [x1, y1] = sourceNode.getPosition(); const [x2, y2] = targetNode.getPosition(); // 返回SVG路径数组,定义从起点到终点的直线 return [ ['M', x1, y1], ['L', x2, y2], ]; } } ``` :::success\{title=关键方法解析\} - `getKeyStyle`: 定义边的基本样式,如线宽、颜色等 - `getKeyPath`: 是 `BaseEdge` 中的抽象方法,**必须实现**,它定义了边的路径形状 ::: ### 第二步:注册自定义边 使用 `register` 方法注册边类型,这样 G6 才能识别你的自定义边: ```js import { ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.EDGE, 'my-line-edge', MyLineEdge); ``` `register` 方法需要三个参数: - 扩展类别:`ExtensionCategory.EDGE` 表示这是一个边类型 - 类型名称:`my-line-edge` 是我们给这个自定义边起的名字,后续会在配置中使用 - 类定义:`MyLineEdge` 是我们刚刚创建的边类 ### 第三步:应用自定义边 在图的配置中,通过设置 `edge.type` 来使用我们的自定义边: ```js const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 } }, { id: 'node2', style: { x: 300, y: 150 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, node: { style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, }, }, edge: { type: 'my-line-edge', style: { zIndex: 3, }, }, }); graph.render(); ``` 🎉 恭喜!你已经创建了第一个自定义边。 ## 更进一步:理解边绘制的原理 ### 原子图形 G6 的节点是由 [G 图形系统](https://g.antv.antgroup.com/) 提供的图形原子单元绘制而成。以下是常见图形元素及其用途: | 图形元素 | 类型 | 描述 | | -------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 圆形 | `circle` | 适合表示状态、头像、圆形按钮等。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Reference/Element/circle) 元素 | | 椭圆 | `ellipse` | 与 circle 类似,但支持横纵轴不同的场景。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Reference/Element/ellipse) 元素 | | 图片 | `image` | 用于展示图标、用户头像、LOGO 等。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/image) 元素 | | 直线 | `line` | 用于装饰、辅助连接等。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/line) 元素 | | 路径 | `path` | 支持复杂图形,如箭头、圆弧、曲线、贝塞尔路径等。路径中包含一组命令与参数,这些命令有不同的语义,[具体用法](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths) | | 多边形 | `polygon` | 支持自定义图形,如五角星、箭头。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/polygon) 元素 | | 折线 | `polyline` | 多点折线,适合复杂的连线结构。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/polyline) 元素 | | 矩形 | `rect` | 最常用图形,适合作为容器、卡片、按钮等基础结构。可以参考 SVG 的 [\](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/rect) 元素 | | 文本 | `text` | 显示名称、描述、标签等内容。提供简单的单行/多行文本排版能力,单行支持水平对齐、字符间距;多行支持显式换行符以及自动换行,垂直对齐 | > 更多原子图形和详细的属性请参考 [元素 - 图形(可选)](/zh/manual/element/shape/overview/) 所有这些图形都可通过 `upsert()` 动态创建或更新,并自动管理图形状态和生命周期。 ### 元素基类 开始自定义元素之前,你需要了解 G6 元素基类中的一些重要属性和方法: #### 属性 | 属性 | 类型 | 描述 | | ---------- | ----------------------------- | -------------------------- | | shapeMap | Record<string, DisplayObject> | 当前元素下所有图形的映射表 | | animateMap | Record<string, IAnimation> | 当前元素下所有动画的映射表 | #### 方法 #### `upsert(name, Ctor, style, container, hooks)`: 图形创建/更新 在创建自定义元素时,你会频繁用到 `upsert` 方法。它是 "update or insert" 的缩写,负责添加或更新元素中的图形: ```typescript upsert(key: string, Ctor: { new (...args: any[]): DisplayObject }, style: Record, container: DisplayObject); ``` | 参数 | 类型 | 描述 | | --------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | key | string | 图形的 key,即 `shapeMap` 中对应的 key。内置的 key 包括 `'key'` `'label'` `'halo'` `'icon'` `'port'` `'badge'`
key 不应使用特殊符号,会基于该值转化为驼峰形式调用 `getXxxStyle` 和 `drawXxxShape` 方法(见[元素约定](#元素约定)) | | Ctor | \{ new (...args: any[]): DisplayObject \} | 图形类 | | style | Record<string, any> | 图形样式 | | container | DisplayObject | 挂载图形的容器 | 例如,插入一个固定位置的紫色圆形: ```js this.upsert( 'element-key', // 元素的唯一标识 'circle', // 图形类型,如 'rect', 'circle' 等 { x: 100, y: 100, fill: '#a975f3' }, // 样式配置对象 container, // 父容器 ); ``` 为什么要使用 `upsert` 而不直接通过 `container.appendChild()` 创建图形?因为: 1. **性能更好**:当状态变化或数据更新时,会智能地复用已有图形,而不是删除再重建,大大提高了渲染性能 2. **代码更简洁**:不需要手动判断元素是否存在 3. **便于管理**:所有通过 `upsert` 创建的图形都会被记录在节点的 `shapeMap` 中,你可以通过 `this.getShape(key)` 轻松获取 #### `render(attributes, container)`: 渲染边的主入口 每个自定义边类都必须实现 `render(attributes, container)` 方法,它定义了该边如何被“绘制”出来。你可以在这里使用各种原子图形,组合出你想要的结构。 ```typescript render(style: Record, container: Group): void; ``` | 参数 | 类型 | 描述 | | --------- | ------------------- | -------- | | style | Record<string, any> | 元素样式 | | container | Group | 容器 | #### `getShape(name)`: 获取已创建的图形 有时,你需要在创建后修改某个子图形的属性,或者让子图形之间有交互关联。这时,`getShape` 方法可以帮你获取之前通过 `upsert` 创建的任何图形: **⚠️ 注意**:图形的顺序很重要,如果图形 B 依赖图形 A 的位置,必须确保 A 先创建 ### 元素约定 - **使用约定属性** 目前约定的元素属性包括: - 通过 `this.getSize()` 获取元素的尺寸 - 通过 `const [sourcePoint, targetPoint] = this.getEndpoints(attributes, false)` 获取边的起点和终点(简单模式 - 不考虑节点形状,直接返回节点中心点或最近连接桩中心˝位置) - 通过 `const [sourcePoint, targetPoint] = this.getEndpoints(attributes)` 获取边的起点和终点(优化模式 - 默认为 true,考虑节点形状,返回节点边界上的连接点) - **采用 `getXxxStyle` 和 `drawXxxShape` 配对的方式进行图形绘制** `getXxxStyle` 用于获取图形样式,`drawXxxShape` 用于绘制图形。通过该方式创建的图形支持自动执行动画。 > 其中 `Xxx` 是调用 [upsert](#方法) 方法时传入的 key 的驼峰形式。 - **可通过 `this.context` 访问 Graph 上下文** ### 生命周期钩子 提供了以下生命周期钩子函数,你可以在自定义边中重写这些方法,在关键时刻执行特定逻辑: | 钩子函数 | 触发时机 | 典型用途 | | ----------- | ------------------------ | ------------------------------------------ | | `onCreate` | 当边创建后完成入场动画时 | 绑定交互事件、初始化边状态、添加外部监听器 | | `onUpdate` | 当边更新后完成更新动画时 | 更新依赖数据、调整相关元素、触发联动效果 | | `onDestroy` | 当边完成退场动画并销毁后 | 清理资源、移除外部监听器、执行销毁通知 | ### 状态响应 G6 元素设计中最强大的一点,是可以将 **“状态响应”** 与 **“绘制逻辑”** 分离。 你可以在边配置中定义每种状态下的样式: ```js edge: { type: 'custom-edge', style: { stroke: '#eee' }, state: { selected: { stroke: '#f00', }, hover: { lineWidth: 3, stroke: '#1890ff', }, }, } ``` 切换状态的方法: ```js graph.setElementState(edgeId, ['selected']); ``` 这个状态会传入到 `render()` 方法的 `attributes` 中,由内部系统合并后的结果自动应用在图形上。 也可以根据状态自定义渲染逻辑: ```typescript protected getKeyStyle(attributes: Required) { const style = super.getKeyStyle(attributes); // 根据状态调整样式 if (attributes.states?.includes('selected')) { return { ...style, stroke: '#1890ff', lineWidth: 2, shadowColor: 'rgba(24,144,255,0.2)', shadowBlur: 15, }; } return style; } ``` ## 从简单到复杂 ### 自定义路径的折线边 ```ts import { Graph, register, BaseEdge, ExtensionCategory } from '@antv/g6'; class MyPolylineEdge extends BaseEdge { getKeyPath(attributes) { const [sourcePoint, targetPoint] = this.getEndpoints(attributes); return [ ['M', sourcePoint[0], sourcePoint[1]], ['L', targetPoint[0] / 2 + (1 / 2) * sourcePoint[0], sourcePoint[1]], ['L', targetPoint[0] / 2 + (1 / 2) * sourcePoint[0], targetPoint[1]], ['L', targetPoint[0], targetPoint[1]], ]; } } register(ExtensionCategory.EDGE, 'my-polyline-edge', MyPolylineEdge); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'node-0', style: { x: 100, y: 50, ports: [{ key: 'right', placement: [1, 0.5] }] } }, { id: 'node-1', style: { x: 250, y: 150, ports: [{ key: 'left', placement: [0, 0.5] }] } }, ], edges: [{ source: 'node-0', target: 'node-1' }], }, edge: { type: 'my-polyline-edge', style: { startArrow: true, endArrow: true, stroke: '#F6BD16', }, }, behaviors: ['drag-element'], }); graph.render(); ``` ### 额外标签 ```ts import { Graph, Line, register, BaseEdge, ExtensionCategory, subStyleProps } from '@antv/g6'; class LabelEdge extends Line { render(attributes, container) { super.render(attributes); this.drawEndLabel(attributes, container, 'start'); this.drawEndLabel(attributes, container, 'end'); } drawEndLabel(attributes, container, type) { const key = type === 'start' ? 'startLabel' : 'endLabel'; const [x, y] = this.getEndpoints(attributes)[type === 'start' ? 0 : 1]; const fontStyle = { x, y, dx: type === 'start' ? 15 : -15, fontSize: 16, fill: 'gray', textBaseline: 'middle', textAlign: type, }; const style = subStyleProps(attributes, key); const text = style.text; this.upsert(`label-${type}`, 'text', text ? { ...fontStyle, ...style } : false, container); } } register(ExtensionCategory.EDGE, 'extra-label-edge', LabelEdge); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'node-0', style: { x: 100, y: 100 } }, { id: 'node-1', style: { x: 300, y: 100 } }, ], edges: [{ source: 'node-0', target: 'node-1' }], }, edge: { type: 'extra-label-edge', style: { startArrow: true, endArrow: true, stroke: '#F6BD16', startLabelText: 'start', endLabelText: 'end', }, }, behaviors: ['drag-element'], }); graph.render(); ``` #### HTML节点 Html - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Html/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Html.md - Description: HTML节点 Html --- title: "HTML节点 Html" description: "HTML节点 Html" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Html/" version: "5.1.1" --- ## 概述 HTML 节点是一个自定义的矩形区域,用于显示 HTML 内容。它允许您在图形节点中嵌入任意的 HTML 元素,提供了极大的灵活性来创建复杂的自定义节点。 适用场景: - 用于表示复杂的自定义节点,如表格、图表或富文本 - 适合表示自定义的可视化元素或交互组件 - 常用于自定义图表、UI 设计、仪表板等场景 - 需要在节点中嵌入表单、按钮等交互元素时 ## 框架支持说明 > **💡 提示**: > > - **React 项目**:推荐使用 [React Node](/zh/manual/element/node/react-node/) 来实现更好的组件化开发体验 > - **Vue 项目**:目前暂不支持 Vue Node,欢迎社区共建贡献 > - **原生 HTML**:本文档介绍的 HTML 节点适用于原生 HTML 开发 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', style: { x: 300, y: 110, size: [120, 40], innerHTML: `
HTML Node
`, }, }, ], }, node: { type: 'html' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'html' }, 'type').disable(); const options = { size: 50, innerHTML: `
'HTML Node'
`, }; const optionFolder = gui.addFolder('html.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'innerHTML'); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `html` 以使用 HTML 节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | --------------------------------------------------------------- | --------------------------- | ------ | ---- | | dx | 横行偏移量。HTML 容器默认以左上角为原点,通过 dx 来进行横向偏移 | number | 0 | | | dy | 纵向偏移量。HTML 容器默认以左上角为原点,通过 dy 来进行纵向偏移 | number | 0 | | | innerHTML | HTML 内容,可以为字符串或者 `HTMLElement` | string | `HTMLElement` | - | ✓ | ## 示例 ### 基础HTML节点 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', data: { location: 'East', status: 'error', ip: '192.168.1.2' } }, { id: 'node-2', data: { location: 'West', status: 'overload', ip: '192.168.1.3' } }, { id: 'node-3', data: { location: 'South', status: 'running', ip: '192.168.1.4' } }, ], }, node: { type: 'html', style: { size: [240, 80], dx: -120, dy: -40, innerHTML: (d) => { const ICON_MAP = { error: '❌', overload: '⚡', running: '✅', }; const COLOR_MAP = { error: '#f5222d', overload: '#faad14', running: '#52c41a', }; const { data: { location, status, ip }, } = d; const color = COLOR_MAP[status]; return `
${location} Node
status: ${status} ${ICON_MAP[status]}
${ip}
`; }, }, }, layout: { type: 'grid', }, behaviors: ['drag-element', 'zoom-canvas'], }); graph.render(); ``` ### 带交互按钮的HTML节点 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'server-1', data: { name: 'Web Server', cpu: 45, memory: 67, status: 'online' } }, { id: 'server-2', data: { name: 'Database', cpu: 78, memory: 89, status: 'warning' } }, { id: 'server-3', data: { name: 'Cache Server', cpu: 23, memory: 34, status: 'offline' } }, ], }, node: { type: 'html', style: { size: [280, 210], dx: -140, dy: -105, innerHTML: (d) => { const { data } = d; const statusColors = { online: '#52c41a', warning: '#faad14', offline: '#f5222d', }; return `

${data.name}

${data.status.toUpperCase()}
CPU ${data.cpu}%
Memory ${data.memory}%
`; }, }, }, layout: { type: 'grid', cols: 2, }, behaviors: ['drag-element', 'zoom-canvas'], }); // 全局函数处理按钮点击 window.handleRestart = (nodeId) => { console.log(`重启服务器: ${nodeId}`); alert(`正在重启服务器 ${nodeId}...`); }; window.handleMonitor = (nodeId) => { console.log(`打开监控面板: ${nodeId}`); alert(`打开服务器 ${nodeId} 的监控面板`); }; graph.render(); ``` ### 表单输入HTML节点 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'form-1', data: { title: '用户信息', type: 'user-form' } }, { id: 'form-2', data: { title: '配置面板', type: 'config-form' } }, ], }, node: { type: 'html', style: { size: [300, 400], dx: -150, dy: -200, innerHTML: (d) => { const { data } = d; return `

${data.title}

`; }, }, }, layout: { type: 'grid', cols: 2, }, behaviors: ['drag-element', 'zoom-canvas'], }); // 全局函数处理表单操作 window.handleSave = (nodeId) => { console.log(`保存表单: ${nodeId}`); alert(`表单 ${nodeId} 已保存`); }; window.handleCancel = (nodeId) => { console.log(`取消表单: ${nodeId}`); alert(`取消表单 ${nodeId} 操作`); }; graph.render(); ``` ## 使用注意事项 ### 1. 性能优化 - HTML 节点相比普通图形节点有更高的渲染成本,建议在节点数量较少时使用 - 复杂的 HTML 结构会影响性能,建议保持结构简洁 - 避免在 HTML 中使用过多的动画效果 ### 2. 事件处理 - HTML 节点中的事件处理需要通过全局函数或事件委托来实现 - 建议将事件处理函数挂载到 `window` 对象上,确保在 HTML 字符串中可以访问 - 注意防止事件冒泡影响图的交互行为 ### 3. 样式隔离 - HTML 节点的样式可能会受到页面全局样式的影响 - 建议使用内联样式或确保样式的特异性足够高 - 考虑使用 CSS-in-JS 或样式命名空间来避免样式冲突 ### 4. 响应式设计 - HTML 节点的尺寸是固定的,不会自动适应内容 - 需要根据内容动态计算节点尺寸,或使用响应式布局 - 考虑在不同缩放级别下的显示效果 ### 5. 框架集成建议 - **React 项目**:推荐使用 [React Node](/zh/manual/element/node/react-node/),可以直接使用 React 组件作为节点内容 - **Vue 项目**:目前暂不支持 Vue Node,如有需求欢迎社区贡献 - **原生项目**:HTML 节点是最佳选择,提供了最大的灵活性 ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 3D D3力导向布局 D3Force3D - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/D3Force3DLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/D3Force3DLayout.md - Description: 3D D3力导向布局 D3Force3D --- title: "3D D3力导向布局 D3Force3D" description: "3D D3力导向布局 D3Force3D" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/D3Force3DLayout/" version: "5.1.1" --- ## 概述 D3Force3D 布局是基于 [d3-force](https://d3js.org/d3-force) 的三维扩展版本,通过在三维空间中模拟物理力的作用来实现自动布局。相比二维布局,它增加了 Z 轴方向的力作用,能够在三维空间中展现更丰富的数据关系。 3D 力导向布局示意图 ## 核心概念 ### 力系统 D3Force3D 在传统二维力导向布局的基础上,扩展了以下力的作用: - **三维中心力**:将节点拉向三维空间的中心点 - **三维碰撞力**:在三维空间中防止节点重叠 - **三维径向力**:将节点吸引到三维空间中的球面上 - **三维坐标力**:分别在 X、Y、Z 三个方向上施加作用力 ### 迭代系统 布局计算通过迭代来实现,主要涉及以下参数: - **alpha**:当前迭代的活力值,控制节点移动速度 - **alphaDecay**:活力值的衰减率 - **alphaMin**:最小活力值,低于此值停止迭代 - **velocityDecay**:速度衰减因子 ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | -------------------------------------------- | -------------------------------------------------------------------------- | ------------- | ---- | | type | 布局类型 | string | `d3-force-3d` | ✓ | | nodeSize | 节点大小(直径),用于碰撞检测防止节点重叠 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | 10 | | | iterations | 力的迭代次数,值越大布局越精确但性能消耗越大 | number | - | | | numDimensions | 维度数量,固定为 3 | number | 3 | | | forceSimulation | 自定义力模拟方法 | Simulation | - | | | onTick | 每次迭代的回调函数 | (data: LayoutMapping) => void | - | | | randomSource | 随机数生成函数 | () => number | - | | ### 迭代控制 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | --------------------- | ------ | ------ | ---- | | alpha | 当前迭代收敛阈值 | number | 1 | | | alphaDecay | 收敛阈值衰减率(0-1) | number | 0.028 | | | alphaMin | 停止迭代的阈值 | number | 0.001 | | | alphaTarget | 目标收敛阈值 | number | 0 | | | velocityDecay | 速度衰减因子 | number | 0.4 | | ### 力模型配置 #### 中心力(center) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ------------- | ------ | ------ | ---- | | center.x | 中心点 x 坐标 | number | 0 | | | center.y | 中心点 y 坐标 | number | 0 | | | center.z | 中心点 z 坐标 | number | 0 | | | center.strength | 力的强度 | number | 1 | | #### 碰撞力(collide) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------ | ------------------ | -------------------------------------------------------------------------- | ------ | ---- | | collide.radius | 碰撞半径 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | 10 | | | collide.strength | 力的强度 | number | 1 | | | collide.iterations | 碰撞检测的迭代次数 | number | 1 | | #### 链接力(link) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ---------------- | -------------------------------------------------------------------------- | ------- | ---- | | link.id | 边的 id 生成函数 | (edge: EdgeDatum, index: number, edges: EdgeDatum[]) => string | edge.id | | | link.distance | 理想边长 | number \| ((edge: EdgeDatum, index: number, edges: EdgeDatum[]) => number) | 30 | | | link.strength | 力的强度 | number \| ((edge: EdgeDatum, index: number, edges: EdgeDatum[]) => number) | 1 | | | link.iterations | 链接力的迭代次数 | number | 1 | | #### 多体力(manyBody) | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------------- | ------------------------- | -------------------------------------------------------------------------- | -------- | ---- | | manyBody.strength | 力的强度 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | -30 | | | manyBody.theta | Barnes-Hut 算法的精度参数 | number | 0.9 | | | manyBody.distanceMin | 最小作用距离 | number | 1 | | | manyBody.distanceMax | 最大作用距离 | number | Infinity | | #### 径向力(radial) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ----------- | -------------------------------------------------------------------------- | ------ | ---- | | radial.strength | 力的强度 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | 0.1 | | | radial.radius | 目标半径 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | 100 | | | radial.x | 球心 x 坐标 | number | 0 | | | radial.y | 球心 y 坐标 | number | 0 | | | radial.z | 球心 z 坐标 | number | 0 | | #### 坐标力(x、y、z) 每个方向的力可以单独配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------- | ---------------- | -------------------------------------------------------------------------- | ------ | ---- | | x.strength | X 轴方向的力强度 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | | x.x | 目标 x 坐标 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | | y.strength | Y 轴方向的力强度 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | | y.y | 目标 y 坐标 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | | z.strength | Z 轴方向的力强度 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | | z.z | 目标 z 坐标 | number \| ((node: NodeDatum, index: number, nodes: NodeDatum[]) => number) | - | | #### 全屏展示 Fullscreen - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Fullscreen/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Fullscreen.md - Description: 全屏展示 Fullscreen --- title: "全屏展示 Fullscreen" description: "全屏展示 Fullscreen" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Fullscreen/" version: "5.1.1" --- ## 概述 全屏展示插件允许用户将图可视化内容扩展到整个屏幕,提供更广阔的视图和更好的沉浸式体验。 ## 使用场景 全屏展示插件主要适用于以下场景: - 提供更广阔的视图,便于查看复杂图数据 - 增强沉浸式体验,专注于图可视化内容 - 在演示或报告中展示图数据 ## 基本用法 以下是一个简单的 Fullscreen 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', autoFit: true, trigger: { request: 'F', // 使用快捷键 F 进入全屏 exit: 'Esc', // 使用快捷键 Esc 退出全屏 }, onEnter: () => { console.log('进入全屏模式'); }, onExit: () => { console.log('退出全屏模式'); }, }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------- | ---------------------------------------------------- | ------------------------------------ | ------------ | ---- | | type | 插件类型 | string | `fullscreen` | ✓ | | key | 插件的唯一标识,可用于获取插件实例或更新插件选项 | string | - | | | autoFit | 是否自适应画布尺寸,全屏后画布尺寸会自动适应屏幕尺寸 | boolean | true | | | trigger | 触发全屏的方式,[示例](#trigger) | \{ request?: string; exit?: string; \} | - | | | onEnter | 进入全屏后的回调 | () => void | - | | | onExit | 退出全屏后的回调 | () => void | - | | ### trigger trigger 属性用于控制触发全屏的方式。它支持两种配置方式: #### 快捷键配置 使用键盘快捷键来触发全屏和退出全屏。 ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', trigger: { request: 'F', // 使用快捷键 F 进入全屏 exit: 'Esc', // 使用快捷键 Esc 退出全屏 }, }, ], }); ``` #### 自定义触发 通过调用 request 和 exit 方法来控制全屏。 ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', key: 'my-fullscreen', }, ], }); // 进入全屏 graph.getPluginInstance('my-fullscreen').request(); // 退出全屏 graph.getPluginInstance('my-fullscreen').exit(); ``` ### autoFit 是否自适应画布尺寸,全屏后画布尺寸会自动适应屏幕尺寸。 - 设置为 true 时,画布会自动调整大小以适应整个屏幕。 - 设置为 false 时,画布大小保持不变。 ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', autoFit: true, }, ], }); ``` ## API ### Fullscreen.request() 这个方法可以让你通过代码进入全屏模式。调用插件实例上的这个方法,就能把图形内容扩展到整个屏幕。 ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', key: 'my-fullscreen', }, ], }); // 进入全屏 graph.getPluginInstance('my-fullscreen').request(); ``` ### Fullscreen.exit() 这个方法可以让你通过代码退出全屏模式。调用插件实例上的这个方法,就能把图形内容恢复到原来的大小。 ```js const graph = new Graph({ plugins: [ { type: 'fullscreen', key: 'my-fullscreen', }, ], }); // 退出全屏 graph.getPluginInstance('my-fullscreen').exit(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ data: { nodes: Array.from({ length: 20 }).map((_, i) => ({ id: `node${i}` })) }, autoFit: 'center', background: '#fff', plugins: [ { type: 'fullscreen', key: 'fullscreen', }, function () { const graph = this; return { type: 'toolbar', key: 'toolbar', position: 'top-left', onClick: (item) => { const fullscreenPlugin = graph.getPluginInstance('fullscreen'); if (item === 'request-fullscreen') { fullscreenPlugin.request(); } if (item === 'exit-fullscreen') { fullscreenPlugin.exit(); } }, getItems: () => { return [ { id: 'request-fullscreen', value: 'request-fullscreen' }, { id: 'exit-fullscreen', value: 'exit-fullscreen' }, ]; }, }; }, ], }); graph.render(); ``` #### 从 5.0 升级到 5.1(布局) - Canonical page: https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade-to-5-1/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade-to-5-1.md - Description: 从 5.0 升级到 5.1(布局) --- title: "从 5.0 升级到 5.1(布局)" description: "从 5.0 升级到 5.1(布局)" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/whats-new/upgrade-to-5-1/" version: "5.1.1" --- 本文档聚焦 G6 `5.1` 中布局文档的写法调整。`5.1` 的布局页面会优先展示与 `@antv/layout` 对齐后的字段;`5.0` 中常见的布局写法统一收敛到本文档中,便于迁移时对照。 ## 总体变化 - `5.1` 起,布局文档会优先展示 `@antv/layout` 的公共字段,例如 `width` `height` `center` `enableWorker` `node` `edge` - 各布局页主要保留 `5.1` 推荐写法,`5.0` 中常见写法请以本文档为准 - 迁移时,建议先按旧项目中的字段定位,再映射到 `5.1` 文档里的推荐配置 ## D3Force:center force 改为快捷字段 `5.0` 文档中,常见把中心力写在 `center` 中: ```typescript { layout: { type: 'd3-force', center: { x: 250, y: 150, strength: 0.8, }, }, } ``` `5.1` 文档中推荐写成更直接的快捷字段: ```typescript { layout: { type: 'd3-force', centerX: 250, centerY: 150, centerStrength: 0.8, }, } ``` - `center.x` 对应 `centerX` - `center.y` 对应 `centerY` - `center.strength` 对应 `centerStrength` 如果你需要继续对照完整字段说明,可查看 [D3Force 布局](/zh/manual/layout/D3ForceLayout/)。 ## ComboCombined:innerLayout / outerLayout 收敛为 layout `5.0` 文档中,常见分别配置 Combo 内部布局和最外层布局: ```typescript import { ConcentricLayout, ForceLayout } from '@antv/layout'; { layout: { type: 'combo-combined', innerLayout: new ConcentricLayout({ sortBy: 'id', }), outerLayout: new ForceLayout({ gravity: 1, }), }, } ``` `5.1` 文档中推荐使用单个 `layout` 字段,根据 `comboId` 为不同层级返回布局配置: ```typescript { layout: { type: 'combo-combined', layout: (comboId) => comboId ? { type: 'concentric', sortBy: 'id' } : { type: 'force', gravity: 1 }, }, } ``` - `comboId` 有值时,表示当前为 Combo 内部层级 - `comboId` 为空时,表示当前为最外层布局 - 多层布局选择统一收敛到 `layout` 入口 如果你需要查看 `5.1` 推荐写法,可查看 [ComboCombined 布局](/zh/manual/layout/ComboCombinedLayout/)。 ## 迁移建议 1. 先按旧项目中的布局类型定位到本文档对应条目 2. 再把 `5.0` 字段映射成 `5.1` 文档里的推荐写法 3. 最后回到具体布局页,核对公共字段和默认值 #### 力导向拖拽元素 DragElementForce - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/DragElementForce/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/DragElementForce.md - Description: 力导向拖拽元素 DragElementForce --- title: "力导向拖拽元素 DragElementForce" description: "力导向拖拽元素 DragElementForce" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/DragElementForce/" version: "5.1.1" --- ## 概述 DragElementForce 是 G6 中用于实现 `d3-force` 和 `d3-force-3d` 布局下节点拖拽的内置交互。在拖拽过程中会 **实时重新计算布局**,使得图的布局能够动态调整以适应节点的新位置。 力导向拖拽元素效果图 ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-element-force'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'drag-element-force', key: 'drag-element-force-1', fixed: true, // 拖拽后固定节点位置 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------- | ---- | | type | 交互类型名称,这里设置 `type: 'drag-element-force'` 启用此交互 | string | `drag-element-force` | ✓ | | key | 交互唯一标识符,用于后续操作交互 | string | - | | | fixed | 在拖拽结束后,节点是否保持固定位置,布尔值代表:
- true: 在拖拽结束后,节点的位置将保持固定,不受布局算法的影响
- false: 在拖拽结束后,节点的位置将继续受到布局算法的影响 | boolean | false | | | enable | 是否启用拖拽功能,默认可以拖拽节点和 Combo | boolean \| ((event: IElementDragEvent) => boolean) | `['node', 'combo'].includes(event.targetType)` | | | state | 节点选中状态的标识,启用多选时会基于该状态查找选中的节点 | string | `selected` | | | hideEdge | 控制拖拽过程中边的显示状态,可选值有:
- `none`: 不隐藏任何边
- `out`: 隐藏以当前节点为源节点的边
- `in`: 隐藏以当前节点为目标节点的边
- `both`: 隐藏与当前节点相关的所有边
- `all`: 隐藏图中所有边
⚠️ 注意:当启用 `shadow`(幽灵节点)时,`hideEdge` 配置将不生效。 | `none` \| `all` \| `in` \| `out` \| `both` | `none` | | | cursor | 自定义鼠标样式,[示例](#cursor) | \{ default?: Cursor; grab: Cursor; grabbing: Cursor \} | - | | | trigger | 同时按下快捷键才能拖拽元素 **按键参考:** _MDN Key Values_ 。若设为**空数组**时则表示不需要按下其他按键配合
⚠️ 注意,`trigger` 设置为 `['drag']` 时会导致 `drag-canvas` 行为失效。两者不可同时配置。 | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | [] | | ### cursor `cursor` 用于自定义拖拽过程中的鼠标指针样式: - `default`: 默认状态下的指针样式 - `grab`: 鼠标悬停在可拖拽元素上时的指针样式 - `grabbing`: 正在拖拽时的指针样式 可选值有:`auto` | `default` | `none` | `context-menu` | `help` | `pointer` | `progress` | `wait` | `cell` | `crosshair` | `text` | `vertical-text` | `alias` | `copy` | `move` | `no-drop` | `not-allowed` | `grab` | `grabbing` | `all-scroll` | `col-resize` | `row-resize` | `n-resize` | `e-resize` | `s-resize` | `w-resize` | `ne-resize` | `nw-resize` | `se-resize` | `sw-resize` | `ew-resize` | `ns-resize` | `nesw-resize` | `nwse-resize` | `zoom-in` | `zoom-out` 示例配置: ```js cursor: { default: 'default', // 默认使用普通指针 grab: 'grab', // 可拖拽时显示抓取指针 grabbing: 'grabbing' // 拖拽中显示抓取中指针 } ``` ## 常见问题 ### 1. DragElementForce 和 DragElement 有什么区别? - `DragElementForce` 专门用于 `d3-force` 或 `d3-force-3d` 布局,拖拽时会实时重新计算布局 - `DragElement` 是通用的拖拽交互,不会触发布局重新计算 ## 实际案例 ### 网格效果 ```ts import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; function getData(size = 10) { const nodes = Array.from({ length: size * size }, (_, i) => ({ id: `${i}` })); const edges = []; for (let y = 0; y < size; ++y) { for (let x = 0; x < size; ++x) { if (y > 0) edges.push({ source: `${(y - 1) * size + x}`, target: `${y * size + x}` }); if (x > 0) edges.push({ source: `${y * size + (x - 1)}`, target: `${y * size + x}` }); } } return { nodes, edges }; } const graph = new Graph({ data: getData(), layout: { type: 'd3-force', manyBody: { strength: -30, }, link: { strength: 1, distance: 20, iterations: 10, }, }, node: { style: { size: 10, fill: '#000', }, }, edge: { style: { stroke: '#000', }, }, behaviors: [{ type: 'drag-element-force' }, 'zoom-canvas'], }); graph.render(); addPanel((gui) => { gui.add({ msg: 'Try to drag nodes' }, 'msg').name('Tips').disable(); }); ``` ### 固定被拖拽的节点 ```ts import { Graph } from '@antv/g6'; const data = { nodes: new Array(10).fill(0).map((_, i) => ({ id: `${i}`, label: `${i}` })), edges: [ { source: '0', target: '1' }, { source: '0', target: '2' }, { source: '0', target: '3' }, { source: '0', target: '4' }, { source: '0', target: '5' }, { source: '0', target: '7' }, { source: '0', target: '8' }, { source: '0', target: '9' }, { source: '2', target: '3' }, { source: '4', target: '5' }, { source: '4', target: '6' }, { source: '5', target: '6' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.label, labelPlacement: 'middle', labelFill: '#fff', }, }, layout: { type: 'd3-force', link: { distance: 100, strength: 2, }, collide: { radius: 40, }, }, behaviors: [ { type: 'drag-element-force', fixed: true, }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 图片节点 Image - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Image/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Image.md - Description: 图片节点 Image --- title: "图片节点 Image" description: "图片节点 Image" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Image/" version: "5.1.1" --- ## 概述 图片节点是一个矩形区域,用于显示图像。 适用场景: - 用于表示用户头像、产品图片或图标。 - 适合表示社交网络、产品目录或图标集合。 - 常用于社交网络图、产品图、UI 设计等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [ { id: 'node1', style: { size: 60, src: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', }, }, ], }, node: { type: 'image' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'image' }, 'type').disable(); const options = { size: 60, src: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', }; const optionFolder = gui.addFolder('image.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'src'); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `image` 以使用图片节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---- | -------------------------- | ------ | ------ | ---- | | img | 该属性为 img 的别名 | string | - | | | src | 图片来源,即图片地址字符串 | string | - | ✓ | ## 示例 ### 内置图片节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'image', style: { size: 40, labelText: (d) => d.id, src: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', haloStroke: '#227eff', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, state: { inactive: { fillOpacity: 0.5, }, disabled: { fillOpacity: 0.2, }, }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### D3力导向布局 D3Force - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/D3ForceLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/D3ForceLayout.md - Description: D3力导向布局 D3Force --- title: "D3力导向布局 D3Force" description: "D3力导向布局 D3Force" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/D3ForceLayout/" version: "5.1.1" --- ## 概述 D3Force 布局是基于 [d3-force](https://d3js.org/d3-force) 实现的力导向布局。它通过模拟物理力的作用(如引力、斥力、碰撞等),使图布局达到一个能量最小的稳定状态。 这种布局的主要特点是: 1. **自动排列**:不需要手动设置节点位置,系统会自动找到合适的位置 2. **实时调整**:当你拖动某个节点时,其他节点会实时跟随调整位置 3. **灵活配置**: - 可以调整节点间的吸引力和排斥力 - 可以设置边的理想长度 - 可以固定某些重要节点的位置 4. **动画效果**:节点移动时会有平滑的动画,让变化更自然 D3Force 布局示意图 ## 核心概念 ### 力系统 Force System D3Force 布局通过模拟五种不同的力来实现自动布局。想象一个物理世界,这些力同时作用,最终达到平衡: force > 注:图中不同颜色的箭头代表不同类型的力,实际布局中这些力是无形的,同时也会受其他力影响。 - **链接力**(Link Force):想象节点之间连着橡皮筋,可以把相连的节点拉到合适的距离。橡皮筋的松紧度就是力的强度(strength),理想长度就是我们设置的距离(distance)。 - **多体力**(Many-Body Force):类似磁铁的效果,可以让所有节点互相吸引或排斥。力的强度为负值时节点会互相排斥(像相同磁极),为正值时会互相吸引(像相反磁极)。这个力决定了图的疏密程度。 - **中心力**(Center Force):就像所有节点都被一根看不见的绳子拴在画布中心。这个力可以防止节点飘得太远,让整个图保持在画布的中心位置。 - **碰撞力**(Collision Force):让节点变成有实体大小的小球,当节点太近时会自动弹开。这个力主要用来防止节点重叠,提高图的可读性。 - **径向力**(Radial Force):想象有一个看不见的圆环,这个力会把节点吸引到圆环上。通过设置圆的半径和力的强度,可以让节点形成漂亮的环形布局。 ### 迭代系统(Iteration System) 布局计算是一个反复调整的过程,包含两个关键概念: #### Alpha 值(活力值) 就像布局的"能量",决定节点移动的剧烈程度: - **初始状态**:Alpha = 1,节点移动剧烈 - **计算过程**:Alpha 值逐渐降低,节点移动变缓 - **结束状态**:当 Alpha < alphaMin 时,节点停止移动 #### 迭代次数(Iterations) 控制每次计算时力的作用次数: - **作用**:值越大,布局越精确,但计算越慢 - **调节**: - 简单图:使用默认值即可 - 复杂图:可以适当增加迭代次数 - 实时交互:建议使用较小的迭代次数 > 提示:迭代次数(iterations)和活力值(alpha)是相互配合的。增加迭代次数可以让每一步计算更精确,而活力值则控制整体计算的进度。 ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | --------------------------------------------- | ------------------------------------------ | ---------- | ---- | | type | 布局类型 | string | 'd3-force' | ✓ | | centerX | 布局中心点 x 坐标 | number | width / 2 | | | centerY | 布局中心点 y 坐标 | number | height / 2 | | | centerStrength | 中心力强度 | number | - | | | nodeSize | 节点大小(直径),用于碰撞检测防止节点重叠 | number \| ((node, index, nodes) => number) | 10 | | | nodeSpacing | 节点间额外间距 | number \| ((node, index, nodes) => number) | 0 | | | iterations | 力的迭代次数,值越大布局越精确但性能消耗越大 | number | - | | | onTick | 每次迭代的回调函数,用于实时获取布局结果 | (data: LayoutMapping) => void | - | | | forceSimulation | 自定义力模拟方法,若不指定则使用 d3.js 的方法 | Simulation<NodeDatum, EdgeDatum> | - | | | randomSource | 用于生成随机数的函数 | () => number | - | | ### 迭代控制 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------- | ------------------------------------------------------ | ------ | ------ | ---- | | alpha | 当前迭代的收敛阈值,控制布局的活跃程度 | number | 1 | | | alphaMin | 停止迭代的最小阈值,当 alpha 小于该值时停止迭代 | number | 0.001 | | | alphaDecay | 收敛阈值的衰减率,范围 [0, 1],0.028 对应约 300 次迭代 | number | 0.028 | | | alphaTarget | 目标收敛阈值,系统会尝试将 alpha 收敛到该值 | number | 0 | | | velocityDecay | 速度衰减因子,值越大节点运动越缓慢 | number | 0.4 | | ### 力模型配置 #### 链接力(link) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ---------------------------------- | ------------------------------------------ | ----------- | ---- | | link.id | 边的 id 生成函数 | (edge, index, edges) => string | (e) => e.id | | | link.distance | 理想边长,边会趋向于该长度 | number \| ((edge, index, edges) => number) | 30 | | | link.strength | 力的强度,值越大边长越接近理想边长 | number \| ((edge, index, edges) => number) | 1 | | | link.iterations | 链接力的迭代次数 | number | 1 | | #### 多体力(manyBody) | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------------- | ----------------------------------------------------- | ------------------------------------------ | -------- | ---- | | manyBody.strength | 力的强度,负值为斥力,正值为引力 | number \| ((node, index, nodes) => number) | -30 | | | manyBody.theta | Barnes-Hut 算法的精度参数,值越小越精确但性能消耗越大 | number | 0.9 | | | manyBody.distanceMin | 最小作用距离,防止力过大 | number | 1 | | | manyBody.distanceMax | 最大作用距离,超过该距离的节点不产生力 | number | Infinity | | #### 中心力(center) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ---------------------------------- | ------ | ------ | ---- | | center.x | 中心点 x 坐标 | number | - | | | center.y | 中心点 y 坐标 | number | - | | | center.strength | 力的强度,值越大节点越趋向于中心点 | number | - | | > 补充:5.1 中推荐优先使用 `centerX` / `centerY` 作为快捷配置;如果直接配置 `center` force,则按 d3-force 原生写法生效。 #### 碰撞力(collide) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------ | -------------------------------------- | ------------------------------------------ | ------ | ---- | | collide.radius | 碰撞半径,小于该距离的节点会产生排斥力 | number \| ((node, index, nodes) => number) | 10 | | | collide.strength | 力的强度,值越大排斥效果越明显 | number | 1 | | | collide.iterations | 碰撞检测的迭代次数 | number | 1 | | #### 径向力(radial) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | -------------------------------------- | ------------------------------------------ | ------ | ---- | | radial.strength | 力的强度,值越大节点越趋向于目标半径 | number \| ((node, index, nodes) => number) | 0.1 | | | radial.radius | 目标半径,节点会被吸引到该半径的圆周上 | number \| ((node, index, nodes) => number) | 100 | | | radial.x | 圆心 x 坐标 | number | 0 | | | radial.y | 圆心 y 坐标 | number | 0 | | #### X 轴力(x) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------- | ----------------------------------- | ------------------------------------------ | ------ | ---- | | x.strength | X 轴方向的力强度 | number \| ((node, index, nodes) => number) | - | | | x.x | 目标 x 坐标,节点会被吸引到这个位置 | number \| ((node, index, nodes) => number) | - | | #### Y 轴力(y) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------- | ----------------------------------- | ------------------------------------------ | ------ | ---- | | y.strength | Y 轴方向的力强度 | number \| ((node, index, nodes) => number) | - | | | y.y | 目标 y 坐标,节点会被吸引到这个位置 | number \| ((node, index, nodes) => number) | - | | ## 代码示例 ### 防止节点重叠 ```js { layout: { type: 'd3-force', collide: { // Prevent nodes from overlapping by specifying a collision radius for each node. radius: (d) => d.size / 2, }, }, } ``` 效果见 [示例 - 力导向布局防止节点重叠](/zh/examples/layout/force-directed/prevent-overlap/) ### 团队聚类布局 该示例展示了如何使用力导向布局实现团队聚类效果,不同团队的节点会自动聚集在一起。 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 500, height: 250, autoFit: 'view', data: { nodes: [ // 团队 A { id: 'A1', team: 'A', label: 'A1', size: 30 }, { id: 'A2', team: 'A', label: 'A2', size: 20 }, { id: 'A3', team: 'A', label: 'A3', size: 20 }, { id: 'A4', team: 'A', label: 'A4', size: 20 }, // 团队 B { id: 'B1', team: 'B', label: 'B1', size: 30 }, { id: 'B2', team: 'B', label: 'B2', size: 20 }, { id: 'B3', team: 'B', label: 'B3', size: 20 }, { id: 'B4', team: 'B', label: 'B4', size: 20 }, // 团队 C { id: 'C1', team: 'C', label: 'C1', size: 30 }, { id: 'C2', team: 'C', label: 'C2', size: 20 }, { id: 'C3', team: 'C', label: 'C3', size: 20 }, { id: 'C4', team: 'C', label: 'C4', size: 20 }, ], edges: [ // 团队 A 内部连接 { source: 'A1', target: 'A2' }, { source: 'A1', target: 'A3' }, { source: 'A1', target: 'A4' }, // 团队 B 内部连接 { source: 'B1', target: 'B2' }, { source: 'B1', target: 'B3' }, { source: 'B1', target: 'B4' }, // 团队 C 内部连接 { source: 'C1', target: 'C2' }, { source: 'C1', target: 'C3' }, { source: 'C1', target: 'C4' }, // 团队间的少量连接 { source: 'A1', target: 'B1' }, { source: 'B1', target: 'C1' }, ], }, node: { style: { size: (d) => d.size, fill: (d) => { // 不同团队使用不同颜色 const colors = { A: '#FF6B6B', B: '#4ECDC4', C: '#45B7D1', }; return colors[d.team]; }, labelText: (d) => d.label, labelPlacement: 'center', labelFill: '#fff', }, }, edge: { style: { stroke: '#aaa', }, }, layout: { type: 'd3-force', // 配置链接力 - 团队内部节点更靠近 link: { distance: (d) => { // 同一团队内的连接距离更短 if (d.source.team === d.target.team) return 50; // 不同团队间的连接距离更长 return 200; }, strength: (d) => { // 同一团队内的连接强度更大 if (d.source.team === d.target.team) return 0.7; // 不同团队间的连接强度更小 return 0.1; }, }, // 配置多体力 - 控制节点间的排斥力 manyBody: { strength: (d) => { // 团队领导节点(编号1)的排斥力更强 if (d.label.endsWith('1')) return -100; return -30; }, }, // 配置碰撞力 - 防止节点重叠 collide: { radius: 35, strength: 0.8, }, // 配置中心力 - 保持图形在画布中心 center: { strength: 0.05, }, }, behaviors: ['drag-element-force'], }); graph.render(); ```
展开查看完整代码 ```javascript import { Graph } from '@antv/g6'; // 创建模拟数据,包含不同团队的节点 const data = { nodes: [ // 团队 A { id: 'A1', team: 'A', label: 'A1', size: 30 }, { id: 'A2', team: 'A', label: 'A2', size: 20 }, { id: 'A3', team: 'A', label: 'A3', size: 20 }, { id: 'A4', team: 'A', label: 'A4', size: 20 }, // 团队 B { id: 'B1', team: 'B', label: 'B1', size: 30 }, { id: 'B2', team: 'B', label: 'B2', size: 20 }, { id: 'B3', team: 'B', label: 'B3', size: 20 }, { id: 'B4', team: 'B', label: 'B4', size: 20 }, // 团队 C { id: 'C1', team: 'C', label: 'C1', size: 30 }, { id: 'C2', team: 'C', label: 'C2', size: 20 }, { id: 'C3', team: 'C', label: 'C3', size: 20 }, { id: 'C4', team: 'C', label: 'C4', size: 20 }, ], edges: [ // 团队 A 内部连接 { source: 'A1', target: 'A2' }, { source: 'A1', target: 'A3' }, { source: 'A1', target: 'A4' }, // 团队 B 内部连接 { source: 'B1', target: 'B2' }, { source: 'B1', target: 'B3' }, { source: 'B1', target: 'B4' }, // 团队 C 内部连接 { source: 'C1', target: 'C2' }, { source: 'C1', target: 'C3' }, { source: 'C1', target: 'C4' }, // 团队间的少量连接 { source: 'A1', target: 'B1' }, { source: 'B1', target: 'C1' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: (d) => d.size, fill: (d) => { // 不同团队使用不同颜色 const colors = { A: '#FF6B6B', B: '#4ECDC4', C: '#45B7D1', }; return colors[d.team]; }, labelText: (d) => d.label, labelPlacement: 'center', labelFill: '#fff', }, }, edge: { style: { stroke: '#aaa', }, }, layout: { type: 'd3-force', // 配置链接力 - 团队内部节点更靠近 link: { distance: (d) => { // 同一团队内的连接距离更短 if (d.source.team === d.target.team) return 50; // 不同团队间的连接距离更长 return 200; }, strength: (d) => { // 同一团队内的连接强度更大 if (d.source.team === d.target.team) return 0.7; // 不同团队间的连接强度更小 return 0.1; }, }, // 配置多体力 - 控制节点间的排斥力 manyBody: { strength: (d) => { // 团队领导节点(编号1)的排斥力更强 if (d.label.endsWith('1')) return -100; return -30; }, }, // 配置碰撞力 - 防止节点重叠 collide: { radius: 35, strength: 0.8, }, // 配置中心力 - 保持图形在画布中心 center: { strength: 0.05, }, }, behaviors: ['drag-element-force'], }); graph.render(); ```
主要配置说明: - `link.distance`:团队内部距离短,团队间距离长 - `link.strength`:团队内部连接强度大,团队间连接强度小 - `manyBody.strength`:控制节点间排斥力 - `collide`:防止节点重叠 - `center`:保持整体布局在画布中心 还可以参考 [定制不同节点的参数](/zh/examples/layout/force-directed/functional-params/) 示例。 #### 网格线 GridLine - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/GridLine/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/GridLine.md - Description: 网格线 GridLine --- title: "网格线 GridLine" description: "网格线 GridLine" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/GridLine/" version: "5.1.1" --- ## 概述 网格线插件为画布提供可视化辅助线,帮助用户精确定位和对齐图形元素,是图形绘制中不可或缺的辅助工具。 ## 使用场景 网格线插件主要适用于以下场景: - 辅助用户精确绘图和元素对齐 - 提供视觉参考,增强空间感知 - 在设计和编辑图形时构建结构化的参考系统 ## 基本用法 以下是一个简单的 GridLine 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'grid-line', key: 'my-grid-line', // 指定唯一标识符,便于后续动态更新 size: 20, stroke: '#0001', follow: true, }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node-1' }] }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, layout: { type: 'force' }, behaviors: ['drag-canvas'], plugins: [{ type: 'grid-line', key: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { const LINE_STYLE = ['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']; const options = { type: 'grid-line', border: true, borderLineWidth: 1, borderStroke: '#eee', borderStyle: 'solid', follow: false, lineWidth: 1, size: 20, stroke: '#eee', }; const optionFolder = gui.addFolder('Gird Line Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'size', 1, 50, 1); optionFolder.add(options, 'lineWidth', 1, 10, 1); optionFolder.addColor(options, 'stroke'); optionFolder.add(options, 'border'); optionFolder.add(options, 'borderLineWidth', 1, 10, 1); optionFolder.add(options, 'borderStyle', LINE_STYLE); optionFolder.addColor(options, 'borderStroke'); optionFolder.add(options, 'follow'); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'grid-line', [property]: value, }); graph.render(); }); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ----------- | ---- | | type | 插件类型 | string | `grid-line` | ✓ | | key | 插件的唯一标识,可用于获取插件实例或更新插件选项 | string | - | | | border | 是否显示边框 | boolean | true | | | borderLineWidth | 边框线宽 | number | 1 | | | borderStroke | 边框颜色,详细属性参考 [CSS border-color](https://developer.mozilla.org/zh-CN/docs/Web/CSS/border-color) | string | `#eee` | | | borderStyle | 边框样式,详细属性参考 [CSS border-style](https://developer.mozilla.org/zh-CN/docs/Web/CSS/border-style) | string | `solid` | | | follow | 是否跟随画布移动 | boolean \| \{translate ?: boolean, zoom?: boolean\} | false | | | lineWidth | 网格线宽度 | number \| string | 1 | | | size | 网格单元大小,单位为像素 | number | 20 | | | stroke | 网格线颜色 | string | `#eee` | | ### follow `follow` 属性用于控制网格线是否跟随画布的变换操作。它支持两种配置方式: 1. **布尔值配置**:当设置为 `true` 时,网格线会同时跟随画布的平移和缩放;设置为 `false` 时则保持静态。 ```js // 同时启用跟随平移和缩放 const graph = new Graph({ plugins: [ { type: 'grid-line', follow: true, }, ], }); ``` 2. **对象配置**:可以更精细地控制网格线的跟随行为。 ```js // 仅跟随平移,不跟随缩放 const graph = new Graph({ plugins: [ { type: 'grid-line', follow: { translate: true, // 跟随平移 zoom: false, // 不跟随缩放 }, }, ], }); // 仅跟随缩放,不跟随平移 const graph = new Graph({ plugins: [ { type: 'grid-line', follow: { translate: false, // 不跟随平移 zoom: true, // 跟随缩放 }, }, ], }); ``` 当网格线跟随缩放时,它会保持与画布内容的相对位置关系,使得对齐参考更加精准。跟随平移则让网格随着画布内容一起移动,增强空间连续性的视觉体验。 ## 代码示例 ### 基础网格线 最简单的方式是直接使用预设配置: ```js const graph = new Graph({ // 其他配置... plugins: ['grid-line'], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, data: { nodes: [{ id: 'node-1', style: { x: 150, y: 75 } }] }, behaviors: ['drag-canvas'], plugins: ['grid-line'], }); graph.render(); ``` ### 自定义样式 您可以根据需要自定义网格线的样式: ```js const graph = new Graph({ // 其他配置... plugins: [ { type: 'grid-line', stroke: '#1890ff33', // 蓝色半透明网格线 lineWidth: 2, size: 40, // 更大的网格单元 borderStroke: '#1890ff', // 蓝色边框 borderLineWidth: 2, }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, data: { nodes: [{ id: 'node-1', style: { x: 150, y: 75 } }] }, behaviors: ['drag-canvas'], plugins: [ { type: 'grid-line', stroke: '#1890ff33', // 蓝色半透明网格线 lineWidth: 2, size: 40, // 更大的网格 borderStroke: '#1890ff', // 蓝色边框 borderLineWidth: 2, }, ], }); graph.render(); ``` ### 跟随移动 启用 follow 选项可以让网格跟随画布移动,增强用户体验: ```js const graph = new Graph({ // 其他配置... behaviors: ['drag-canvas', 'zoom-canvas'], plugins: [ { type: 'grid-line', follow: true, // 网格跟随画布移动 }, ], }); ``` 试着拖拽/缩放画布,观察网格的跟随效果: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, data: { nodes: [{ id: 'node-1', style: { x: 150, y: 75 } }] }, behaviors: ['drag-canvas', 'zoom-canvas'], plugins: [ { type: 'grid-line', follow: true, // 网格跟随画布移动 }, ], }); graph.render(); ``` ### 动态更新网格 使用 key 标识符可以在运行时动态更新网格属性: ```js // 初始化配置 const graph = new Graph({ // 其他配置... plugins: [ { type: 'grid-line', key: 'my-grid', size: 20, }, ], }); // 后续动态更新 graph.updatePlugin({ key: 'my-grid', size: 40, // 更新网格大小 stroke: '#ff4d4f', // 更新网格颜色 }); ``` ## 实际案例 ```ts import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['drag-canvas'], plugins: [{ key: 'grid-line', type: 'grid-line', follow: false }], }); graph.render(); addPanel((gui) => { gui .add({ follow: false }, 'follow') .name('Follow') .onChange((value) => { graph.updatePlugin({ key: 'grid-line', follow: value, }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 缩放画布时固定元素大小 FixElementSize - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/FixElementSize/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/FixElementSize.md - Description: 缩放画布时固定元素大小 FixElementSize --- title: "缩放画布时固定元素大小 FixElementSize" description: "缩放画布时固定元素大小 FixElementSize" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/FixElementSize/" version: "5.1.1" --- ## 概述 FixElementSize 是 G6 提供的一种内置交互,用于在视图缩放过程中,**保持节点中某些元素的尺寸不随缩放变化。** 提升缩放过程中的视觉一致性与可操作性。 通过监听视口变化,自动对标记为“固定尺寸”的元素进行缩放补偿,确保它们在不同缩放级别下保持相对恒定的显示尺寸。支持全局启用,也支持按需控制具体元素或节点的适配行为。 ## 使用场景 这一交互主要用于: - 需要固定视觉大小的图形元素或嵌入式组件(按钮、标签等) ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node1', style: { x: 200, y: 100, labelText: 'node1' } }, { id: 'node2', style: { x: 360, y: 100, labelText: 'node2' } }, { id: 'node3', style: { x: 280, y: 220, labelText: 'node3' } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node3' }, ], }, node: { style: { label: true, labelFill: '#666', labelFontSize: 14, labelPlacement: 'bottom' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: ['zoom-canvas', 'drag-canvas', { key: 'fix-element-size', type: 'fix-element-size' }], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 800, height: 400 }, (gui, graph) => { const options = { key: 'fix-element-size', type: 'fix-element-size', animation: true, enable: true, reset: true, }; const optionFolder = gui.addFolder('CollapseExpand Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'reset'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'fix-element-size', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互 **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['fix-element-size'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'fix-element-size', enable: true, // 开启该交互 state: 'selected', // 要固定大小的元素状态 reset: true, // 元素重绘时还原样式 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ----------- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ---- | | type | 交互类型名称 | string | `fix-element-size` | √ | | enable | 是否启用该交互,[示例](#enable) | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | reset | 元素重绘时是否还原样式 | boolean | `false` | | | state | 指定要固定大小的元素状态 | string | "" | | | node | 节点配置项,用于定义哪些属性在视觉上保持固定大小。若未指定(即为 undefined),则整个节点将被固定,[示例](#node) | [FixShapeConfig](#fixshapeconfig) \| FixShapeConfig[] | | | | nodeFilter | 节点过滤器,用于过滤哪些节点在缩放过程中保持固定大小 | (datum: [NodeData](/zh/manual/data/#节点数据nodedata)) => boolean | `() => true` | | | edge | 边配置项,用于定义哪些属性在视觉上保持固定大小。默认固定 lineWidth、labelFontSize 属性,用法同[node配置项](#node) | [FixShapeConfig](#fixshapeconfig) \| FixShapeConfig[] | `[ shape: 'key', fields: ['lineWidth'] , shape: 'halo', fields: ['lineWidth'] , shape: 'label' ]` | | | edgeFilter | 边过滤器,用于过滤哪些边在缩放过程中保持固定大小 | (datum: [EdgeData](/zh/manual/data/#边数据edgedata)) => boolean | `() => true` | | | combo | Combo 配置项,用于定义哪些属性在视觉上保持固定大小。默认整个 Combo 将被固定,用法同[node配置项](#node) | [FixShapeConfig](#fixshapeconfig) \| FixShapeConfig[] | | | | comboFilter | Combo 过滤器,用于过滤哪些 Combo 在缩放过程中保持固定大小 | (datum: [ComboData](/zh/manual/data/#组合数据combodata)) => boolean | `() => true` | | ### enable 是否启用固定元素大小交互。默认在缩小画布时启用 默认在缩小画布时启用,设置 `enable: (event) => event.data.scale < 1`;如果希望在放大画布时启用,设置 `enable: (event) => event.data.scale > 1`;如果希望在放大缩小画布时都启用,设置 `enable: true` ### node 节点配置项,用于定义哪些属性在视觉上保持固定大小。若未指定(即为 undefined),则整个节点将被固定 **示例** 如果在缩放过程中希望固定节点主图形的 lineWidth,可以这样配置: ```ts { node: [{ shape: 'key', fields: ['lineWidth'] }]; } ``` 如果在缩放过程中想保持元素标签大小不变,可以这样配置: ```ts { shape: 'label'; } ``` ### FixShapeConfig | 参数 | 描述 | 类型 | 默认值 | 必选 | | ------ | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | ------ | ---- | | shape | 指定要固定大小的图形,可以是图形的类名字,或者是一个函数,该函数接收构成元素的所有图形并返回目标图形 | string \| ((shapes: DisplayObject[]) => DisplayObject) | - | ✓ | | fields | 指定要固定大小的图形属性字段。如果未指定,则默认固定整个图形的大小 | string[] | - | ✘ | ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node0', size: 50, label: '0', style: { x: 326, y: 268 }, states: ['selected'] }, { id: 'node1', size: 30, label: '1', style: { x: 280, y: 384 }, states: ['selected'] }, { id: 'node2', size: 30, label: '2', style: { x: 234, y: 167 } }, { id: 'node3', size: 30, label: '3', style: { x: 391, y: 368 } }, { id: 'node4', size: 30, label: '4', style: { x: 444, y: 209 } }, { id: 'node5', size: 30, label: '5', style: { x: 378, y: 157 } }, { id: 'node6', size: 15, label: '6', style: { x: 229, y: 400 } }, { id: 'node7', size: 15, label: '7', style: { x: 281, y: 440 } }, { id: 'node8', size: 15, label: '8', style: { x: 188, y: 119 } }, { id: 'node9', size: 15, label: '9', style: { x: 287, y: 157 } }, { id: 'node10', size: 15, label: '10', style: { x: 185, y: 200 } }, { id: 'node11', size: 15, label: '11', style: { x: 238, y: 110 } }, { id: 'node12', size: 15, label: '12', style: { x: 239, y: 221 } }, { id: 'node13', size: 15, label: '13', style: { x: 176, y: 160 } }, { id: 'node14', size: 15, label: '14', style: { x: 389, y: 423 } }, { id: 'node15', size: 15, label: '15', style: { x: 441, y: 341 } }, { id: 'node16', size: 15, label: '16', style: { x: 442, y: 398 } }, ], edges: [ { source: 'node0', target: 'node1', label: '0-1', states: ['selected'] }, { source: 'node0', target: 'node2', label: '0-2' }, { source: 'node0', target: 'node3', label: '0-3' }, { source: 'node0', target: 'node4', label: '0-4' }, { source: 'node0', target: 'node5', label: '0-5' }, { source: 'node1', target: 'node6', label: '1-6' }, { source: 'node1', target: 'node7', label: '1-7' }, { source: 'node2', target: 'node8', label: '2-8' }, { source: 'node2', target: 'node9', label: '2-9' }, { source: 'node2', target: 'node10', label: '2-10' }, { source: 'node2', target: 'node11', label: '2-11' }, { source: 'node2', target: 'node12', label: '2-12' }, { source: 'node2', target: 'node13', label: '2-13' }, { source: 'node3', target: 'node14', label: '3-14' }, { source: 'node3', target: 'node15', label: '3-15' }, { source: 'node3', target: 'node16', label: '3-16' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.label, size: (d) => d.size, lineWidth: 1, }, }, edge: { style: { labelText: (d) => d.label } }, behaviors: [ 'zoom-canvas', 'drag-canvas', { key: 'fix-element-size', type: 'fix-element-size', enable: (event) => event.data.scale < 1, state: 'selected', reset: true, }, { type: 'click-select', key: 'click-select', multiple: true }, ], autoFit: 'center', }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 矩形节点 Rect - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Rect/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Rect.md - Description: 矩形节点 Rect --- title: "矩形节点 Rect" description: "矩形节点 Rect" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Rect/" version: "5.1.1" --- ## 概述 矩形是一个四边相等的几何形状,具有明确的边界。 适用场景: - 用于表示模块、组件或容器。 - 适合表示层次结构,如组织结构图、文件目录树。 - 常用于流程图、架构图、UML 图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }] }, node: { type: 'rect' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'rect' }, 'type').disable(); const options = { 'size[0]': 48, 'size[1]': 24 }; const optionFolder = gui.addFolder('rect.style'); optionFolder.add(options, 'size[0]', 0, 100, 1); optionFolder.add(options, 'size[1]', 0, 100, 1); optionFolder.onChange(({ object }) => { graph.updateNodeData([{ id: 'node1', style: { size: [object['size[0]'], object['size[1]']] } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `rect` 以使用矩形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) ## 示例 ### 内置矩形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### Extension - 扩展 - Canonical page: https://g6.antv.antgroup.com/zh/manual/graph/extension/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/graph/extension.md - Description: Extension - 扩展 --- title: "Extension - 扩展" description: "Extension - 扩展" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/graph/extension/" version: "5.1.1" --- ## 概念 扩展 (Extension) 是 G6 中的一个重要概念,它是 G6 中所有可扩展部分的统称,包括以下几种: - 动画 (Animation) - 交互 (Behavior) - 元素 (Element) - 节点 (Node) - 边 (Edge) - 组合 (Combo) - 布局 (Layout) - 色板 (Palette) - 插件 (Plugin) - 主题 (Theme) - 数据转换 (Transform) ## 注册扩展 G6 提供了 `register` 函数用于注册扩展,例如: ```typescript import { register, ExtensionCategory } from '@antv/g6'; import { CustomNode } from './my-custom-node'; // 注册节点 register(ExtensionCategory.NODE, 'custom-node', CustomNode); ``` `register` 函数的第一个参数是扩展的类型,第二个参数是扩展的名称,第三个参数是扩展的实现(扩展实现参考各扩展类型所在文档的自定义相关章节)。 不同的扩展类型之间**可以**使用相同的扩展名称,但同一类型的扩展重复注册时仅会在第一次注册时生效。 ```typescript // ✅ register(ExtensionCategory.NODE, 'custom-name', CustomNode); register(ExtensionCategory.COMBO, 'custom-name', CustomCombo); // ❌ register(ExtensionCategory.NODE, 'custom-name', CustomNode); register(ExtensionCategory.NODE, 'custom-name', CustomNode); ``` ## 使用扩展 不同的扩展类型的配置位置有所不同,但都是通过指定注册时所使用的名称来使用扩展,例如: - 使用节点扩展:`options.node.type` - 使用边扩展:`options.edge.type` - 使用组合扩展:`options.combo.type` - 使用交互扩展:`options.behaviors` - 使用布局扩展:`options.layout.type` - 使用插件扩展:`options.plugins` - 使用主题扩展:`options.theme` - 使用数据转换扩展:`options.transform` - 使用色板扩展:`options.node.palette` `options.edge.palette` 等 - 使用动画扩展:`options.node.animate` `options.edge.animate` 等 ## 获取扩展 G6 提供了 `getExtension` 和 `getExtensions` 方法分别用于获取指定扩展类型下的单个扩展和所有扩展,例如: ```typescript import { getExtension, getExtensions, ExtensionCategory } from '@antv/g6'; // 获取注册的名称为 'custom-node' 的节点扩展实现 getExtension(ExtensionCategory.NODE, 'custom-node'); // 获取所有注册的节点扩展实现 getExtensions(ExtensionCategory.NODE); ``` #### Dagre 布局 - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/DagreLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/DagreLayout.md - Description: Dagre 布局 --- title: "Dagre 布局" description: "Dagre 布局" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/DagreLayout/" version: "5.1.1" --- ## 概述 Dagre 是一种层次化布局,适用于有向无环图(DAG)的布局场景,能够自动处理节点之间的方向和间距,支持水平和垂直布局。参考更多 Dagre 布局[样例](/zh/examples/layout/dagre/)或[源码](https://github.com/dagrejs/dagre/blob/master/lib/layout.js)以及[官方文档](https://github.com/dagrejs/dagre/wiki)。 Dagre布局 ## 配置方式 ```js const graph = new Graph({ layout: { type: 'dagre', rankdir: 'TB', align: 'UL', nodesep: 50, ranksep: 50, }, }); ``` ## 配置项 > 更多配置项可参考[官方文档](https://github.com/dagrejs/dagre/wiki#configuring-the-layout) Dagre 布局配置项图解 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ----------------- | ---- | | type | 布局类型 | `dagre` | - | ✓ | | rankdir | 布局方向,可选值 | `TB` \| `BT` \| `LR` \| `RL` | `TB` | | | align | 节点对齐方式,可选值 | `UL` \| `UR` \| `DL` \| `DR` | `UL` | | | nodesep | 节点间距(px)。在 rankdir 为 `TB` 或 `BT` 时是节点的水平间距;在 rankdir 为 `LR` 或 `RL` 时代表节点的竖直方向间距 | number | 50 | | | ranksep | 层间距(px)。在 rankdir 为 `TB` 或 `BT` 时是竖直方向相邻层间距;在 rankdir 为 `LR` 或 `RL` 时代表水平方向相邻层间距 | number | 100 | | | ranker | 为每个节点分配等级的算法,共支持三种算法,分别是:`longest-path`、`tight-tree`、`network-simplex` | `network-simplex` \| `tight-tree` \| `longest-path` | `network-simplex` | | | directed | 是否按有向图处理 | boolean | true | | | compound | 是否支持嵌套结构 | boolean | true | | | multigraph | 是否允许多重边 | boolean | true | | | nodeSize | G6 自定义属性,统一指定或为每个节点指定节点大小。如果仅返回单个 number,则表示节点的宽度和高度相同;如果返回一个数组,则形如:`[width, height]` | number \| number[] \| () => (number \| number[]) | [0, 0] | | | edgeMinLen | 边跨越的最小层数 | number \| (edge) => number | 1 | | | edgeWeight | 边权重,用于影响优化优先级 | number \| (edge) => number | | | | edgeLabelSize | 边标签尺寸,用于预留空间 | number[] \| (edge) => number[] | | | | edgeLabelPos | 边标签位置 | string \| (edge) => string | | | | edgeLabelOffset | 标签与边的偏移 | number \| (edge) => number | | | > 补充:`dagre` 不需要单独配置 `controlPoints`,G6 会把布局输出的折线点自动转换为边的 `style.controlPoints`。 ### rankdir > `TB` | `BT` | `LR` | `RL`, **Default**: `TB` 布局方向 - `TB`:从上到下; :从上到下布局 - `BT`:从下到上; 从下到上布局 - `LR`:从左到右; 从左到右布局 - `RL`:从右到左。 水平布局 ### align > `UL` | `UR` | `DL` | `DR`, **Default**: `UL` 节点对齐方式 - `UL`:左上对齐 - `UR`:右上对齐 - `DL`:左下对齐 - `DR`:右下对齐 ### nodesep > number, **Default**: 50 节点间距(px)。在rankdir 为 `TB` 或 `BT` 时是节点的水平间距;在rankdir 为 `LR` 或 `RL` 时代表节点的竖直方向间距 ### ranksep > number, **Default**: 50 层间距(px)。在rankdir 为 `TB` 或 `BT` 时是竖直方向相邻层间距;在rankdir 为 `LR` 或 `RL` 时代表水平方向相邻层间距 ### ranker > `network-simplex` | `tight-tree` | `longest-path`, **Default**: `network-simplex` 为每个节点分配层级的算法,共支持三种算法,分别是: - `longest-path`: 最长路径算法,使用DFS深度优先搜索,递归查找每个节点的最长路径。优点是计算简单速度快,但会导致长边过多; - `tight-tree`: 紧凑树算法,一种优化算法,目的是减少长边的数量。先用最长路径算法`longest-path`计算出初始层级,然后调整松弛边的长度,从而构建可行树。 - `network-simplex`: 网络单形法,参考算法[A Technique for Drawing Directed Graphs](https://www.graphviz.org/documentation/TSE93.pdf),核心思想是迭代修改节点的层级,缩小松弛边。 ### nodeSize > number \| number[] \| () => (number \| number[]) G6自定义属性,统一指定或为每个节点指定节点大小。如果仅返回单个number,则表示节点的宽度和高度相同;如果返回一个数组,则形如:`[width, height]` ```js (d) => { // d 是一个节点 if (d.id === 'testId') return 20; return [10, 20]; }; ``` ### controlPoints > boolean, **Default**: false 是否保留边的控制点。 ## 布局适用场景 - **流程图**:适合展示流程图,节点之间的方向和间距会自动处理; - **依赖关系图**:展示软件包或模块之间的依赖关系; - **任务调度图**:展示任务之间的依赖关系和执行顺序。 ## 相关文档 > 以下文档可以帮助你更好地理解Dagre 布局 - [图布局算法|详解 Dagre 布局](https://mp.weixin.qq.com/s/EdyTfFUH7fyMefNSBXI2nA) - [深入解读Dagre布局算法](https://www.yuque.com/antv/g6-blog/xxp5nl) #### 历史记录 History - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/History/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/History.md - Description: 历史记录 History --- title: "历史记录 History" description: "历史记录 History" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/History/" version: "5.1.1" --- ## 概述 该插件用于实现图编辑的 **撤销(Undo)** 和 **重做(Redo)** 功能,通过记录用户操作的历史状态堆栈,支持在图交互过程中进行回溯或恢复操作。该插件为用户提供了完善的配置项和 API 。 ## 使用场景 历史记录插件适用于所有涉及到图编辑的场景。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node-1' }] }, layout: { type: 'force' }, node: { style: { size: 60, labelText: 'Drag Me!', labelPlacement: 'middle', labelFill: '#fff', fill: '#7e3feb', }, }, edge: { style: { stroke: '#8b9baf' } }, behaviors: ['drag-element'], plugins: ['grid-line', { type: 'history', key: 'history' }], }, { width: 600, height: 300 }, (gui, graph) => { const options = { type: 'history', stackSize: 0, }; const optionFolder = gui.addFolder('History Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'stackSize', 0, 10, 1); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'history', [property]: value, }); graph.render(); }); const apiFolder = gui.addFolder('History API'); const instance = graph.getPluginInstance('history'); apiFolder.add(instance, 'undo'); apiFolder.add(instance, 'redo'); apiFolder.add(instance, 'clear'); }, ); ``` ## 基本用法 在图配置中添加这一插件: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... plugins: ['history'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... plugins: [ { type: 'history', key: 'history-1', stackSize: 10, }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ----------- | ---- | | afterAddCommand | 当一个命令被添加到 `Undo/Redo` 队列后被调用。`revert` 为 `true` 时表示撤销操作,为 `false` 时表示重做操作 | (cmd: [Command](#command), revert: boolean) => void | - | | | beforeAddCommand | 当一个命令被添加到 `Undo/Redo` 队列前被调用,如果该方法返回 `false`,那么这个命令将不会被添加到队列中。`revert` 为 `true` 时表示撤销操作,为 `false` 时表示重做操作 | (cmd: [Command](#command), revert: boolean) => boolean \| void | - | | | executeCommand | 执行命令时的回调函数 | (cmd: [Command](#command)) => void | - | | | stackSize | 最多记录该数据长度的历史记录 | number | 0(不限制) | | ### 参数类型说明 #### `Command` ```typescript // 单条历史记录命令 interface Command { current: CommandData; // 当前数据 original: CommandData; // 原始数据 animation: boolean; // 是否开启动画 } // 单条历史记录命令数据 interface CommandData { add: GraphData; // 新增的数据 update: GraphData; // 更新的数据 remove: GraphData; // 移除的数据 } // 图数据 interface GraphData { nodes?: NodeData[]; // 节点数据 edges?: EdgeData[]; // 边数据 combos?: ComboData[]; // Combo 数据 } ``` ## API history 插件提供了以下 API 供用户按需使用,调用插件方法的方式请参考 [插件总览文档](/zh/manual/plugin/overview/#调用插件方法) ### History.canRedo() 判断是否可以进行**重做**操作。如果重做堆栈中有记录,则返回 `true`,否则返回 `false`。 ```typescript canRedo(): boolean; ``` **示例:** ```typescript const canRedo = historyInstance.canRedo(); if (canRedo) { console.log('可以进行重做操作'); } else { console.log('重做堆栈为空,无法重做'); } ``` ### History.canUndo() 判断是否可以进行**撤销**操作。如果撤销堆栈中有记录,则返回 `true`,否则返回 `false`。 ```typescript canUndo(): boolean; ``` **示例:** ```typescript const canUndo = historyInstance.canUndo(); if (canUndo) { console.log('可以进行撤销操作'); } else { console.log('撤销堆栈为空,无法撤销'); } ``` ### History.clear() 清空历史记录,包括撤销和重做堆栈。 ```typescript clear(): void; ``` **示例:** ```typescript historyInstance.clear(); console.log('历史记录已清空'); ``` ### History.on() 监听历史记录事件,允许用户在特定事件发生时执行自定义逻辑。 ```typescript on(event: Loosen/, handler: (e: { cmd?: Command | null }) => void): void; ``` 参数类型说明: - HistoryEvent ```typescript enum HistoryEvent \{ UNDO = 'undo', // 当命令被撤销时 REDO = 'redo', // 当命令被重做时 CANCEL = 'cancel', // 当命令被取消时 ADD = 'add', // 当命令被添加到队列时 CLEAR = 'clear', // 当历史队列被清空时 CHANGE = 'change', // 当历史队列发生变化时 \} ``` - Command 请参考前面的 [Command](#参数类型说明) 类型说明 示例: ```typescript historyInstance.on(HistoryEvent.UNDO, () => { console.log('执行了撤销操作'); }); ``` ### History.redo() 执行**重做**操作,并返回插件实例。如果重做堆栈为空,则不执行任何操作。 ```typescript redo(): History; ``` **示例:** ```typescript historyInstance.redo(); console.log('执行了重做操作'); ``` ### History.undo() 执行**撤销**操作,并返回插件实例。如果撤销堆栈为空,则不执行任何操作。 ```typescript undo(): History; ``` **示例:** ```typescript historyInstance.undo(); console.log('执行了撤销操作'); ``` ### History.undoAndCancel() 执行撤销操作且不计入历史记录,并返回插件实例。注意,执行该操作会清空**重做**栈。 ```typescript undoAndCancel(): History; ``` **示例:** ```typescript historyInstance.undoAndCancel(); console.log('执行了撤销并取消操作'); ``` ## 历史记录模式 该插件支持两种历史记录模式: ### 默认模式 默认模式下,每一次触发**渲染后**(比如更新元素数据后,用户主动执行 `graph.draw()` 方法触发渲染),插件会把**渲染前**和**渲染后**的数据记录下来并作为一次操作记录入栈。 ### 自定义模式 #### 场景描述 实际需求中,用户的一次图编辑操作可能涉及到**多次渲染**,比如,一次编辑操作中,首先把节点 A、B 展示出来,然后展示 A->B 的连线,这里就涉及到两次渲染(即用户需要进行两次 `graph.draw()` ),这种场景下,默认模式会入栈两次历史记录,分别是: - 展示节点 A 和 B - 展示 A->B 的连线 显然,实际业务中,一次操作,也应该只需一次撤销。 但这里在撤销本次操作时,用户需要调用两次 `undo` 方法,也就是需要进行两次撤销。 #### 场景支持 为了支持这样的场景,G6 提供了一个批量控制器( `BatchController`,[可参考源码](https://github.com/antvis/G6/blob/v5/packages/g6/src/runtime/batch.ts)),在图实例上下文中提供了这个批量控制器实例。 历史记录插件则基于这个批量控制器,来实现自定义操作记录,代码示例如下: ```typescript const graph = new Graph({ // 其他配置... plugins: [ { type: 'history', key: 'history', }, ], }); graph.context.batch.startBatch(); // 开始批量操作 graph.addNodeData(...); // 把节点 A、B 展示出来 graph.draw(); // 第一次触发渲染 graph.addEdgeData(...); // 把 A->B 连线展示出来 graph.draw(); // 第二次触发渲染 graph.context.batch.endBatch(); // 结束批量操作 ``` 示例中: - 通过调用批量控制器实例的 `startBatch` 方法,告诉历史记录插件,现在开始进行批量操作,在批量操作没有结束前,不管触发多少次渲染,都不能进行历史记录入栈(历史记录插件会把每次触发渲染的变更数据记录下来) - 在完成最后一次数据变更后,调用 `endBatch()` 方法,历史记录插件监听到批量操作完成,则把本次批量操作作为一次历史记录入栈 最终,用户只需要进行一次 `undo` 即可撤销。 ## 代码示例 下面列举一些常见的案例,并给出相应的代码参考 ### 撤销、重做按钮状态 实际业务场景中,可能需要自定义画布的工具栏,也就涉及到撤销和重做按钮的启禁用状态 ```typescript const canUndo = false; const canRedo = false; const graph = new Graph({ // 其他配置... plugins: [ { type: 'history', key: 'history', }, ], }); const historyInstance = graph.getPluginInstance('history'); historyInstance.on(HistoryEvent.CHANGE, () => { canUndo = historyInstance.canUndo(); canRedo = historyInstance.canRedo(); }); ``` 示例中通过监听 `HistoryEvent.CHANGE` 事件,这个事件在历史队列发生变化时会触发,每次发生变化后,实时判断当前是否可以进行撤销和重做操作 ### 判断是否允许命令进入队列 这里实现一个简单的场景:只有移除元素的操作才允许进入历史记录队列 ```typescript const graph = new Graph({ // 其他配置... plugins: [ { type: 'history', key: 'history', beforeAddCommand: (cmd) => { return ( cmd.current.remove?.nodes?.length > 0 || cmd.current.remove?.combos?.length > 0 || cmd.current.remove?.edges?.length > 0 ); }, }, ], }); ``` 示例中通过配置项 [beforeAddCommand](#beforeAddCommand) 来实现,判断 `cmd.current.remove` 里面是否存在被移除的元素 ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 聚焦元素 FocusElement - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/FocusElement/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/FocusElement.md - Description: 聚焦元素 FocusElement --- title: "聚焦元素 FocusElement" description: "聚焦元素 FocusElement" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/FocusElement/" version: "5.1.1" --- ## 概述 FocusElement 是 G6 中用于实现元素聚焦功能的内置交互,支持通过点击元素将其聚焦到视图中心。这个交互可以帮助用户快速定位和关注特定的图元素。 ## 使用场景 - 快速将关注的节点或边居中显示 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, behaviors: [ { type: 'focus-element', key: 'focus-element', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'focus-element', type: 'focus-element', animation: true, enable: true, }; const optionFolder = gui.addFolder('FocusElement Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'focus-element', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['focus-element'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'focus-element', animation: { duration: 500, easing: 'ease-in', }, }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------- | ---- | | type | 交互类型名称 | string | `focus-element` | ✓ | | animation | 聚焦动画效果设置 | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | `{ duration: 500, easing: 'ease-in' }` | | | enable | 是否启用聚焦功能 | boolean \| ((event: IElementEvent) => boolean) | true | | | trigger | 同时按下快捷键才能聚焦元素 **按键参考:** _MDN Key Values_ 。若设为**空数组**时则表示不需要按下其他按键配合
| string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | [] | | ### ViewportAnimationEffectTiming ```typescript type ViewportAnimationEffectTiming = | boolean // true 启用默认动画,false 禁用动画 | { easing?: string; // 动画缓动函数:'ease-in-out'、'ease-in'、'ease-out'、'linear' duration?: number; // 动画持续时间(毫秒) }; ``` ## 代码示例 ### 基础聚焦功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['focus-element'], }); ``` ### 自定义动画效果 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'focus-element', animation: { duration: 800, easing: 'ease-in-out', }, }, ], }); ``` ### 条件性启用聚焦 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'focus-element', enable: (event) => { // 只对节点启用聚焦,边不聚焦 return event.target.type === 'node'; }, }, ], }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', combo: 'combo1', style: { x: 110, y: 150 } }, { id: 'node2', combo: 'combo1', style: { x: 190, y: 150 } }, { id: 'node3', combo: 'combo2', style: { x: 150, y: 260 } }, ], edges: [{ source: 'node1', target: 'node2' }], combos: [{ id: 'combo1', combo: 'combo2' }, { id: 'combo2' }], }; const graph = new Graph({ container: 'container', node: { style: { labelText: (d) => d.id }, }, data, behaviors: ['collapse-expand', 'focus-element'], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 五角形节点 Star - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Star/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Star.md - Description: 五角形节点 Star --- title: "五角形节点 Star" description: "五角形节点 Star" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Star/" version: "5.1.1" --- ## 概述 星形是一个多角几何形状,具有突出的角。 适用场景: - 用于表示重要节点、特殊标记或装饰性元素。 - 适合表示流程图、网络图或拓扑图。 - 常用于流程图、网络图、拓扑图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }] }, node: { type: 'star' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'star' }, 'type').disable(); const options = { size: 40, innerR: 0, }; const optionFolder = gui.addFolder('star.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'innerR', 0, 100); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `star` 以使用星形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------ | ------------------------------------ | ------ | ------------------ | ---- | | innerR | 内半径,是指从星形中心到内顶点的距离 | number | 默认为外半径的 3/8 | 结构说明: ## 示例 ### 内置五角形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'star', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 生态树 Dendrogram - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/DendrogramLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/DendrogramLayout.md - Description: 生态树 Dendrogram --- title: "生态树 Dendrogram" description: "生态树 Dendrogram" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/DendrogramLayout/" version: "5.1.1" --- ## 概述 生态树布局适用于层次聚类数据的可视化,其特点是所有子节点布局在同一层级,不考虑节点大小,每个节点被当成 1px 处理。 生态树布局示例 ## 配置方式 ```js const graph = new Graph({ layout: { type: 'dendrogram', direction: 'LR', nodeSep: 30, rankSep: 250, radial: false, }, }); ``` ## 配置项 生态树配置项图解 | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | ---------------------------------------------- | ------------------------------------------ | ------ | ---- | | type | 布局类型 | `dendrogram` | - | ✓ | | direction | 布局方向,[可选值](#direction) | `LR` \| `RL` \| `TB` \| `BT` \| `H` \| `V` | `LR` | | | nodeSep | 节点间距,即同一层级节点之间的距离,单位为像素 | number | 20 | | | rankSep | 层级间距,即不同层级之间的距离,单位为像素 | number | 200 | | | radial | 是否启用辐射状布局,[说明](#radial) | boolean | false | | ### direction 树布局的方向,有以下选项: - `TB`:根节点在上,往下布局 TB方向 - `BT`:根节点在下,往上布局 BT方向 - `LR`:根节点在左,往右布局 LR方向 - `RL`:根节点在右,往左布局 RL方向 - `H`:根节点在中间,水平对称布局 H方向 - `V`:根节点在中间,垂直对称布局 V方向 ### radial 是否启用辐射状布局模式。启用后,节点将以根节点为中心呈辐射状分布。 若 `radial` 设置为 `true`,建议将 `direction` 设置为 `'LR'` 或 `'RL'` 以获得最佳效果。 辐射状布局 #### 轮廓包围 Hull - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Hull/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Hull.md - Description: 轮廓包围 Hull --- title: "轮廓包围 Hull" description: "轮廓包围 Hull" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Hull/" version: "5.1.1" --- ## 概述 轮廓包围(Hull)用于处理和表示一组点的凸多边形或凹多边形包围盒。它可以将一组节点包裹在一个最小的几何形状中,帮助用户更好地理解和分析数据集。 - **凸包(Convex Hull)**:这是一个凸多边形,它包含所有的点,并且没有任何凹陷。 - **凹包(Concave Hull)**:这是一个凹多边形,它同样包含所有的点,但是可能会有凹陷。凹包的凹陷程度由 concavity 参数控制。 ## 使用场景 轮廓包围插件主要适用于以下场景: - 数据可视化中的节点集合包裹 - 提供视觉参考,增强空间感知 - 在复杂网络图中标识特定节点的集合关系 ## 基本用法 以下是一个简单的 Hull 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'hull', key: 'my-hull', // 指定唯一标识符,便于后续动态更新 members: ['node-1', 'node-2'], // 需要包裹的节点 ID 列表 concavity: Infinity, // 默认为凸包 }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { source: 'node-0', target: 'node-2', }, { source: 'node-1', target: 'node-2', }, { source: 'node-2', target: 'node-3', }, { source: 'node-3', target: 'node-4', }, { source: 'node-3', target: 'node-5', }, { source: 'node-3', target: 'node-6', }, ], }, node: { style: { labelText: (d) => d.id }, palette: { field: 'cluster', color: ['#7e3feb', '#ffa940'] }, }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ 'grid-line', { type: 'hull', key: 'hull-a', members: ['node-0', 'node-1', 'node-2', 'node-3'], labelText: 'hull-a', fill: '#7e3feb', stroke: '#7e3feb', fillOpacity: 0.1, strokeOpacity: 1, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: '#7e3feb', labelBackgroundRadius: 5, }, ], }, { width: 600, height: 450 }, (gui, graph) => { const options = { type: 'hull', members: ['node-0', 'node-1', 'node-2', 'node-3'], concavity: Infinity, corner: 'rounded', padding: 10, // style fill: '#7e3feb', stroke: '#7e3feb', fillOpacity: 0.1, strokeOpacity: 1, // label label: true, labelCloseToPath: true, labelAutoRotate: true, labelOffsetX: 0, labelOffsetY: 0, labelPlacement: 'bottom', }; const optionFolder = gui.addFolder('Hull Options'); optionFolder.add(options, 'type').disable(); optionFolder.add(options, 'concavity', 0, 200, 1); optionFolder.add(options, 'corner', ['rounded', 'smooth', 'sharp']); optionFolder.add(options, 'padding', 0, 20, 1); optionFolder.addColor(options, 'fill'); optionFolder.addColor(options, 'stroke'); optionFolder.add(options, 'fillOpacity', 0, 1, 0.1); optionFolder.add(options, 'strokeOpacity', 0, 1, 0.1); optionFolder.add(options, 'label'); optionFolder.add(options, 'labelCloseToPath'); optionFolder.add(options, 'labelAutoRotate'); optionFolder.add(options, 'labelOffsetX', 0, 20, 1); optionFolder.add(options, 'labelOffsetY', 0, 20, 1); optionFolder.add(options, 'labelPlacement', ['left', 'right', 'top', 'bottom', 'center']); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'hull-a', [property]: value, }); graph.render(); }); const apiConfig = { member: 'node-1', }; const apiFolder = gui.addFolder('Hull API'); const instance = graph.getPluginInstance('hull-a'); apiFolder.add( apiConfig, 'member', new Array(7).fill(0).map((_, index) => `node-${index}`), ); apiFolder.add({ addMember: () => instance.addMember(apiConfig.member) }, 'addMember').name('add member'); apiFolder .add({ removeMember: () => instance.removeMember(apiConfig.member) }, 'removeMember') .name('remove member'); apiFolder .add({ removeMember: () => alert('Members in Hull-a: ' + instance.getMember()) }, 'removeMember') .name('get member'); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------------- | ---------------------------------------------------------- | -------------------------------------------------- | --------- | ---- | | type | 插件类型 | string | `hull` | ✓ | | key | 插件唯一标识符,用于后续更新 | string | - | | | members | Hull 内的元素,包括节点和边 | string[] | - | ✓ | | concavity | 凹度,数值越大凹度越小;默认为 Infinity 代表为 Convex Hull | number | Infinity | | | corner | 拐角类型,可选值为 `rounded` \| `smooth` \| `sharp` | string | `rounded` | | | padding | 内边距 | number | `10` | | | label | 是否显示标签 | boolean | true | | | labelPlacement | 标签位置 | `left` \| `right` \| `top` \| `bottom` \| `center` | `bottom` | | | labelBackground | 是否显示背景 | boolean | false | | | labelPadding | 标签内边距 | number \| number[] | 0 | | | labelCloseToPath | 标签是否贴合轮廓 | boolean | true | | | labelAutoRotate | 标签是否跟随轮廓旋转,仅在 closeToPath 为 true 时生效 | boolean | true | | | labelOffsetX | x 轴偏移量 | number | 0 | | | labelOffsetY | y 轴偏移量 | number | 0 | | | labelMaxWidth | 文本的最大宽度,超出会自动省略 | number | 0 | | 完整的标签样式见[此链接](/zh/manual/element/node/BaseNode/#%E6%A0%87%E7%AD%BE%E6%A0%B7%E5%BC%8F) ### concavity concavity 属性用于控制 Hull 的凹度。当设置为 Infinity 时,生成的是凸包;否则会生成凹包。 ```js // 凸包示例 const graph = new Graph({ plugins: [ { type: 'hull', concavity: Infinity, // 凸包 members: ['node-1', 'node-2'], }, ], }); // 凹包示例 const graph = new Graph({ plugins: [ { type: 'hull', concavity: 50, // 凹包 members: ['node-1', 'node-2'], }, ], }); ``` ## 代码示例 ### 基础 Hull 最简单的方式是直接使用预设配置: ```js const graph = new Graph({ plugins: [ { type: 'hull', members: ['node-1', 'node-2'], // 需要包裹的节点 ID 列表 }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'view', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { source: 'node-0', target: 'node-2', }, { source: 'node-1', target: 'node-2', }, { source: 'node-2', target: 'node-3', }, { source: 'node-3', target: 'node-4', }, { source: 'node-3', target: 'node-5', }, { source: 'node-3', target: 'node-6', }, ], }, plugins: [ { type: 'hull', members: ['node-1', 'node-2'], // 需要包裹的节点 ID 列表 }, ], behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); ``` ### 自定义样式 您可以根据需要自定义 Hull 的样式,例如调整颜色、透明度等属性。 ```js const graph = new Graph({ plugins: [ { type: 'hull', members: ['node-1', 'node-2', 'node-3'], stroke: '#ff000033', // 红色半透明边框 fill: '#7e3feb', // 浅紫色填充 fillOpacity: 0.2, lineWidth: 2, padding: 15, // 更大的内边距 }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'view', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { source: 'node-0', target: 'node-2', }, { source: 'node-1', target: 'node-2', }, { source: 'node-2', target: 'node-3', }, { source: 'node-3', target: 'node-4', }, { source: 'node-3', target: 'node-5', }, { source: 'node-3', target: 'node-6', }, ], }, plugins: [ { type: 'hull', members: ['node-1', 'node-2', 'node-3'], stroke: '#ff000033', // 红色半透明边框 fill: '#7e3feb', // 浅紫色填充 fillOpacity: 0.2, lineWidth: 2, padding: 15, // 更大的内边距 }, ], behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); ``` ### 标签配置 您可以配置标签的位置、背景、偏移量等属性,以增强可视化效果。 ```js const graph = new Graph({ plugins: [ { type: 'hull', members: ['node-1', 'node-2'], label: true, // 显示标签 labelText: 'hull-a', labelPlacement: 'top', // 标签位置 labelBackground: true, // 显示标签背景 labelPadding: 5, // 标签内边距 }, ], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 300, height: 150, autoFit: 'center', data: { nodes: [ { id: 'node-0', data: { cluster: 'a' }, style: { x: 555, y: 151 }, }, { id: 'node-1', data: { cluster: 'a' }, style: { x: 532, y: 323 }, }, { id: 'node-2', data: { cluster: 'a' }, style: { x: 473, y: 227 }, }, { id: 'node-3', data: { cluster: 'a' }, style: { x: 349, y: 212 }, }, { id: 'node-4', data: { cluster: 'b' }, style: { x: 234, y: 201 }, }, { id: 'node-5', data: { cluster: 'b' }, style: { x: 338, y: 333 }, }, { id: 'node-6', data: { cluster: 'b' }, style: { x: 365, y: 91 }, }, ], edges: [ { source: 'node-0', target: 'node-2', }, { source: 'node-1', target: 'node-2', }, { source: 'node-2', target: 'node-3', }, { source: 'node-3', target: 'node-4', }, { source: 'node-3', target: 'node-5', }, { source: 'node-3', target: 'node-6', }, ], }, plugins: [ { type: 'hull', members: ['node-1', 'node-2'], label: true, // 显示标签 labelText: 'hull-a', labelPlacement: 'top', // 标签位置 labelBackground: true, // 显示标签背景 labelPadding: 5, // 标签内边距 }, ], behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/collection.json') .then((res) => res.json()) .then((data) => { const groupedNodesByCluster = data.nodes.reduce((acc, node) => { const cluster = node.data.cluster; acc[cluster] ||= []; acc[cluster].push(node.id); return acc; }, {}); const createStyle = (baseColor) => ({ fill: baseColor, stroke: baseColor, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: baseColor, labelBackgroundRadius: 5, }); const graph = new Graph({ container: 'container', data, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], node: { palette: { field: 'cluster' }, }, layout: { type: 'force', preventOverlap: true, linkDistance: (d) => { if (d.source === 'node0' || d.target === 'node0') { return 200; } return 80; }, }, plugins: [ { key: 'hull-a', type: 'hull', members: groupedNodesByCluster['a'], labelText: 'cluster-a', ...createStyle('#1783FF'), }, { key: 'hull-b', type: 'hull', members: groupedNodesByCluster['b'], labelText: 'cluster-b', ...createStyle('#00C9C9'), }, { key: 'hull-c', type: 'hull', members: groupedNodesByCluster['c'], labelText: 'cluster-c', ...createStyle('#F08F56'), }, { key: 'hull-d', type: 'hull', members: groupedNodesByCluster['d'], labelText: 'cluster-d', ...createStyle('#D580FF'), }, ], autoFit: 'center', }); graph.render(); }); ``` ``` ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 悬停激活 HoverActivate - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/HoverActivate/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/HoverActivate.md - Description: 悬停激活 HoverActivate --- title: "悬停激活 HoverActivate" description: "悬停激活 HoverActivate" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/HoverActivate/" version: "5.1.1" --- ## 概述 HoverActivate 是 G6 中用于实现元素悬停激活效果的内置交互,当鼠标悬停在节点或边上时,会自动触发高亮、显示等视觉反馈。该交互是图可视化中增强数据探索的重要手段,有助于用户快速聚焦目标元素并获取相关信息。 ## 使用场景 这一交互主要用于: - 在复杂关系图中快速定位关注元素 - 通过悬停信息展示节点额外信息 - 分析节点间关联关系时,通过激活边凸显连接路径 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node0', size: 50, label: '0', style: { x: 326, y: 268 } }, { id: 'node1', size: 30, label: '1', style: { x: 280, y: 384 } }, { id: 'node2', size: 30, label: '2', style: { x: 234, y: 167 } }, { id: 'node3', size: 30, label: '3', style: { x: 391, y: 368 } }, { id: 'node4', size: 30, label: '4', style: { x: 444, y: 209 } }, { id: 'node5', size: 30, label: '5', style: { x: 378, y: 157 } }, { id: 'node6', size: 15, label: '6', style: { x: 229, y: 400 } }, { id: 'node7', size: 15, label: '7', style: { x: 281, y: 440 } }, { id: 'node8', size: 15, label: '8', style: { x: 188, y: 119 } }, { id: 'node9', size: 15, label: '9', style: { x: 287, y: 157 } }, { id: 'node10', size: 15, label: '10', style: { x: 185, y: 200 } }, { id: 'node11', size: 15, label: '11', style: { x: 238, y: 110 } }, { id: 'node12', size: 15, label: '12', style: { x: 239, y: 221 } }, { id: 'node13', size: 15, label: '13', style: { x: 176, y: 160 } }, { id: 'node14', size: 15, label: '14', style: { x: 389, y: 423 } }, { id: 'node15', size: 15, label: '15', style: { x: 441, y: 341 } }, { id: 'node16', size: 15, label: '16', style: { x: 442, y: 398 } }, ], edges: [ { source: 'node0', target: 'node1', label: '0-1' }, { source: 'node0', target: 'node2', label: '0-2' }, { source: 'node0', target: 'node3', label: '0-3' }, { source: 'node0', target: 'node4', label: '0-4' }, { source: 'node0', target: 'node5', label: '0-5' }, { source: 'node1', target: 'node6', label: '1-6' }, { source: 'node1', target: 'node7', label: '1-7' }, { source: 'node2', target: 'node8', label: '2-8' }, { source: 'node2', target: 'node9', label: '2-9' }, { source: 'node2', target: 'node10', label: '2-10' }, { source: 'node2', target: 'node11', label: '2-11' }, { source: 'node2', target: 'node12', label: '2-12' }, { source: 'node2', target: 'node13', label: '2-13' }, { source: 'node3', target: 'node14', label: '3-14' }, { source: 'node3', target: 'node15', label: '3-15' }, { source: 'node3', target: 'node16', label: '3-16' }, ], }, behaviors: ['zoom-canvas', 'drag-canvas', { key: 'hover-activate', type: 'hover-activate' }], autoFit: 'center', }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'hover-activate', type: 'hover-activate', animation: true, enable: true, degree: 1, direction: 'both', }; const optionFolder = gui.addFolder('Hover Activate Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'degree', 0, 10, 1); optionFolder.add(options, 'direction', { both: ['both'], in: ['in'], out: ['out'], }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'hover-activate', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['hover-activate'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'hover-activate', key: 'hover-activate-1', // 为交互指定标识符,方便动态更新 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | ------------- | -------------------- | ---------------------------------------------- | ---------------- | ---- | | type | 交互类型名称 | string | `hover-activate` | ✓ | | animation | 是否开启动画效果 | boolean | true | | | enable | 是否开启悬浮元素功能 | boolean \| ((event: IPointerEvent) => boolean) | true | | | degree | 激活元素的n度关系 | number \| ((event: IPointerEvent) => number); | 0 | | | direction | 指定边方向 | `both` \| `in` \| `out` | `both` | | | state | 激活元素的状态 | string | `active` | | | inactiveState | 不激活元素的状态 | string | - | | | onHover | 当元素被悬停时的回调 | (event: IPointerEvent) => void | - | | | onHoverEnd | 当悬停结束时的回调 | (event: IPointerEvent) => void | - | | ### enable `enable` 用于控制是否开启元素的悬浮高亮,可接收一个函数来动态控制 例如:只有节点开启悬浮高亮 ```typescript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'hover-activate', enable: (e) => { if (e.targetType === 'node') { return true; } return false; }, }, ], }); ``` ## 代码示例 ### 基础悬浮用法 ```typescript const graph = new Graph({ // 其他配置... behaviors: ['hover-activate'], }); ``` ### 节点触发高亮 ```typescript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'hover-activate', enable: (e) => { if (e.targetType === 'node') { return true; } return false; }, }, ], }); ``` ### 流程图移入节点 下一步节点高亮 ```typescript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'hover-activate', degree: 1, direction: 'out', enable: (e) => { if (e.targetType === 'node') { return true; } return false; }, }, ], }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const format = (data) => { const { nodes, edges } = data; return { nodes: nodes.map(({ id, ...node }) => ({ id, data: node })), edges: edges.map(({ id, source, target, ...edge }) => ({ id, source, target, data: edge })), }; }; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/xiaomi.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: format(data), behaviors: ['hover-activate'], layout: { type: 'force', preventOverlap: true, nodeSize: 24, }, animation: false, }); graph.render(); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 三角形节点 Triangle - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/Triangle/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/Triangle.md - Description: 三角形节点 Triangle --- title: "三角形节点 Triangle" description: "三角形节点 Triangle" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/Triangle/" version: "5.1.1" --- ## 概述 三角形是一个三边几何形状,具有明确的方向性。 适用场景: - 用于表示方向性节点、警告或提示。 - 适合表示流程图中的方向指示或层级关系。 - 常用于流程图、网络图、拓扑图等。 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { autoFit: 'center', data: { nodes: [{ id: 'node1', style: { size: 40, fill: '#7e3feb' } }] }, node: { type: 'triangle' }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 220 }, (gui, graph) => { gui.add({ type: 'triangle' }, 'type').disable(); const options = { size: 40, direction: 'up', }; const optionFolder = gui.addFolder('triangle.style'); optionFolder.add(options, 'size', 0, 100, 1); optionFolder.add(options, 'direction', ['up', 'left', 'right', 'down']); optionFolder.onChange(({ property, value }) => { graph.updateNodeData([{ id: 'node1', style: { [property]: value } }]); graph.render(); }); }, ); ``` 设置 `node.type` 为 `triangle` 以使用三角形节点。 ## 样式配置 > 如果元素有其特定的属性,我们将在下面列出。对于所有的通用样式属性,见 [BaseNode](/zh/manual/element/node/BaseNode/) | 属性 | 描述 | 类型 | 默认值 | 必选 | | --------- | ------------ | ----------------------------------- | ------ | ---- | | direction | 三角形的方向 | `up` \| `left` \| `right` \| `down` | `up` | ## 示例 ### 内置三角形节点效果 ```ts import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'triangle', style: { size: 40, direction: (d) => (d.id === 'ports' ? 'left' : undefined), labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 鱼骨布局 Fishbone - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/Fishbone/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/Fishbone.md - Description: 鱼骨布局 Fishbone --- title: "鱼骨布局 Fishbone" description: "鱼骨布局 Fishbone" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/Fishbone/" version: "5.1.1" --- ## 概述 鱼骨布局是一种专门用于表示层次结构数据的图形布局方式。它通过模拟鱼骨的形状,将数据节点按照层次结构排列,使得数据的层次关系更加清晰直观。鱼骨布局特别适用于需要展示因果关系、层次结构或分类信息的数据集。 ## 使用场景 - 需要展示层次结构数据,如组织结构、分类体系 - 需要展示问题分析过程,如故障分析、质量分析 - 需要展示决策过程,如决策树、影响因素分析 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'Quality', depth: 0, children: ['Machine', 'Method', 'Material', 'Man Power', 'Measurement', 'Milieu'], }, { id: 'Machine', depth: 1, children: ['Mill', 'Mixer', 'Metal Lathe'], }, { id: 'Mill', depth: 2, }, { id: 'Mixer', depth: 2, }, { id: 'Metal Lathe', depth: 2, children: ['Milling'], }, { id: 'Milling', depth: 3, }, { id: 'Method', depth: 1, }, { id: 'Material', depth: 1, children: ['Masonite', 'Marscapone', 'Meat'], }, { id: 'Masonite', depth: 2, children: ['spearMint', 'pepperMint', 'test1'], }, { id: 'spearMint', depth: 3, }, { id: 'pepperMint', depth: 3, children: ['test3'], }, { id: 'test3', depth: 4, }, { id: 'test1', depth: 3, children: ['test4'], }, { id: 'test4', depth: 4, }, { id: 'Marscapone', depth: 2, children: ['Malty', 'Minty'], }, { id: 'Malty', depth: 3, }, { id: 'Minty', depth: 3, }, { id: 'Meat', depth: 2, children: ['Mutton'], }, { id: 'Mutton', depth: 3, }, { id: 'Man Power', depth: 1, children: ['Manager', "Master's Student", 'Magician', 'Miner', 'Magister', 'Massage Artist'], }, { id: 'Manager', depth: 2, }, { id: "Master's Student", depth: 2, }, { id: 'Magician', depth: 2, }, { id: 'Miner', depth: 2, }, { id: 'Magister', depth: 2, children: ['Malpractice'], }, { id: 'Malpractice', depth: 3, }, { id: 'Massage Artist', depth: 2, children: ['Masseur', 'Masseuse'], }, { id: 'Masseur', depth: 3, }, { id: 'Masseuse', depth: 3, }, { id: 'Measurement', depth: 1, children: ['Malleability'], }, { id: 'Malleability', depth: 2, }, { id: 'Milieu', depth: 1, children: ['Marine'], }, { id: 'Marine', depth: 2, }, ], edges: [ { source: 'Quality', target: 'Machine', }, { source: 'Quality', target: 'Method', }, { source: 'Quality', target: 'Material', }, { source: 'Quality', target: 'Man Power', }, { source: 'Quality', target: 'Measurement', }, { source: 'Quality', target: 'Milieu', }, { source: 'Machine', target: 'Mill', }, { source: 'Machine', target: 'Mixer', }, { source: 'Machine', target: 'Metal Lathe', }, { source: 'Metal Lathe', target: 'Milling', }, { source: 'Material', target: 'Masonite', }, { source: 'Material', target: 'Marscapone', }, { source: 'Material', target: 'Meat', }, { source: 'Masonite', target: 'spearMint', }, { source: 'Masonite', target: 'pepperMint', }, { source: 'Masonite', target: 'test1', }, { source: 'pepperMint', target: 'test3', }, { source: 'test1', target: 'test4', }, { source: 'Marscapone', target: 'Malty', }, { source: 'Marscapone', target: 'Minty', }, { source: 'Meat', target: 'Mutton', }, { source: 'Man Power', target: 'Manager', }, { source: 'Man Power', target: "Master's Student", }, { source: 'Man Power', target: 'Magician', }, { source: 'Man Power', target: 'Miner', }, { source: 'Man Power', target: 'Magister', }, { source: 'Man Power', target: 'Massage Artist', }, { source: 'Magister', target: 'Malpractice', }, { source: 'Massage Artist', target: 'Masseur', }, { source: 'Massage Artist', target: 'Masseuse', }, { source: 'Measurement', target: 'Malleability', }, { source: 'Milieu', target: 'Marine', }, ], }, node: { type: 'rect', style: { size: [32, 32], // fill: () => randomColor(), label: false, labelFill: '#262626', labelFontFamily: 'Gill Sans', labelMaxLines: 2, labelMaxWidth: '100%', labelPlacement: 'center', labelText: (d) => d.id, labelWordWrap: true, }, }, edge: { type: 'polyline', style: { lineWidth: 3, }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], autoFit: 'view', layout: { type: 'fishbone', direction: 'RL', hGap: 50, vGap: 50, getRibSep: () => 60, }, }, { width: 600, height: 400 }, (gui, graph) => { const options = { type: 'fishbone', direction: 'RL', hGap: 50, vGap: 50, getRibSep: 60, }; const optionFolder = gui.addFolder('Fishbone Layout Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'direction', ['RL', 'LR']); optionFolder.add(options, 'hGap', 20, 100, 10); optionFolder.add(options, 'vGap', 20, 100, 10); optionFolder.add(options, 'getRibSep', 30, 100, 10); optionFolder.onChange(async ({ property, value }) => { graph.setLayout( Object.assign({}, graph.getLayout(), { [property]: property === 'getRibSep' ? () => value : value, }), ); await graph.layout(); // 调整 direction 后部分node可能会溢出屏幕,重新执行下fitView if (property === 'direction') { graph.fitView(); } }); }, ); ``` ## 基本用法 ```js const graph = new Graph({ layout: { type: 'fishbone', direction: 'LR', hGap: 50, vGap: 50, getRibSep: () => 60, }, }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ---------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---- | | type | 布局类型 | `fishbone` | - | ✓ | | direction | 排布方向,`RL` 从右到左,鱼头在右;`LR` 从左到右,鱼头在左 | `RL` \| `LR` | `RL` | | | hGap | 水平间距 | number | - | | | vGap | 垂直间距 | number | - | | | getRibSep | 获取鱼骨间距 | (node: NodeData) => number | () => 60 | | | width | 布局宽度 | number | - | | | height | 布局高度 | number | - | | | nodeSize | 节点大小 | number \| [number, number] \| [number, number, number] \| ((node: NodeData) => number \| [number, number] \| [number, number, number]) | - | | | isLayoutInvisibleNodes | 不可见节点是否参与布局,当 preLayout 为 true 时生效 | boolean | - | | | nodeFilter | 参与该布局的节点 | (node: NodeData) => boolean | - | | | preLayout | 使用前布局,在初始化元素前计算布局,不适用于流水线布局 | boolean | - | | ## 代码示例 ### 基础用法 最简单的配置方式: ```js import { Graph, treeToGraphData } from '@antv/g6'; const graph = new Graph({ layout: { type: 'fishbone', }, autoFit: 'view', data: treeToGraphData({ nodes: [ { id: 'root', data: { label: 'Root' } }, { id: 'child1', data: { label: 'Child 1' } }, { id: 'child2', data: { label: 'Child 2' } }, { id: 'child3', data: { label: 'Child 3' } }, ], edges: [ { id: 'e1', source: 'root', target: 'child1' }, { id: 'e2', source: 'root', target: 'child2' }, { id: 'e3', source: 'root', target: 'child3' }, ], }), edge: { type: 'polyline', style: { lineWidth: 3, }, }, behaviors: ['drag-canvas'], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 400, layout: { type: 'fishbone', }, autoFit: 'view', data: { nodes: [ { id: 'Quality', depth: 0, children: ['Machine', 'Method', 'Material', 'Man Power', 'Measurement', 'Milieu'], }, { id: 'Machine', depth: 1, children: ['Mill', 'Mixer', 'Metal Lathe'], }, { id: 'Mill', depth: 2, }, { id: 'Mixer', depth: 2, }, { id: 'Metal Lathe', depth: 2, children: ['Milling'], }, { id: 'Milling', depth: 3, }, { id: 'Method', depth: 1, }, { id: 'Material', depth: 1, children: ['Masonite', 'Marscapone', 'Meat'], }, { id: 'Masonite', depth: 2, children: ['spearMint', 'pepperMint', 'test1'], }, { id: 'spearMint', depth: 3, }, { id: 'pepperMint', depth: 3, children: ['test3'], }, { id: 'test3', depth: 4, }, { id: 'test1', depth: 3, children: ['test4'], }, { id: 'test4', depth: 4, }, { id: 'Marscapone', depth: 2, children: ['Malty', 'Minty'], }, { id: 'Malty', depth: 3, }, { id: 'Minty', depth: 3, }, { id: 'Meat', depth: 2, children: ['Mutton'], }, { id: 'Mutton', depth: 3, }, { id: 'Man Power', depth: 1, children: ['Manager', "Master's Student", 'Magician', 'Miner', 'Magister', 'Massage Artist'], }, { id: 'Manager', depth: 2, }, { id: "Master's Student", depth: 2, }, { id: 'Magician', depth: 2, }, { id: 'Miner', depth: 2, }, { id: 'Magister', depth: 2, children: ['Malpractice'], }, { id: 'Malpractice', depth: 3, }, { id: 'Massage Artist', depth: 2, children: ['Masseur', 'Masseuse'], }, { id: 'Masseur', depth: 3, }, { id: 'Masseuse', depth: 3, }, { id: 'Measurement', depth: 1, children: ['Malleability'], }, { id: 'Malleability', depth: 2, }, { id: 'Milieu', depth: 1, children: ['Marine'], }, { id: 'Marine', depth: 2, }, ], edges: [ { source: 'Quality', target: 'Machine', }, { source: 'Quality', target: 'Method', }, { source: 'Quality', target: 'Material', }, { source: 'Quality', target: 'Man Power', }, { source: 'Quality', target: 'Measurement', }, { source: 'Quality', target: 'Milieu', }, { source: 'Machine', target: 'Mill', }, { source: 'Machine', target: 'Mixer', }, { source: 'Machine', target: 'Metal Lathe', }, { source: 'Metal Lathe', target: 'Milling', }, { source: 'Material', target: 'Masonite', }, { source: 'Material', target: 'Marscapone', }, { source: 'Material', target: 'Meat', }, { source: 'Masonite', target: 'spearMint', }, { source: 'Masonite', target: 'pepperMint', }, { source: 'Masonite', target: 'test1', }, { source: 'pepperMint', target: 'test3', }, { source: 'test1', target: 'test4', }, { source: 'Marscapone', target: 'Malty', }, { source: 'Marscapone', target: 'Minty', }, { source: 'Meat', target: 'Mutton', }, { source: 'Man Power', target: 'Manager', }, { source: 'Man Power', target: "Master's Student", }, { source: 'Man Power', target: 'Magician', }, { source: 'Man Power', target: 'Miner', }, { source: 'Man Power', target: 'Magister', }, { source: 'Man Power', target: 'Massage Artist', }, { source: 'Magister', target: 'Malpractice', }, { source: 'Massage Artist', target: 'Masseur', }, { source: 'Massage Artist', target: 'Masseuse', }, { source: 'Measurement', target: 'Malleability', }, { source: 'Milieu', target: 'Marine', }, ], }, edge: { type: 'polyline', style: { lineWidth: 3, }, }, behaviors: ['drag-canvas'], }); graph.render(); ``` ## 实际案例 ```ts import { Graph, treeToGraphData } from '@antv/g6'; const data = { id: 'Quality', children: [ { id: 'Machine', children: [{ id: 'Mill' }, { id: 'Mixer' }, { id: 'Metal Lathe', children: [{ id: 'Milling' }] }], }, { id: 'Method' }, { id: 'Material', children: [ { id: 'Masonite', children: [ { id: 'spearMint' }, { id: 'pepperMint', children: [{ id: 'test3' }] }, { id: 'test1', children: [{ id: 'test4' }] }, ], }, { id: 'Marscapone', children: [{ id: 'Malty' }, { id: 'Minty' }], }, { id: 'Meat', children: [{ id: 'Mutton' }] }, ], }, { id: 'Man Power', children: [ { id: 'Manager' }, { id: "Master's Student" }, { id: 'Magician' }, { id: 'Miner' }, { id: 'Magister', children: [{ id: 'Malpractice' }] }, { id: 'Massage Artist', children: [{ id: 'Masseur' }, { id: 'Masseuse' }], }, ], }, { id: 'Measurement', children: [{ id: 'Malleability' }], }, { id: 'Milieu', children: [{ id: 'Marine' }], }, ], }; export const layoutFishbone = async (context) => { const graph = new Graph({ ...context, container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { type: 'rect', style: { size: [32, 32], // fill: () => randomColor(), label: false, labelFill: '#262626', labelFontFamily: 'Gill Sans', labelMaxLines: 2, labelMaxWidth: '100%', labelPlacement: 'center', labelText: (d) => d.id, labelWordWrap: true, }, }, edge: { type: 'polyline', style: { lineWidth: 3, }, }, layout: { type: 'fishbone', vGap: 48, hGap: 48, direction: 'RL', }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], animation: false, }); await graph.render(); layoutFishbone.form = (panel) => { const config = { type: 'fishbone', direction: 'RL', }; return [ panel .add(config, 'direction', ['LR', 'RL']) .name('Direction') .onChange((value) => { graph.setLayout((prev) => ({ ...prev, direction: value })); graph.render(); }), ]; }; return graph; }; layoutFishbone(); ``` - [Fishbone布局](/zh/examples/layout/fishbone/basic/) ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 图例 Legend - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Legend/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Legend.md - Description: 图例 Legend --- title: "图例 Legend" description: "图例 Legend" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Legend/" version: "5.1.1" --- ## 概述 图例(Legend)插件用于展示图中元素的分类信息,支持节点、边、组合的分类信息展示。通过图例,用户可以快速感知到图中相关元素的分类信息,也可以通过点击对应图例项来快速定位到元素,提高用户的浏览效率。 ## 使用场景 这一插件主要用于: - 通过图例快速对元素进行分类 - 通过图例快速高亮定位到对应元素 ## 基本用法 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, // 其他配置... plugins: [ { type: 'legend', // 插件类型为 legend nodeField: 'cluster', // 用于节点分组的数组字段名称 edgeField: 'cluster', // 用于边分组的数组字段名称 }, ], }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ----------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------ | ---- | | type | 插件类型 | string | `legend` | ✓ | | key | 插件唯一标识符,用于后续更新 | string | - | | | trigger | 图例项触发对应项高亮的方式:
- `hover`:鼠标移入图例项时触发
- `click`:鼠标点击图例项时触发 | `hover` \| `click` | `hover` | | | position | 图例在画布中的相对位置,[可选值](#cardinalplacement) | [CardinalPlacement](#cardinalplacement) | `bottom` | | | container | 图例挂载的容器,无则挂载到 Graph 所在容器 | HTMLElement \| string | - | | | className | 图例画布类名,传入外置容器时不生效 | string | - | | | containerStyle | 图例的容器样式,传入外置容器时不生效 | [CSSStyleDeclaration](https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration) | - | | | nodeField | 节点分类标识 | string \| (item: ElementDatum) => string | - | | | edgeField | 边分类标识 | string \| (item: ElementDatum) => string | - | | | comboField | 组合分类标识 | string \| (item: ElementDatum) => string | - | | | orientation | 图例项的布局方向:
- `horizontal`:水平方向
- `vertical`:垂直方向 | `horizontal` \| `vertical` | 'horizontal' | | | layout | 布局方式:
- `flex`:弹性布局
- `grid`:网格布局 | `flex` \| `grid` | `flex` | | | showTitle | 是否显示标题 | boolean | false | | titleText | 标题内容 | string | "" | | x | 图例在画布中的相对的横向位置,优先级高于position | number | - | | | y | 图例在画布中的相对的纵向位置,优先级高于position | number | - | | | width | 图例的宽度 | number | 240 | | | height | 图例的高度 | number | 160 | | | itemSpacing | 图例项的文本和对应标记之间的间距 | number | 4 | | | rowPadding | 图例中每行之间的间距 | number | 10 | | | colPadding | 图例中每列之间的间距 | number | 10 | | | itemMarkerSize | 图例项标记的大小 | number | 16 | | | itemLabelFontSize | 图例项文本的字体大小 | number | 16 | | | gridCol | 图例项在宽度允许情况下的最大列数 | number | - | | | gridRow | 图例项在高度允许情况下的最大行数 | number | - | | ### CardinalPlacement `position` 属性支持以下值: - `'top-left'`:左上角 - `'top-right'`:右上角 - `'bottom-left'`:左下角 - `'bottom-right'`:右下角 - `'left-top'`:左侧靠上 - `'left-bottom'`:左侧靠下 - `'right-top'`:右侧靠上 - `'right-bottom'`:右侧靠下 ## 代码示例 ### 基础图例 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ // 其他配置... plugins: [ { type: 'legend', // 插件类型为 legend nodeField: 'cluster', // 用于节点分组的数组字段名称 edgeField: 'cluster', // 用于边分组的数组字段名称 }, ], }); ``` ### 自定义图例位置 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, // 其他配置... plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', // 可以通过 position 快捷的来指定位置 // position: "top-left", // 也可以通过x,y来更加灵活的控制图例的位置 x: 20, y: 20, }, ], }); ``` ### 自定义图例项布局 ```js const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, ], edges: [{ source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }], }; const graph = new Graph({ data, // 其他配置... plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', layout: 'flex', // 控制只显示一行 gridRow: 1, // 控制一行显示10列,当列宽不足时会显示翻页按钮 gridCol: 10, }, ], }); ``` ## 常见问题 ### 1. 设置了 orientation 无效? `orientation`主要控制布局的方向,具体展示**一行多列**还是**一列多行**,主要通过 `gridRow` 以及`gridCol`来控制,例如想要看起来像是竖向的图例项,则可以通过这样配置: ```js plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', layout: "flex", // 控制一行显示1列 gridCol:1, // 控制显示最多20行 gridRow: 20, }, ], ``` 这样就变成了只有一列的图例,符合视觉上的竖向排列。 ### 2. 如何动态更新工具栏? 可以使用 `updatePlugin` 方法动态更新工具栏: ```js const graph = new Graph({ data, // 其他配置... plugins: [ { type: 'legend', key: 'my-legend', nodeField: 'cluster', edgeField: 'cluster', }, ], }); // 更新图例位置 graph.updatePlugin({ key: 'my-legend', position: 'bottom-right', }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, { id: 'node-3', type: 'triangle', data: { cluster: 'node-type3' } }, { id: 'node-4', type: 'diamond', data: { cluster: 'node-type4' } }, ], edges: [ { source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }, { source: 'node-1', target: 'node-4', data: { cluster: 'edge-type2' } }, { source: 'node-3', target: 'node-4' }, { source: 'node-2', target: 'node-4', data: { cluster: 'edge-type3' } }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: 32 }, palette: { field: 'cluster', }, }, layout: { type: 'force', }, plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', }, ], }); graph.render(); ``` #### 套索选择 LassoSelect - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/LassoSelect/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/LassoSelect.md - Description: 套索选择 LassoSelect --- title: "套索选择 LassoSelect" description: "套索选择 LassoSelect" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/LassoSelect/" version: "5.1.1" --- ## 概述 鼠标点击拖出一个 **不规则的** 框框笼罩元素,精准框选范围内的元素会被选中。 ## 使用场景 这一交互主要用于: - 快速选中一批元素,并且更容易的避开不想选的元素 - 快速取消选中一批元素,并且更容易的避开想保留的元素 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'lasso-select', key: 'lasso-select', }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'lasso-select', type: 'lasso-select', animation: false, enable: true, enableElements: ['node', 'edge', 'combo'], immediately: false, mode: 'default', state: 'selected', trigger: 'shift+drag', }; const optionFolder = gui.addFolder('LassoSelect Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'animation'); optionFolder.add(options, 'enable'); optionFolder.add(options, 'enableElements', [ ['node', 'edge', 'combo'], ['node', 'edge'], ['node', 'combo'], ['combo', 'edge'], ['node'], ['edge'], ['combo'], ]); optionFolder.add(options, 'trigger', { 'shift+drag': ['shift'], drag: [], }); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'mode', ['union', 'intersect', 'diff', 'default']).onChange((e) => { immediately.show(e === 'default'); }); const immediately = optionFolder.add(options, 'immediately'); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'lasso-select', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['lasso-select'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'lasso-select', key: 'lasso-select', immediately: true, // 可以看到框框笼罩过去时,元素立即被框选了 trigger: ['shift', 'alt', 'control'], // 配合多种按键进行框选 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------- | ---- | | type | 交互类型名称。此插件已内置,你可以通过 `type: 'lasso-select'` 来使用它。 | `lasso-select` \| string | `lasso-select` | ✓ | | animation | 是否启用动画 | boolean | false | | | enable | 是否启用框选功能 | boolean \| ((event: [Event](/zh/api/event/#事件对象属性)) => boolean) | true | | | enableElements | 可框选的元素类型 | ( `node` \| `edge` \| `combo` )[] | [`node`, `combo`, `edge`] | | | [immediately](#immediately) | 是否及时框选, 仅在[框选模式 mode](#mode)为 `default` 时生效 | boolean | false | | | [mode](#mode) | 框选的选择模式 | `union` \| `intersect` \| `diff` \| `default` | `default` | | | onSelect | 框选元素状态回调 | (states:Record<string,string\|string[]>) =>Record<string,string\|string[]> | | | | state | 被选中时切换到该状态 | string \| `selected` \| `active` \| `inactive` \| `disabled` \| `highlight` | `selected` | | | [style](#style) | 框选时的 框样式 | RectStyleProps extends BaseStyleProps | [默认值](#style) | | | trigger | 按下该快捷键配合鼠标点击进行框选 **按键参考:** _MDN Key Values_ | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[] | [`shift`] | | ### immediately 是否及时框选, 仅在框选模式为 `default` 时生效 ```js const graph = new Graph({ behaviors: [ { type: 'lasso-select', key: 'lasso-select', immediately: true, // 可以看到框框笼罩过去时,元素立即被框选了 trigger: [], // 不需要配合其他按键,点击鼠标拖动即可框选 }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 200, data: { nodes: [ { id: 'node-1', style: { x: 100, y: 50 } }, { id: 'node-2', style: { x: 260, y: 50 } }, { id: 'node-3', style: { x: 280, y: 100 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, }, edge: { stroke: '#8b9baf', }, behaviors: [ { type: 'lasso-select', key: 'lasso-select', immediately: true, // 立即框选 trigger: [], }, ], plugins: [{ type: 'grid-line', size: 30 }], }); graph.render(); ``` ### mode 框选的选择模式 - `union`:保持已选元素的当前状态,并添加指定的 state 状态。 - `intersect`:如果已选元素已有指定的 state 状态,则保留;否则清除该状态。 - `diff`:对已选元素的指定 state 状态进行取反操作。 - `default`:清除已选元素的当前状态,并添加指定的 state 状态。 ```js const graph = new Graph({ behaviors: [ { type: 'lasso-select', key: 'lasso-select', mode: 'default', // 框选模式, 默认框选模式 }, ], }); ``` ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, state: { custom: { fill: '#ffa940' }, }, }, edge: { stroke: '#8b9baf', state: { custom: { stroke: '#ffa940' }, }, }, behaviors: [ { type: 'lasso-select', key: 'lasso-select', trigger: [], immediately: true, }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'lasso-select', type: 'lasso-select', animation: false, enable: true, enableElements: ['node', 'edge', 'combo'], mode: 'default', state: 'selected', }; const optionFolder = gui.addFolder('lassoSelect Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'state', ['active', 'selected', 'custom']); optionFolder.add(options, 'mode', ['union', 'intersect', 'diff', 'default']); // .onChange((e) => { // immediately.show(e === 'default'); // }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'lasso-select', [property]: value, }); graph.render(); }); }, ); ``` ### style | 属性 | 描述 | 类型 | 默认值 | | ----------------- | ------------------ | ---------------------------------------- | --------- | | cursor | 鼠标样式 | string | | | fill | 填充颜色 | string \| Pattern \| null | `#1677FF` | | fillOpacity | 填充透明度 | number \| string | 0.1 | | isBillboard | 是否启用公告牌模式 | boolean | | | isSizeAttenuation | 是否启用大小衰减 | boolean | | | lineCap | 线段端点样式 | `butt` \| `round` \| `square` | | | lineDash | 虚线配置 | number \| string \| (string \| number)[] | | | lineDashOffset | 虚线偏移量 | number | | | lineJoin | 线段连接处样式 | `miter` \| `round` \| `bevel` | | | lineWidth | 线宽度 | number \| string | 1 | | opacity | 整体透明度 | number \| string | | | radius | 矩形圆角半径 | number \| string \| number[] | | | shadowBlur | 阴影模糊程度 | number | | | shadowColor | 阴影颜色 | string | | | shadowOffsetX | 阴影 X 方向偏移 | number | | | shadowOffsetY | 阴影 Y 方向偏移 | number | | | stroke | 描边颜色 | string \| Pattern \| null | `#1677FF` | | strokeOpacity | 描边透明度 | number \| string | | | visibility | 可见性 | `visible` \| `hidden` | | | zIndex | 渲染层级 | number | 2 | **示例**: ```js const graph = new Graph({ behaviors: [ { type: 'lasso-select', key: 'lasso-select', style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], // 虚线外框 // rgb超级炫彩框框 fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], }); ``` ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: [ { id: 'node-1', style: { x: 200, y: 100 } }, { id: 'node-2', style: { x: 360, y: 100 } }, { id: 'node-3', style: { x: 280, y: 220 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-2', target: 'node-3' }, ], }, node: { style: { fill: '#7e3feb' }, }, edge: { stroke: '#8b9baf', }, behaviors: [ { type: 'lasso-select', key: 'lasso-select', trigger: [], immediately: true, style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], // 虚线外框 // rgb超级炫彩框框 fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], plugins: [{ type: 'grid-line', size: 30 }], animation: true, }); graph.render(); ``` ### trigger 按下该快捷键配合鼠标点击进行框选,若设为**空数组**时则表示鼠标点击进行框选,不需要按下其他按键配合。 注意,`trigger` 设置为 `['drag']` 时会导致 `drag-canvas` 行为失效。两者不可同时配置。 ### 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', style: { x: 200, y: 250 } }, { id: 'node-2', style: { x: 250, y: 200 } }, { id: 'node-3', style: { x: 300, y: 250 } }, { id: 'node-4', style: { x: 250, y: 300 } }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-2', target: 'node-3' }, { source: 'node-3', target: 'node-4' }, { source: 'node-4', target: 'node-1' }, ], }, behaviors: [ { key: 'lasso-select', type: 'lasso-select', enable: true, animation: false, mode: 'default', // union intersect diff default state: 'selected', // 'active', 'selected', 'inactive', ... trigger: [], // ['Shift', 'Alt', 'Control', 'Drag', 'Meta', ...] style: { width: 0, height: 0, lineWidth: 4, lineDash: [2, 2], fill: 'linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', stroke: 'pink', fillOpacity: 0.2, zIndex: 2, pointerEvents: 'none', }, }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 自定义节点 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/custom-node/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/custom-node.md - Description: 自定义节点 --- title: "自定义节点" description: "自定义节点" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/custom-node/" version: "5.1.1" --- G6 提供了一系列 [内置节点](/zh/manual/element/node/BaseNode/),包含 [circle(圆形节点)](/zh/manual/element/node/Circle/)、[diamond(菱形节点)](/zh/manual/element/node/Diamond/)、[donut(甜甜圈节点)](/zh/manual/element/node/Donut/)、[ellipse(椭圆节点)](/zh/manual/element/node/Ellipse/)、[hexagon(六边形节点)](/zh/manual/element/node/Hexagon/)、[html(HTML节点)](/zh/manual/element/node/Html/)、[image(图片节点)](/zh/manual/element/node/Image/)、[rect(矩形节点)](/zh/manual/element/node/Rect/)、[star(星形节点)](/zh/manual/element/node/Star/) 和 [triangle(三角形节点)](/zh/manual/element/node/Triangle/)。这些内置节点能够满足大部分基础场景需求。 但在实际项目中,你可能会遇到这些基础节点无法满足的需求。这时,你需要创建自定义节点。别担心,这比你想象的要简单! ## 自定义节点的方式 **选择合适的方式** 创建自定义节点的方式主要有两种途径: ### 1. 继承现有节点类型 **推荐** 这是最常用的方式,你可以选择继承以下类型之一: - [`BaseNode`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/base-node.ts) - 最基础的节点类,提供节点的核心功能 - [`Circle`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/circle.ts) - 圆形节点 - [`Rect`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/rect.ts) - 矩形节点 - [`Ellipse`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/ellipse.ts) - 椭圆节点 - [`Diamond`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/diamond.ts) - 菱形节点 - [`Triangle`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/triangle.ts) - 三角形节点 - [`Star`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/star.ts) - 星形节点 - [`Image`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/image.ts) - 图片节点 - [`Donut`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/donut.ts) - 甜甜圈节点 - [`Hexagon`](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/hexagon.ts) - 六边形节点 **为什么选择这种方式?** - 📌 **代码量少**:复用现有节点的属性和方法,只需专注于新增功能 - 📌 **开发迅速**:适合大多数项目需求,快速实现业务目标 - 📌 **易于维护**:代码结构清晰,继承关系明确 :::tip\{title=立即开始\} 如果你选择继承现有节点类型(推荐),可以直接跳到 [三步创建你的第一个自定义节点](#三步创建你的第一个自定义节点) 开始实践。大部分用户都会选择这种方式! ::: ### 2. 基于 G 图形系统从零开发 **高级用法** 如果现有节点类型都不满足需求,你可以基于 G 的底层图形系统从零创建节点。 **为什么选择这种方式?** - 📌 **最大自由度**:完全控制节点的每个细节,实现任意复杂效果 - 📌 **特殊需求**:现有节点类型无法满足的高度定制场景 - 📌 **性能优化**:针对特定场景的性能优化 :::warning\{title=注意事项\} 从零开发的自定义节点需要自行处理所有细节,包括图形绘制、事件响应、状态变化等,开发难度较大。这里可以直接参考 [源码](https://github.com/antvis/G6/blob/v5/packages/g6/src/elements/nodes/base-node.ts) 进行实现。 ::: ## 三步创建你的第一个自定义节点 让我们从一个简单的例子开始 - 创建一个 **带有主副标题的矩形节点**: ```ts import { Graph, register, Rect, ExtensionCategory } from '@antv/g6'; // 第一步:创建自定义节点类 class DualLabelNode extends Rect { // 副标题样式 getSubtitleStyle(attributes) { return { x: 0, y: 45, // 放在主标题下方 text: attributes.subtitle || '', fontSize: 12, fill: '#666', textAlign: 'center', textBaseline: 'middle', }; } // 绘制副标题 drawSubtitleShape(attributes, container) { const subtitleStyle = this.getSubtitleStyle(attributes); this.upsert('subtitle', 'text', subtitleStyle, container); } // 渲染方法 render(attributes = this.parsedAttributes, container) { // 1. 渲染基础矩形和主标题 super.render(attributes, container); // 2. 添加副标题 this.drawSubtitleShape(attributes, container); } } // 第二步:注册自定义节点 register(ExtensionCategory.NODE, 'dual-label-node', DualLabelNode); // 第三步:使用自定义节点 const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 }, data: { title: '节点 A', // 主标题 subtitle: '你的第一个自定义节点', // 副标题 }, }, ], }, node: { type: 'dual-label-node', style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, radius: 5, // 主标题样式 labelText: (d) => d.data.title, labelFill: '#222', labelFontSize: 14, labelFontWeight: 500, // 副标题 subtitle: (d) => d.data.subtitle, }, }, }); graph.render(); ``` ### 第一步:编写自定义节点类 继承 G6 的 `Rect`(矩形节点),并添加一个副标题: ```js import { Rect, register, Graph, ExtensionCategory } from '@antv/g6'; // 创建自定义节点,继承自 Rect class DualLabelNode extends Rect { // 副标题样式 getSubtitleStyle(attributes) { return { x: 0, y: 45, // 放在主标题下方 text: attributes.subtitle || '', fontSize: 12, fill: '#666', textAlign: 'center', textBaseline: 'middle', }; } // 绘制副标题 drawSubtitleShape(attributes, container) { const subtitleStyle = this.getSubtitleStyle(attributes); this.upsert('subtitle', 'text', subtitleStyle, container); } // 渲染方法 render(attributes = this.parsedAttributes, container) { // 1. 渲染基础矩形和主标题 super.render(attributes, container); // 2. 添加副标题 this.drawSubtitleShape(attributes, container); } } ``` ### 第二步:注册自定义节点 使用 `register` 方法注册节点类型,这样 G6 才能识别你的自定义节点: ```js register(ExtensionCategory.NODE, 'dual-label-node', DualLabelNode); ``` `register` 方法需要三个参数: - 扩展类别:`ExtensionCategory.NODE` 表示这是一个节点类型 - 类型名称:`dual-label-node` 是我们给这个自定义节点起的名字,后续会在配置中使用 - 类定义:`DualLabelNode` 是我们刚刚创建的节点类 ### 第三步:应用自定义节点 在图配置中使用自定义节点: ```js const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 }, data: { title: '节点 A', // 主标题 subtitle: '你的第一个自定义节点', // 副标题 }, }, ], }, node: { type: 'dual-label-node', style: { fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, radius: 8, // 主标题样式 labelText: (d) => d.data.title, labelFill: '#222', labelFontSize: 14, labelFontWeight: 500, // 副标题 subtitle: (d) => d.data.subtitle, }, }, }); graph.render(); ``` 🎉 恭喜!你已经创建了第一个自定义节点。它看起来很简单,但这个过程包含了自定义节点的核心思想:**继承一个基础节点类型**,然后 **重写 `render` 方法** 来添加自定义内容。 ## 理解数据流:如何在自定义节点中获取数据 在创建复杂的自定义节点之前,理解数据如何流入自定义节点是非常重要的。G6 为自定义节点提供了多种数据获取方式: ### 方式一:通过 `attributes` 参数(推荐) `render` 方法的第一个参数 `attributes` 包含了经过处理的样式属性,包括数据驱动的样式: ```js class CustomNode extends Rect { render(attributes, container) { // attributes 包含了所有样式属性,包括数据驱动的样式 console.log('当前节点的所有属性:', attributes); // 如果在 style 中定义了 customData: (d) => d.data.someValue // 那么可以通过 attributes.customData 获取 const customValue = attributes.customData; super.render(attributes, container); } } ``` ### 方式二:通过 `this.context.graph` 获取原始数据 当你需要访问节点的原始数据时,可以通过图实例获取: ```js class CustomNode extends Rect { // 便捷的数据获取方法 get nodeData() { return this.context.graph.getNodeData(this.id); } get data() { return this.nodeData.data || {}; } render(attributes, container) { // 获取节点的完整数据 const nodeData = this.nodeData; console.log('节点完整数据:', nodeData); // 获取 data 字段中的业务数据 const businessData = this.data; console.log('业务数据:', businessData); super.render(attributes, container); } } ``` ### 数据传递的完整流程 让我们通过一个具体例子来理解数据是如何从图数据传递到自定义节点的: ```ts import { Graph, register, Rect, ExtensionCategory } from '@antv/g6'; class DataFlowNode extends Rect { // 方式二:通过 graph 获取原始数据 get nodeData() { return this.context.graph.getNodeData(this.id); } get data() { return this.nodeData.data || {}; } render(attributes, container) { // 方式一:从 attributes 获取处理后的样式 console.log('从 attributes 获取:', { iconUrl: attributes.iconUrl, userName: attributes.userName, }); // 方式二:从原始数据获取 console.log('从原始数据获取:', { icon: this.data.icon, name: this.data.name, role: this.data.role, }); // 渲染基础矩形 super.render(attributes, container); // 使用数据渲染自定义内容 if (attributes.iconUrl) { this.upsert( 'icon', 'image', { x: -25, y: -12, width: 20, height: 20, src: attributes.iconUrl, }, container, ); } if (attributes.userName) { this.upsert( 'username', 'text', { x: 10, y: 0, text: attributes.userName, fontSize: 10, fill: '#666', textAlign: 'center', textBaseline: 'middle', }, container, ); } } } register(ExtensionCategory.NODE, 'data-flow-node', DataFlowNode); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'user1', style: { x: 100, y: 100 }, // 这里是节点的业务数据 data: { name: '张三', role: '开发者', icon: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix', }, }, ], }, node: { type: 'data-flow-node', style: { size: [80, 40], fill: '#f0f9ff', stroke: '#0ea5e9', lineWidth: 1, radius: 4, // 将 data 中的数据映射到样式属性 iconUrl: (d) => d.data.icon, // 这会变成 attributes.iconUrl userName: (d) => d.data.name, // 这会变成 attributes.userName // 主标题使用角色信息 labelText: (d) => d.data.role, labelFontSize: 12, labelFill: '#0369a1', }, }, }); graph.render(); ``` :::tip\{title=数据流总结\} 1. **图数据定义**:在 `data.nodes[].data` 中定义业务数据 2. **样式映射**:在 `node.style` 中使用函数将数据映射到样式属性 3. **节点获取**:在自定义节点中通过 `attributes` 或 `this.context.graph` 获取数据 4. **渲染使用**:使用获取到的数据渲染自定义图形 ::: ## 从简单到复杂:逐步构建功能丰富的节点 让我们通过实际例子,逐步增加节点的复杂度和功能。 ### 示例一:带图标和徽章的用户卡片节点 这个例子展示如何创建一个包含头像、姓名、状态徽章的用户卡片节点: ```ts import { Graph, register, Rect, ExtensionCategory } from '@antv/g6'; class UserCardNode extends Rect { get nodeData() { return this.context.graph.getNodeData(this.id); } get data() { return this.nodeData.data || {}; } // 头像样式 getAvatarStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: -width / 2 + 20, y: -height / 2 + 15, width: 30, height: 30, src: attributes.avatarUrl || '', radius: 15, // 圆形头像 }; } drawAvatarShape(attributes, container) { if (!attributes.avatarUrl) return; const avatarStyle = this.getAvatarStyle(attributes); this.upsert('avatar', 'image', avatarStyle, container); } // 状态徽章样式 getBadgeStyle(attributes) { const [width, height] = this.getSize(attributes); const status = this.data.status || 'offline'; const colorMap = { online: '#52c41a', busy: '#faad14', offline: '#8c8c8c', }; return { x: width / 2 - 8, y: -height / 2 + 8, r: 4, fill: colorMap[status], stroke: '#fff', lineWidth: 2, }; } drawBadgeShape(attributes, container) { const badgeStyle = this.getBadgeStyle(attributes); this.upsert('badge', 'circle', badgeStyle, container); } // 用户名样式 getUsernameStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: -width / 2 + 55, y: -height / 2 + 20, text: attributes.username || '', fontSize: 14, fill: '#262626', fontWeight: 'bold', textAlign: 'left', textBaseline: 'middle', }; } drawUsernameShape(attributes, container) { if (!attributes.username) return; const usernameStyle = this.getUsernameStyle(attributes); this.upsert('username', 'text', usernameStyle, container); } // 角色标签样式 getRoleStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: -width / 2 + 55, y: -height / 2 + 35, text: attributes.userRole || '', fontSize: 11, fill: '#8c8c8c', textAlign: 'left', textBaseline: 'middle', }; } drawRoleShape(attributes, container) { if (!attributes.userRole) return; const roleStyle = this.getRoleStyle(attributes); this.upsert('role', 'text', roleStyle, container); } render(attributes, container) { // 渲染基础矩形 super.render(attributes, container); // 添加各个组件 this.drawAvatarShape(attributes, container); this.drawBadgeShape(attributes, container); this.drawUsernameShape(attributes, container); this.drawRoleShape(attributes, container); } } register(ExtensionCategory.NODE, 'user-card-node', UserCardNode); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'user1', style: { x: 100, y: 100 }, data: { name: '张小明', role: '前端工程师', status: 'online', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Zhang', }, }, ], }, node: { type: 'user-card-node', style: { size: [140, 50], fill: '#ffffff', stroke: '#d9d9d9', lineWidth: 1, radius: 6, // 数据映射 avatarUrl: (d) => d.data.avatar, username: (d) => d.data.name, userRole: (d) => d.data.role, }, }, }); graph.render(); ``` ### 示例二:可点击操作按钮的节点 给节点加一个蓝色按钮,点击后触发事件(打印日志或执行回调)。 ```ts import { Graph, register, Rect, ExtensionCategory } from '@antv/g6'; class ClickableNode extends Rect { getButtonStyle(attributes) { return { x: 40, y: -10, width: 20, height: 20, radius: 10, fill: '#1890ff', cursor: 'pointer', // 鼠标指针变为手型 }; } drawButtonShape(attributes, container) { const btnStyle = this.getButtonStyle(attributes, container); const btn = this.upsert('button', 'rect', btnStyle, container); // 为按钮添加点击事件 if (!btn.__clickBound) { btn.addEventListener('click', (e) => { // 阻止事件冒泡,避免触发节点的点击事件 e.stopPropagation(); // 执行业务逻辑 console.log('Button clicked on node:', this.id); // 如果数据中有回调函数,则调用 if (typeof attributes.onButtonClick === 'function') { attributes.onButtonClick(this.id, this.data); } }); btn.__clickBound = true; // 标记已绑定事件,避免重复绑定 } } render(attributes, container) { super.render(attributes, container); // 添加一个按钮 this.drawButtonShape(attributes, container); } } register(ExtensionCategory.NODE, 'clickable-node', ClickableNode); const graph = new Graph({ container: 'container', height: 200, data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 }, }, ], }, node: { type: 'clickable-node', // 指定使用我们的自定义节点 style: { size: [60, 30], fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, radius: 5, onButtonClick: (id, data) => {}, }, }, }); graph.render(); ``` ### 示例三:响应状态变化的节点(点击变色) 常见的交互都需要节点和边通过样式变化做出反馈,例如鼠标移动到节点上、点击选中节点/边、通过交互激活边上的交互等,都需要改变节点和边的样式,有两种方式来实现这种效果: 1. 从 `data.states` 获取当前状态,在自定义节点类中处理状态变化; 2. 将交互状态同原始数据和绘制节点的逻辑分开,仅更新节点。 我们推荐用户使用第二种方式来实现节点的状态调整,可以通过以下方式来实现: 1. 实现自定义节点; 2. 在图配置项中配置节点状态样式; 3. 通过 `graph.setElementState()` 方法来设置节点状态。 基于 rect 扩展出一个 hole 图形,默认填充色为白色,当鼠标点击时变成橙色,实现这一效果的示例代码如下: ```ts import { Rect, register, Graph, ExtensionCategory } from '@antv/g6'; // 1. 定义节点类 class SelectableNode extends Rect { getHoleStyle(attributes) { return { x: 20, y: -10, radius: 10, width: 20, height: 20, fill: attributes.holeFill, }; } drawHoleShape(attributes, container) { const holeStyle = this.getHoleStyle(attributes, container); this.upsert('hole', 'rect', holeStyle, container); } render(attributes, container) { super.render(attributes, container); this.drawHoleShape(attributes, container); } } // 2. 注册节点 register(ExtensionCategory.NODE, 'selectable-node', SelectableNode, true); // 3. 创建图实例 const graph = new Graph({ container: 'container', height: 200, data: { nodes: [{ id: 'node-1', style: { x: 100, y: 100 } }], }, node: { type: 'selectable-node', style: { size: [120, 60], radius: 6, fill: '#7FFFD4', stroke: '#5CACEE', lineWidth: 2, holeFill: '#fff', }, state: { // 鼠标选中状态 selected: { holeFill: 'orange', }, }, }, }); // 4. 添加节点交互 graph.on('node:click', (evt) => { const nodeId = evt.target.id; graph.setElementState(nodeId, ['selected']); }); graph.render(); ``` #### ForceAtlas2 力导向布局 - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/ForceAtlas2Layout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/ForceAtlas2Layout.md - Description: ForceAtlas2 力导向布局 --- title: "ForceAtlas2 力导向布局" description: "ForceAtlas2 力导向布局" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/ForceAtlas2Layout/" version: "5.1.1" --- ## 概述 ForceAtlas2 是一种基于力导向的布局算法,它通过模拟物理系统中的力来优化节点位置。该布局特别适用于大规模网络数据的可视化,能够有效地展示节点之间的关系和聚类结构。 ## 使用场景 - 社交网络分析:展示用户之间的关系网络,通过节点度数反映用户影响力 - 知识图谱:展示概念之间的关联关系,通过聚类效果发现知识领域 - 系统架构图:展示系统组件之间的依赖关系,通过 hub 模式突出核心组件 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'Myriel' }, { id: 'Napoleon' }, { id: 'Mlle.Baptistine' }, { id: 'Mme.Magloire' }, { id: 'CountessdeLo' }, { id: 'Geborand' }, { id: 'Champtercier' }, { id: 'Cravatte' }, { id: 'Count' }, { id: 'OldMan' }, { id: 'Labarre' }, { id: 'Valjean' }, { id: 'Marguerite' }, { id: 'Mme.deR' }, { id: 'Isabeau' }, { id: 'Gervais' }, { id: 'Tholomyes' }, { id: 'Listolier' }, { id: 'Fameuil' }, { id: 'Blacheville' }, { id: 'Favourite' }, { id: 'Dahlia' }, { id: 'Zephine' }, { id: 'Fantine' }, { id: 'Mme.Thenardier' }, { id: 'Thenardier' }, { id: 'Cosette' }, { id: 'Javert' }, { id: 'Fauchelevent' }, { id: 'Bamatabois' }, { id: 'Perpetue' }, { id: 'Simplice' }, { id: 'Scaufflaire' }, { id: 'Woman1' }, { id: 'Judge' }, { id: 'Champmathieu' }, { id: 'Brevet' }, { id: 'Chenildieu' }, { id: 'Cochepaille' }, { id: 'Pontmercy' }, { id: 'Boulatruelle' }, { id: 'Eponine' }, { id: 'Anzelma' }, { id: 'Woman2' }, { id: 'MotherInnocent' }, { id: 'Gribier' }, { id: 'Jondrette' }, { id: 'Mme.Burgon' }, { id: 'Gavroche' }, { id: 'Gillenormand' }, { id: 'Magnon' }, { id: 'Mlle.Gillenormand' }, { id: 'Mme.Pontmercy' }, { id: 'Mlle.Vaubois' }, { id: 'Lt.Gillenormand' }, { id: 'Marius' }, { id: 'BaronessT' }, { id: 'Mabeuf' }, { id: 'Enjolras' }, { id: 'Combeferre' }, { id: 'Prouvaire' }, { id: 'Feuilly' }, { id: 'Courfeyrac' }, { id: 'Bahorel' }, { id: 'Bossuet' }, { id: 'Joly' }, { id: 'Grantaire' }, { id: 'MotherPlutarch' }, { id: 'Gueulemer' }, { id: 'Babet' }, { id: 'Claquesous' }, { id: 'Montparnasse' }, { id: 'Toussaint' }, { id: 'Child1' }, { id: 'Child2' }, { id: 'Brujon' }, { id: 'Mme.Hucheloup' }, ], edges: [ { source: 'Napoleon', target: 'Myriel', value: 1 }, { source: 'Mlle.Baptistine', target: 'Myriel', value: 8 }, { source: 'Mme.Magloire', target: 'Myriel', value: 10 }, { source: 'Mme.Magloire', target: 'Mlle.Baptistine', value: 6 }, { source: 'CountessdeLo', target: 'Myriel', value: 1 }, { source: 'Geborand', target: 'Myriel', value: 1 }, { source: 'Champtercier', target: 'Myriel', value: 1 }, { source: 'Cravatte', target: 'Myriel', value: 1 }, { source: 'Count', target: 'Myriel', value: 2 }, { source: 'OldMan', target: 'Myriel', value: 1 }, { source: 'Valjean', target: 'Labarre', value: 1 }, { source: 'Valjean', target: 'Mme.Magloire', value: 3 }, { source: 'Valjean', target: 'Mlle.Baptistine', value: 3 }, { source: 'Valjean', target: 'Myriel', value: 5 }, { source: 'Marguerite', target: 'Valjean', value: 1 }, { source: 'Mme.deR', target: 'Valjean', value: 1 }, { source: 'Isabeau', target: 'Valjean', value: 1 }, { source: 'Gervais', target: 'Valjean', value: 1 }, { source: 'Listolier', target: 'Tholomyes', value: 4 }, { source: 'Fameuil', target: 'Tholomyes', value: 4 }, { source: 'Fameuil', target: 'Listolier', value: 4 }, { source: 'Blacheville', target: 'Tholomyes', value: 4 }, { source: 'Blacheville', target: 'Listolier', value: 4 }, { source: 'Blacheville', target: 'Fameuil', value: 4 }, { source: 'Favourite', target: 'Tholomyes', value: 3 }, { source: 'Favourite', target: 'Listolier', value: 3 }, { source: 'Favourite', target: 'Fameuil', value: 3 }, { source: 'Favourite', target: 'Blacheville', value: 4 }, { source: 'Dahlia', target: 'Tholomyes', value: 3 }, { source: 'Dahlia', target: 'Listolier', value: 3 }, { source: 'Dahlia', target: 'Fameuil', value: 3 }, { source: 'Dahlia', target: 'Blacheville', value: 3 }, { source: 'Dahlia', target: 'Favourite', value: 5 }, { source: 'Zephine', target: 'Tholomyes', value: 3 }, { source: 'Zephine', target: 'Listolier', value: 3 }, { source: 'Zephine', target: 'Fameuil', value: 3 }, { source: 'Zephine', target: 'Blacheville', value: 3 }, { source: 'Zephine', target: 'Favourite', value: 4 }, { source: 'Zephine', target: 'Dahlia', value: 4 }, { source: 'Fantine', target: 'Tholomyes', value: 3 }, { source: 'Fantine', target: 'Listolier', value: 3 }, { source: 'Fantine', target: 'Fameuil', value: 3 }, { source: 'Fantine', target: 'Blacheville', value: 3 }, { source: 'Fantine', target: 'Favourite', value: 4 }, { source: 'Fantine', target: 'Dahlia', value: 4 }, { source: 'Fantine', target: 'Zephine', value: 4 }, { source: 'Fantine', target: 'Marguerite', value: 2 }, { source: 'Fantine', target: 'Valjean', value: 9 }, { source: 'Mme.Thenardier', target: 'Fantine', value: 2 }, { source: 'Mme.Thenardier', target: 'Valjean', value: 7 }, { source: 'Thenardier', target: 'Mme.Thenardier', value: 13 }, { source: 'Thenardier', target: 'Fantine', value: 1 }, { source: 'Thenardier', target: 'Valjean', value: 12 }, { source: 'Cosette', target: 'Mme.Thenardier', value: 4 }, { source: 'Cosette', target: 'Valjean', value: 31 }, { source: 'Cosette', target: 'Tholomyes', value: 1 }, { source: 'Cosette', target: 'Thenardier', value: 1 }, { source: 'Javert', target: 'Valjean', value: 17 }, { source: 'Javert', target: 'Fantine', value: 5 }, { source: 'Javert', target: 'Thenardier', value: 5 }, { source: 'Javert', target: 'Mme.Thenardier', value: 1 }, { source: 'Javert', target: 'Cosette', value: 1 }, { source: 'Fauchelevent', target: 'Valjean', value: 8 }, { source: 'Fauchelevent', target: 'Javert', value: 1 }, { source: 'Bamatabois', target: 'Fantine', value: 1 }, { source: 'Bamatabois', target: 'Javert', value: 1 }, { source: 'Bamatabois', target: 'Valjean', value: 2 }, { source: 'Perpetue', target: 'Fantine', value: 1 }, { source: 'Simplice', target: 'Perpetue', value: 2 }, { source: 'Simplice', target: 'Valjean', value: 3 }, { source: 'Simplice', target: 'Fantine', value: 2 }, { source: 'Simplice', target: 'Javert', value: 1 }, { source: 'Scaufflaire', target: 'Valjean', value: 1 }, { source: 'Woman1', target: 'Valjean', value: 2 }, { source: 'Woman1', target: 'Javert', value: 1 }, { source: 'Judge', target: 'Valjean', value: 3 }, { source: 'Judge', target: 'Bamatabois', value: 2 }, { source: 'Champmathieu', target: 'Valjean', value: 3 }, { source: 'Champmathieu', target: 'Judge', value: 3 }, { source: 'Champmathieu', target: 'Bamatabois', value: 2 }, { source: 'Brevet', target: 'Judge', value: 2 }, { source: 'Brevet', target: 'Champmathieu', value: 2 }, { source: 'Brevet', target: 'Valjean', value: 2 }, { source: 'Brevet', target: 'Bamatabois', value: 1 }, { source: 'Chenildieu', target: 'Judge', value: 2 }, { source: 'Chenildieu', target: 'Champmathieu', value: 2 }, { source: 'Chenildieu', target: 'Brevet', value: 2 }, { source: 'Chenildieu', target: 'Valjean', value: 2 }, { source: 'Chenildieu', target: 'Bamatabois', value: 1 }, { source: 'Cochepaille', target: 'Judge', value: 2 }, { source: 'Cochepaille', target: 'Champmathieu', value: 2 }, { source: 'Cochepaille', target: 'Brevet', value: 2 }, { source: 'Cochepaille', target: 'Chenildieu', value: 2 }, { source: 'Cochepaille', target: 'Valjean', value: 2 }, { source: 'Cochepaille', target: 'Bamatabois', value: 1 }, { source: 'Pontmercy', target: 'Thenardier', value: 1 }, { source: 'Boulatruelle', target: 'Thenardier', value: 1 }, { source: 'Eponine', target: 'Mme.Thenardier', value: 5 }, { source: 'Eponine', target: 'Thenardier', value: 1 }, { source: 'Anzelma', target: 'Eponine', value: 1 }, { source: 'Anzelma', target: 'Thenardier', value: 1 }, { source: 'Anzelma', target: 'Mme.Thenardier', value: 1 }, { source: 'Woman2', target: 'Valjean', value: 3 }, { source: 'Woman2', target: 'Cosette', value: 1 }, { source: 'Woman2', target: 'Javert', value: 1 }, { source: 'MotherInnocent', target: 'Fauchelevent', value: 3 }, { source: 'MotherInnocent', target: 'Valjean', value: 1 }, { source: 'Gribier', target: 'Fauchelevent', value: 2 }, { source: 'Mme.Burgon', target: 'Jondrette', value: 1 }, { source: 'Jondrette', target: 'Mme.Burgon', value: 2 }, { source: 'Jondrette', target: 'Valjean', value: 1 }, { source: 'Gavroche', target: 'Mme.Burgon', value: 2 }, { source: 'Gavroche', target: 'Thenardier', value: 1 }, { source: 'Gavroche', target: 'Javert', value: 1 }, { source: 'Gavroche', target: 'Valjean', value: 2 }, { source: 'Gillenormand', target: 'Cosette', value: 3 }, { source: 'Gillenormand', target: 'Valjean', value: 2 }, { source: 'Magnon', target: 'Gillenormand', value: 1 }, { source: 'Magnon', target: 'Mme.Thenardier', value: 1 }, { source: 'Mlle.Gillenormand', target: 'Gillenormand', value: 9 }, { source: 'Mlle.Gillenormand', target: 'Cosette', value: 2 }, { source: 'Mlle.Gillenormand', target: 'Valjean', value: 2 }, { source: 'Mme.Pontmercy', target: 'Mlle.Gillenormand', value: 1 }, { source: 'Mme.Pontmercy', target: 'Pontmercy', value: 1 }, { source: 'Mlle.Vaubois', target: 'Mlle.Gillenormand', value: 1 }, { source: 'Lt.Gillenormand', target: 'Mlle.Gillenormand', value: 2 }, { source: 'Lt.Gillenormand', target: 'Gillenormand', value: 1 }, { source: 'Lt.Gillenormand', target: 'Cosette', value: 1 }, { source: 'Marius', target: 'Mlle.Gillenormand', value: 6 }, { source: 'Marius', target: 'Gillenormand', value: 12 }, { source: 'Marius', target: 'Pontmercy', value: 1 }, { source: 'Marius', target: 'Lt.Gillenormand', value: 1 }, { source: 'Marius', target: 'Cosette', value: 21 }, { source: 'Marius', target: 'Valjean', value: 19 }, { source: 'Marius', target: 'Tholomyes', value: 1 }, { source: 'Marius', target: 'Thenardier', value: 2 }, { source: 'Marius', target: 'Eponine', value: 5 }, { source: 'Marius', target: 'Gavroche', value: 4 }, { source: 'BaronessT', target: 'Gillenormand', value: 1 }, { source: 'BaronessT', target: 'Marius', value: 1 }, { source: 'Mabeuf', target: 'Marius', value: 1 }, { source: 'Mabeuf', target: 'Eponine', value: 1 }, { source: 'Mabeuf', target: 'Gavroche', value: 1 }, { source: 'Enjolras', target: 'Marius', value: 7 }, { source: 'Enjolras', target: 'Gavroche', value: 7 }, { source: 'Enjolras', target: 'Javert', value: 6 }, { source: 'Enjolras', target: 'Mabeuf', value: 1 }, { source: 'Enjolras', target: 'Valjean', value: 4 }, { source: 'Combeferre', target: 'Enjolras', value: 15 }, { source: 'Combeferre', target: 'Marius', value: 5 }, { source: 'Combeferre', target: 'Gavroche', value: 6 }, { source: 'Combeferre', target: 'Mabeuf', value: 2 }, { source: 'Prouvaire', target: 'Gavroche', value: 1 }, { source: 'Prouvaire', target: 'Enjolras', value: 4 }, { source: 'Prouvaire', target: 'Combeferre', value: 2 }, { source: 'Feuilly', target: 'Gavroche', value: 2 }, { source: 'Feuilly', target: 'Enjolras', value: 6 }, { source: 'Feuilly', target: 'Prouvaire', value: 2 }, { source: 'Feuilly', target: 'Combeferre', value: 5 }, { source: 'Feuilly', target: 'Mabeuf', value: 1 }, { source: 'Feuilly', target: 'Marius', value: 1 }, { source: 'Courfeyrac', target: 'Marius', value: 9 }, { source: 'Courfeyrac', target: 'Enjolras', value: 17 }, { source: 'Courfeyrac', target: 'Combeferre', value: 13 }, { source: 'Courfeyrac', target: 'Gavroche', value: 7 }, { source: 'Courfeyrac', target: 'Mabeuf', value: 2 }, { source: 'Courfeyrac', target: 'Eponine', value: 1 }, { source: 'Courfeyrac', target: 'Feuilly', value: 6 }, { source: 'Courfeyrac', target: 'Prouvaire', value: 3 }, { source: 'Bahorel', target: 'Combeferre', value: 5 }, { source: 'Bahorel', target: 'Gavroche', value: 5 }, { source: 'Bahorel', target: 'Courfeyrac', value: 6 }, { source: 'Bahorel', target: 'Mabeuf', value: 2 }, { source: 'Bahorel', target: 'Enjolras', value: 4 }, { source: 'Bahorel', target: 'Feuilly', value: 3 }, { source: 'Bahorel', target: 'Prouvaire', value: 2 }, { source: 'Bahorel', target: 'Marius', value: 1 }, { source: 'Bossuet', target: 'Marius', value: 5 }, { source: 'Bossuet', target: 'Courfeyrac', value: 12 }, { source: 'Bossuet', target: 'Gavroche', value: 5 }, { source: 'Bossuet', target: 'Bahorel', value: 4 }, { source: 'Bossuet', target: 'Enjolras', value: 10 }, { source: 'Bossuet', target: 'Feuilly', value: 6 }, { source: 'Bossuet', target: 'Prouvaire', value: 2 }, { source: 'Bossuet', target: 'Combeferre', value: 9 }, { source: 'Bossuet', target: 'Mabeuf', value: 1 }, { source: 'Bossuet', target: 'Valjean', value: 1 }, { source: 'Joly', target: 'Bahorel', value: 5 }, { source: 'Joly', target: 'Bossuet', value: 7 }, { source: 'Joly', target: 'Gavroche', value: 3 }, { source: 'Joly', target: 'Courfeyrac', value: 5 }, { source: 'Joly', target: 'Enjolras', value: 5 }, { source: 'Joly', target: 'Feuilly', value: 5 }, { source: 'Joly', target: 'Prouvaire', value: 2 }, { source: 'Joly', target: 'Combeferre', value: 5 }, { source: 'Joly', target: 'Mabeuf', value: 1 }, { source: 'Joly', target: 'Marius', value: 2 }, { source: 'Grantaire', target: 'Bossuet', value: 3 }, { source: 'Grantaire', target: 'Enjolras', value: 3 }, { source: 'Grantaire', target: 'Combeferre', value: 1 }, { source: 'Grantaire', target: 'Courfeyrac', value: 2 }, { source: 'Grantaire', target: 'Joly', value: 2 }, { source: 'Grantaire', target: 'Gavroche', value: 1 }, { source: 'Grantaire', target: 'Bahorel', value: 1 }, { source: 'Grantaire', target: 'Feuilly', value: 1 }, { source: 'Grantaire', target: 'Prouvaire', value: 1 }, { source: 'MotherPlutarch', target: 'Mabeuf', value: 3 }, { source: 'Gueulemer', target: 'Thenardier', value: 5 }, { source: 'Gueulemer', target: 'Valjean', value: 1 }, { source: 'Gueulemer', target: 'Mme.Thenardier', value: 1 }, { source: 'Gueulemer', target: 'Javert', value: 1 }, { source: 'Gueulemer', target: 'Gavroche', value: 1 }, { source: 'Gueulemer', target: 'Eponine', value: 1 }, { source: 'Babet', target: 'Thenardier', value: 6 }, { source: 'Babet', target: 'Gueulemer', value: 6 }, { source: 'Babet', target: 'Valjean', value: 1 }, { source: 'Babet', target: 'Mme.Thenardier', value: 1 }, { source: 'Babet', target: 'Javert', value: 2 }, { source: 'Babet', target: 'Gavroche', value: 1 }, { source: 'Babet', target: 'Eponine', value: 1 }, { source: 'Claquesous', target: 'Thenardier', value: 4 }, { source: 'Claquesous', target: 'Babet', value: 4 }, { source: 'Claquesous', target: 'Gueulemer', value: 4 }, { source: 'Claquesous', target: 'Valjean', value: 1 }, { source: 'Claquesous', target: 'Mme.Thenardier', value: 1 }, { source: 'Claquesous', target: 'Javert', value: 1 }, { source: 'Claquesous', target: 'Eponine', value: 1 }, { source: 'Claquesous', target: 'Enjolras', value: 1 }, { source: 'Montparnasse', target: 'Javert', value: 1 }, { source: 'Montparnasse', target: 'Babet', value: 2 }, { source: 'Montparnasse', target: 'Gueulemer', value: 2 }, { source: 'Montparnasse', target: 'Claquesous', value: 2 }, { source: 'Montparnasse', target: 'Valjean', value: 1 }, { source: 'Montparnasse', target: 'Gavroche', value: 1 }, { source: 'Montparnasse', target: 'Eponine', value: 1 }, { source: 'Montparnasse', target: 'Thenardier', value: 1 }, { source: 'Toussaint', target: 'Cosette', value: 2 }, { source: 'Toussaint', target: 'Javert', value: 1 }, { source: 'Toussaint', target: 'Valjean', value: 1 }, { source: 'Child1', target: 'Gavroche', value: 2 }, { source: 'Child2', target: 'Gavroche', value: 2 }, { source: 'Child2', target: 'Child1', value: 3 }, { source: 'Brujon', target: 'Babet', value: 3 }, { source: 'Brujon', target: 'Gueulemer', value: 3 }, { source: 'Brujon', target: 'Thenardier', value: 3 }, { source: 'Brujon', target: 'Gavroche', value: 1 }, { source: 'Brujon', target: 'Eponine', value: 1 }, { source: 'Brujon', target: 'Claquesous', value: 1 }, { source: 'Brujon', target: 'Montparnasse', value: 1 }, { source: 'Mme.Hucheloup', target: 'Bossuet', value: 1 }, { source: 'Mme.Hucheloup', target: 'Joly', value: 1 }, { source: 'Mme.Hucheloup', target: 'Grantaire', value: 1 }, { source: 'Mme.Hucheloup', target: 'Bahorel', value: 1 }, { source: 'Mme.Hucheloup', target: 'Courfeyrac', value: 1 }, { source: 'Mme.Hucheloup', target: 'Gavroche', value: 1 }, { source: 'Mme.Hucheloup', target: 'Enjolras', value: 1 }, ], }, autoFit: 'view', layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, center: [250, 250], ks: 0.1, ksmax: 10, tao: 0.1, mode: 'normal', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], autoResize: true, zoomRange: [0.1, 5], }, { width: 600, height: 400 }, (gui, graph) => { const options = { type: 'force-atlas2', preventOverlap: true, kr: 20, ks: 0.1, ksmax: 10, tao: 0.1, mode: 'normal', kg: 1, barnesHut: false, dissuadeHubs: false, prune: false, }; const optionFolder = gui.addFolder('ForceAtlas2 Layout Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'preventOverlap'); optionFolder.add(options, 'kr', 1, 100, 1); optionFolder.add(options, 'ks', 0.01, 1, 0.01); optionFolder.add(options, 'ksmax', 1, 20, 1); optionFolder.add(options, 'tao', 0.01, 1, 0.01); optionFolder.add(options, 'kg', 0, 10, 0.1); optionFolder.add(options, 'barnesHut'); optionFolder.add(options, 'dissuadeHubs'); optionFolder.add(options, 'prune'); optionFolder.add(options, 'mode', ['normal', 'linlog']); optionFolder.onChange(async ({ property, value }) => { graph.setLayout( Object.assign({}, graph.getLayout(), { [property]: value, }), ); await graph.layout(); }); }, ); ``` ## 基本用法 ```js const graph = new Graph({ layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, center: [250, 250], }, }); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | -------- | ---- | | type | 布局类型,必须为 `force-atlas2` | `force-atlas2` | - | ✓ | | maxIteration | 最大迭代次数 | number | 500 | | | minMovement | 收敛阈值 | number | 0.4 | | | barnesHut | 是否开启四叉树加速,开启后可以提升大规模图的布局性能,但可能会影响布局质量。默认情况下为 undefined,当节点数量大于 250 时它将会被激活。设置为 false 则不会自动被激活 | boolean | - | | | dissuadeHubs | 是否开启 hub 模式。若为 true,相比与出度大的节点,入度大的节点将会有更高的优先级被放置在中心位置 | boolean | false | | | height | 布局高度,默认使用容器高度 | number | - | | | kg | 重力系数,`kg` 越大,布局越聚集在中心 | number | 1 | | | kr | 斥力系数,可用于调整布局的紧凑程度。kr 越大,布局越松散 | number | 5 | | | ks | 控制迭代过程中,节点移动的速度 | number | 0.1 | | | ksmax | 迭代过程中,最大的节点移动的速度上限 | number | 10 | | | mode | 聚类模式,`linlog` 模式下,聚类将更加紧凑 | `normal` \| `linlog` | `normal` | | | nodeSize | 节点大小(直径)。当开启 `preventOverlap` 时,用于计算节点之间的斥力。如果不设置,则使用节点数据中的 size 属性 | Size \| ((node?: Node) => Size) | - | | | nodeSpacing | 节点间距 | number \| ((node?: Node) => number) | - | | | onTick | 每一次迭代的回调函数 | (data: LayoutMapping) => void | - | | | preventOverlap | 是否防止节点重叠。开启后,布局会考虑节点大小,避免节点重叠 | boolean | false | | | prune | 是否开启自动剪枝模式。默认情况下为 undefined,当节点数量大于 100 时它将会被激活。注意,剪枝能够提高收敛速度,但可能会降低图的布局质量。设置为 false 则不会自动被激活 | boolean | - | | | tao | 迭代接近收敛时停止震荡的容忍度 | number | 0.1 | | | width | 布局宽度,默认使用容器宽度 | number | - | | | center | 布局中心点,用于指定重力的中心,格式为 [x, y]。每个节点都会受到一个指向该中心点的重力,重力大小由 `kg` 参数控制。如果不设置,则使用画布中心点 | [number, number] | - | | ## 代码示例 ### 基础用法 ```js import { Graph } from '@antv/g6'; const graph = new Graph({ layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, }, autoFit: 'view', data: { nodes: [ { id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }, { id: 'node6' }, { id: 'node7' }, { id: 'node8' }, { id: 'node9' }, { id: 'node10' }, { id: 'node11' }, { id: 'node12' }, { id: 'node13' }, { id: 'node14' }, { id: 'node15' }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, { source: 'node5', target: 'node6' }, { source: 'node6', target: 'node7' }, { source: 'node7', target: 'node8' }, { source: 'node8', target: 'node9' }, { source: 'node9', target: 'node10' }, { source: 'node10', target: 'node11' }, { source: 'node11', target: 'node12' }, { source: 'node12', target: 'node13' }, { source: 'node13', target: 'node14' }, { source: 'node14', target: 'node15' }, { source: 'node15', target: 'node1' }, { source: 'node1', target: 'node8' }, { source: 'node2', target: 'node9' }, { source: 'node3', target: 'node10' }, { source: 'node4', target: 'node11' }, { source: 'node5', target: 'node12' }, { source: 'node6', target: 'node13' }, { source: 'node7', target: 'node14' }, ], }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }); ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 400, height: 300, layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, }, data: { nodes: [ { id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }, { id: 'node6' }, { id: 'node7' }, { id: 'node8' }, { id: 'node9' }, { id: 'node10' }, { id: 'node11' }, { id: 'node12' }, { id: 'node13' }, { id: 'node14' }, { id: 'node15' }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, { source: 'node5', target: 'node6' }, { source: 'node6', target: 'node7' }, { source: 'node7', target: 'node8' }, { source: 'node8', target: 'node9' }, { source: 'node9', target: 'node10' }, { source: 'node10', target: 'node11' }, { source: 'node11', target: 'node12' }, { source: 'node12', target: 'node13' }, { source: 'node13', target: 'node14' }, { source: 'node14', target: 'node15' }, { source: 'node15', target: 'node1' }, { source: 'node1', target: 'node8' }, { source: 'node2', target: 'node9' }, { source: 'node3', target: 'node10' }, { source: 'node4', target: 'node11' }, { source: 'node5', target: 'node12' }, { source: 'node6', target: 'node13' }, { source: 'node7', target: 'node14' }, ], }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], }); graph.render(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'view', layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, center: [250, 250], }, behaviors: ['zoom-canvas', 'drag-canvas'], autoResize: true, zoomRange: [0.1, 5], }); graph.render(); }); ``` - [ForceAtlas2布局](/zh/examples/layout/force-directed/atlas2/) ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 小地图 Minimap - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Minimap/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Minimap.md - Description: 小地图 Minimap --- title: "小地图 Minimap" description: "小地图 Minimap" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Minimap/" version: "5.1.1" --- ## 概述 Minimap(小地图)的主要作用是为用户提供以缩略图形式展示当前图内容的整体布局,可以快速定位图操作位置。 **⚠️ 需要注意**,Minimap 插件当前不兼容 React Node 渲染机制,在需要使用 Minimap 功能的场景中,建议通过 [内置节点](/zh/manual/element/node/overview/) 或者[自定义节点](/zh/manual/element/node/custom-node/) 实现节点渲染。 ## 使用场景 Minimap(小地图)插件主要适用于以下场景: - 提供全局视野,快速定位区域 - 导航与交互辅助,通过操作小地图可以快速定位到目标位置 ## 基本用法 以下是一个简单的 Minimap 插件初始化示例: ```js const graph = new Graph({ plugins: [ { key: 'minimap', type: 'minimap', size: [240, 160], }, ], }); ``` ## 在线体验 minimap.md ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: Array.from({ length: 50 }).map((_, i) => ({ id: `node-${i}`, x: Math.random() * 500, y: Math.random() * 300, })), edges: Array.from({ length: 100 }).map((_, i) => ({ id: `edge-${i}`, source: `node-${Math.floor(Math.random() * 50)}`, target: `node-${Math.floor(Math.random() * 50)}`, })), }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, layout: { type: 'force' }, behaviors: ['drag-canvas'], plugins: [{ type: 'minimap', key: 'minimap', size: [240, 160], position: 'right-bottom' }], }, { width: 600, height: 300 }, (gui, graph) => { const options = { type: 'minimap', width: 240, height: 160, shape: 'key', padding: 10, position: 'right-bottom', maskStyleBorder: '1px solid #ddd', maskStyleBackground: 'rgba(0, 0, 0, 0.1)', containerStyleBorder: '1px solid #ddd', containerStyleBackground: '#fff', delay: 128, }; const optionFolder = gui.addFolder('Minimap Options'); optionFolder.add(options, 'type').disable(true); optionFolder .add(options, 'width', 100, 500, 1) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', size: [value, options.height], }); graph.render(); }); optionFolder .add(options, 'height', 100, 500, 1) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', size: [options.width, value], }); graph.render(); }); optionFolder .add(options, 'shape', ['key']) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', shape: value, }); graph.render(); }); optionFolder .add(options, 'padding', 0, 50, 1) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', padding: value, }); graph.render(); }); optionFolder .add(options, 'position', ['right-bottom', 'left-bottom', 'right-top', 'left-top']) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', position: value, }); graph.render(); }); optionFolder .addColor(options, 'maskStyleBorder') .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', maskStyle: { ...options.maskStyle, border: value }, }); graph.render(); }); optionFolder .addColor(options, 'maskStyleBackground') .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', maskStyle: { ...options.maskStyle, background: value }, }); graph.render(); }); optionFolder .addColor(options, 'containerStyleBorder') .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', containerStyle: { ...options.containerStyle, border: value }, }); graph.render(); }); optionFolder .addColor(options, 'containerStyleBackground') .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', containerStyle: { ...options.containerStyle, background: value }, }); graph.render(); }); optionFolder .add(options, 'delay', 0, 500, 1) .listen() .onChange((value) => { graph.updatePlugin({ key: 'minimap', delay: value, }); graph.render(); }); // Update the maskStyle and containerStyle in the options object Object.defineProperty(options, 'maskStyle', { get: () => ({ border: options.maskStyleBorder, background: options.maskStyleBackground, }), set: (value) => { options.maskStyleBorder = value.border; options.maskStyleBackground = value.background; }, }); Object.defineProperty(options, 'containerStyle', { get: () => ({ border: options.containerStyleBorder, background: options.containerStyleBackground, }), set: (value) => { options.containerStyleBorder = value.border; options.containerStyleBackground = value.background; }, }); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | -------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | ---- | | type | 插件类型 | string | `minimap` | ✓ | | key | 插件唯一标识符,用于后续更新 | string | - | | | className | 缩略图画布类名,传入外置容器时不生效 | string | | | | container | 缩略图挂载的容器,无则挂载到 Graph 所在容器 | HTMLElement \| string | | | | containerStyle | 缩略图的容器样式,传入外置容器时不生效 | Partial\<CSSStyleDeclaration\> | | | | delay | 延迟更新时间(毫秒),用于性能优化 | number | 128 | | | filter | 过滤器,用于过滤不必显示的元素 | (id: string, elementType: `node` \| `edge` \| `combo`) => boolean | | | | maskStyle | 遮罩的样式 | Partial\<CSSStyleDeclaration\> | | | | padding | 内边距 | number \| number[] | 10 | | | position | 缩略图相对于画布的位置 | [number, number] \| `left` \| `right` \| `top` \| `bottom` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` \| `center` | `right-bottom` | | | renderer | 渲染器,默认使用 Canvas 渲染器 | IRenderer | | | | shape | 元素缩略图形的生成方法 | `key` \| ((id: string, elementType: `node` \| `edge` \| `combo`, element: DisplayObject) => DisplayObject) | `key` | | | size | 宽度和高度 | [number, number] | [240, 160] | | ### containerStyle 设置缩略图的容器样式,传入外置容器时不生效。继承了所有 CSS 样式属性(CSSStyleDeclaration),你可以使用任何合法的 CSS 属性来配置缩略图容器的样式。 以下是一些常用配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------ | ------------ | ------ | ---------------- | ---- | | border | 容器边框样式 | string | `1px solid #ddd` | ✓ | | background | 容器背景颜色 | string | `#fff` | ✓ | | borderRadius | 容器圆角大小 | string | - | | | boxShadow | 容器阴影效果 | string | - | | | padding | 容器内边距 | string | - | | | margin | 容器外边距 | string | - | | | opacity | 透明度 | string | - | | ### maskStyle 指定遮罩的样式。继承了所有 CSS 样式属性(CSSStyleDeclaration),你可以使用任何合法的 CSS 属性来配置缩略图容器的样式。 以下是一些常用配置: | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------ | ------------ | ------ | -------------------- | ---- | | border | 容器边框样式 | string | `1px solid #ddd` | ✓ | | background | 容器背景颜色 | string | `rgba(0, 0, 0, 0.1)` | ✓ | | borderRadius | 容器圆角大小 | string | - | - | | boxShadow | 容器阴影效果 | string | - | - | | padding | 容器内边距 | string | - | - | | margin | 容器外边距 | string | - | - | | opacity | 透明度 | string | - | - | ### position 缩略图相对于画布的位置,缩略图位置配置支持数组形式和预设值形式。 - 数组形式 [number, number] 表示相对位置,取值范围为 0~1。举例:[0, 0] 代表画布左上角,[1, 1] 代表画布右下角。 - 预设值形式用于设定缩略图所在画布固定方位,可选值有:`left` \| `right` \| `top` \| `bottom` \| `left-top` \| `left-bottom` \| `right-top` \| `right-bottom` \| `top-left` \| `top-right` \| `bottom-left` \| `bottom-right` \| `center` ```js const graph = new Graph({ plugins:[ { ... // 其他配置 key: 'minimap', type: 'minimap', position: 'right-bottom' // 这里进行修改minimap所在位置 } ] }) ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: Array.from({ length: 50 }).map((_, i) => ({ id: `node-${i}`, x: Math.random() * 500, y: Math.random() * 300, })), edges: Array.from({ length: 100 }).map((_, i) => ({ id: `edge-${i}`, source: `node-${Math.floor(Math.random() * 50)}`, target: `node-${Math.floor(Math.random() * 50)}`, })), }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, layout: { type: 'force' }, behaviors: ['drag-canvas'], plugins: [{ type: 'minimap', key: 'minimap', size: [240, 160], position: 'right-bottom' }], }); graph.render(); ``` ### size 设置小地图的宽度和高度,默认值为 [240, 160] ```js const graph = new Graph({ plugins:[ { ... // 其他配置 key: 'minimap', type: 'minimap', size: [200, 120] // minimap的宽度和高度的设置 } ] }) ``` 效果如下: ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 600, height: 300, data: { nodes: Array.from({ length: 50 }).map((_, i) => ({ id: `node-${i}`, x: Math.random() * 500, y: Math.random() * 300, })), edges: Array.from({ length: 100 }).map((_, i) => ({ id: `edge-${i}`, source: `node-${Math.floor(Math.random() * 50)}`, target: `node-${Math.floor(Math.random() * 50)}`, })), }, node: { style: { fill: '#7e3feb' } }, edge: { style: { stroke: '#8b9baf' } }, layout: { type: 'force' }, behaviors: ['drag-canvas'], plugins: [{ type: 'minimap', key: 'minimap', size: [200, 120], position: 'right-bottom' }], }); graph.render(); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: Array.from({ length: 20 }).map((_, i) => ({ id: `node${i}` })) }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], plugins: [ { type: 'minimap', size: [240, 160], }, ], node: { palette: 'spectral', }, layout: { type: 'circular', }, autoFit: 'view', }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 优化视口变换 OptimizeViewportTransform - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/OptimizeViewportTransform/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/OptimizeViewportTransform.md - Description: 优化视口变换 OptimizeViewportTransform --- title: "优化视口变换 OptimizeViewportTransform" description: "优化视口变换 OptimizeViewportTransform" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/OptimizeViewportTransform/" version: "5.1.1" --- ## 概述 OptimizeViewportTransform 是 G6 中用于提升大规模图表交互性能的内置交互。 该交互通过实现**选择性渲染策略**,在视口变换过程中(即用户进行拖拽、缩放、滚动等操作时)临时隐藏非关键视觉元素,从而显著降低渲染计算负载,提高帧率和响应速度。当视口变换操作结束后,系统会在设定的延迟时间后自动恢复所有元素的可见性,确保完整的视觉呈现。 此交互基于 [事件系统](/zh/api/event/) 实现,通过监听 `GraphEvent.BEFORE_TRANSFORM` 和 `GraphEvent.AFTER_TRANSFORM` 事件,精确捕捉视口变换的开始和结束时机,进而执行元素可见性的动态控制。因此,必须与视口操作类交互(如 `drag-canvas`、`zoom-canvas` 或 `scroll-canvas`)配合使用才能发挥作用。 ## 使用场景 这一交互主要用于: - 大规模图表(上千节点/边)的流畅交互 - 性能敏感的应用场景 ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['optimize-viewport-transform'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'optimize-viewport-transform', key: 'optimize-viewport-transform-1', // 为交互指定标识符,方便动态更新 debounce: 300, // 设置更长的防抖时间 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | -------- | ------------------------------------------------------------- | -------------------------------------- | ----------------------------- | ---- | | type | 交互类型名称 | string | `optimize-viewport-transform` | ✓ | | enable | 是否启用该交互 | boolean \| ((event: Event) => boolean) | true | | | debounce | 操作结束后多长时间恢复显示所有元素(毫秒) | number | 200 | | | shapes | 指定在操作画布过程中始终保持可见的图形元素,[配置项](#shapes) | function | `(type) => type === 'node'` | | ### Shapes `shapes` 用于指定在画布操作过程中需要保持可见的图形元素。默认情况下,节点始终可见,而边和组合在操作画布时会被临时隐藏以提升性能。 ```javascript { shapes: (type, shape) => { // 根据元素类型和图形对象动态决定是否保持可见 if (type === 'node') return true; // 所有节点保持可见 if (type === 'edge' && shape.get('importante')) return true; // 重要的边保持可见 return false; // 其他图形隐藏 }; } ``` [示例](#保持特定元素可见) ## 代码示例 ### 基础优化功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['drag-canvas', 'zoom-canvas', 'optimize-viewport-transform'], }); ``` ### 自定义防抖时间 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ 'drag-canvas', 'zoom-canvas', { type: 'optimize-viewport-transform', debounce: 500, // 设置更长的防抖时间,在操作停止后0.5秒才恢复显示所有元素 }, ], }); ``` ### 保持特定元素可见 ```javascript const graph = new Graph({ // 其他配置... node: { style: { labelText: 'Drag Canvas!', }, }, behaviors: [ 'drag-canvas', 'zoom-canvas', { type: 'optimize-viewport-transform', shapes: (type, shape) => { if (type === 'node' && shape.className === 'key') return true; return false; }, }, ], }); ``` > 👇 试试拖拽一下画布,看看效果吧 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 200, height: 200, data: { nodes: [{ id: 'node-1', style: { x: 100, y: 100 } }], }, node: { style: { labelText: 'Drag Canvas!', }, }, behaviors: [ 'drag-canvas', { type: 'optimize-viewport-transform', shapes: (type, shape) => { if (type === 'node' && shape.className === 'key') return true; return false; }, }, ], }); graph.render(); ``` ### 根据图表元素数量动态启用/禁用优化 可以根据图表元素数量动态决定是否启用优化: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ 'drag-canvas', 'zoom-canvas', function () { // 超出500个元素时启用优化 const enable = graph.getNodeData().length + graph.getEdgeData().length > 500; return { type: 'optimize-viewport-transform', key: 'optimize-behavior', enable, }; }, ], }); ``` ## 常见问题 ### 1. 什么情况下应该使用此交互? 当图表包含大量节点和边(通常超过500个元素)时,使用此交互可以显著提升操作流畅度。在性能要求高或硬件性能有限的环境中尤其有用。 ## 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, node: { style: { labelText: (datum) => datum.id, }, }, behaviors: ['zoom-canvas', 'drag-canvas', 'scroll-canvas', 'optimize-viewport-transform'], }); graph.render(); ``` #### 使用 React 定义节点 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/react-node/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/react-node.md - Description: 使用 React 定义节点 --- title: "使用 React 定义节点" description: "使用 React 定义节点" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/react-node/" version: "5.1.1" --- 在 G6 中,自定义节点通常需要操作 DOM 或 Canvas 元素,但借助 `@antv/g6-extension-react` 一方生态库,可以直接使用 React 组件作为节点内容,提升开发效率与可维护性。 ## 自定义节点方案选择 ### G6 节点 ✅ **推荐场景:** - 节点只是简单的几何图形 - 需要高效渲染超过 2,000 个节点的场景 - 需要直接操作图形实例进行精细控制 > 有关如何使用 Canvas 图形自定义节点的详细信息,请参阅 [自定义节点](/zh/manual/element/node/custom-node/) 文档 ### React Node ✅ **推荐场景:** - 需要集成 Ant Design 等 UI 库的业务系统 - 节点包含表单输入、状态切换等交互逻辑 - 已有 React 设计系统需要复用的场景 ## 快速入门 ### 环境准备 在开始之前,请确保您已经: - **安装 React 项目**:确保已安装并创建 React 项目。 - **React 版本要求**:确保使用的 React 版本 >=16.8.0。 ### 安装依赖 要使用 `@antv/g6-extension-react`,请运行以下命令: :::code-group ```bash [npm] npm install @antv/g6-extension-react ``` ```bash [yarn] yarn add @antv/g6-extension-react ``` ```bash [pnpm] pnpm add @antv/g6-extension-react ``` ::: ### 组件集成 #### 1. 注册 React 节点类型 通过扩展机制注册 React 节点类型: ```jsx import { ExtensionCategory, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; register(ExtensionCategory.NODE, 'react-node', ReactNode); ``` `register` 方法需要三个参数: - 扩展类别:`ExtensionCategory.NODE` 表示这是一个节点类型 - 类型名称:`react-node` 是我们给这个自定义节点起的名字,后续会在配置中使用 - 类定义:ReactNode 是 `@antv/g6-extension-react` 导出的实现类 #### 2. 定义业务组件 定义一个简单的 React 组件作为节点的内容: ```jsx const MyReactNode = () => { return
node
; }; ``` #### 3. 使用组件 在图配置中使用自定义的 React 节点。通过在图配置中指定节点类型和样式,来使用自定义的 React 组件。 - `type`:指定节点类型为 `react-node` (使用与注册时起的名字) - `style.component`:定义节点的 React 组件内容 ```jsx const graph = new Graph({ node: { type: 'react-node', style: { component: () => , }, }, }); graph.render(); ``` ## 高级功能 ### 状态管理 在复杂图可视化场景中,节点需要动态响应交互状态。我们提供两种互补的状态管理方案: #### 响应内置交互状态 G6 提供内置的交互状态管理状态,如 `hover-activate` 和 `click-select`。可以通过节点数据中的 `data.states` 字段获取当前节点状态,并根据状态调整节点样式。 **示例**:在节点被 hover 时改变背景颜色。 ```jsx import { ExtensionCategory, register, Graph } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; register(ExtensionCategory.NODE, 'react-node', ReactNode); const StatefulNode = ({ data }) => { const isActive = data.states?.includes('active'); return (
{data.data.label}
); }; const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 200 }, data: { label: 'node1' } }, { id: 'node2', style: { x: 300, y: 200 }, data: { label: 'node2' } }, ], }, node: { type: 'react-node', style: { component: (data) => , }, }, behaviors: ['hover-activate'], }); graph.render(); ``` #### 自定义业务状态 当需要管理业务相关状态(如审批状态、风险等级)时,可通过扩展节点数据实现: **示例**:通过 data 添加 `selected` 变量,实现节点选中和取消选中的样式变化。 ```jsx import { ExtensionCategory, register, Graph } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; register(ExtensionCategory.NODE, 'react-node', ReactNode); const MyReactNode = ({ data, graph }) => { const handleClick = () => { graph.updateNodeData([{ id: data.id, data: { selected: !data.data.selected } }]); graph.draw(); }; return (
Node
); }; const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 }, data: { selected: true }, }, ], }, node: { type: 'react-node', style: { component: (data) => , }, }, }); graph.render(); ``` ### 事件交互 实现节点与图实例的双向通信,使节点和图实例可以相互更新。 **示例**:通过自定义节点操作图数据,并重新渲染图形。 ```jsx const IDCardNode = ({ id, selected, graph }) => { const handleSelect = () => { graph.updateNodeData([{ id, data: { selected: true } }]); graph.draw(); }; return { const url = event.target.value; onChange?.(url); }} /> ); }; export const ReactNodeDemo = () => { const containerRef = useRef(); useEffect(() => { const graph = new Graph({ container: containerRef.current, data: { nodes: [ { id: 'local-server-1', data: { status: 'success', type: 'local', url: 'http://localhost:3000' }, style: { x: 50, y: 50 }, }, { id: 'remote-server-1', data: { status: 'warning', type: 'remote' }, style: { x: 350, y: 50 }, }, ], edges: [{ source: 'local-server-1', target: 'remote-server-1' }], }, node: { type: 'react', style: { size: [240, 100], component: (data) => , }, }, behaviors: ['drag-element', 'zoom-canvas', 'drag-canvas'], }); graph.render(); }, []); return
; }; const root = createRoot(document.getElementById('container')); root.render(); ```
```ts import { UserOutlined } from '@ant-design/icons'; import { ExtensionCategory, Graph, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; import { Avatar, Button, Card, Descriptions, Select, Space, Typography } from 'antd'; import React, { useEffect, useRef } from 'react'; import { createRoot } from 'react-dom/client'; const { Title, Text } = Typography; const { Option } = Select; register(ExtensionCategory.NODE, 'react-node', ReactNode); const IDCardNode = ({ id, data }) => { const { name, idNumber, address, expanded, selected, graph } = data; const toggleExpand = (e) => { e.stopPropagation(); graph.updateNodeData([ { id, data: { expanded: !expanded }, }, ]); graph.render(); }; const handleSelect = (value) => { graph.updateNodeData([ { id, data: { selected: value !== 0 }, }, ]); if (value === 2) { // 获取与当前节点相连的所有节点 const connectedNodes = graph.getNeighborNodesData(id); connectedNodes.forEach((node) => { graph.updateNodeData([ { id: node.id, data: { selected: true }, }, ]); }); } graph.render(); }; const CardTitle = (
} /> {name}
); return ( {expanded ? ( {idNumber} {address} ) : ( IDCard Information )} ); }; // 定义 Graph 数据 const data = { nodes: [ { id: 'node1', data: { name: 'Alice', idNumber: 'IDUSAASD2131734', address: '1234 Broadway, Apt 5B, New York, NY 10001', expanded: false, // 初始状态为收缩 selected: false, // 初始状态为未选中 selectedOption: 1, // 初始选择本节点 }, style: { x: 50, y: 50 }, }, { id: 'node2', data: { name: 'Bob', idNumber: 'IDUSAASD1431920', address: '3030 Chestnut St, Philadelphia, PA 19104', expanded: false, // 初始状态为收缩 selected: false, // 初始状态为未选中 selectedOption: 0, // 初始不选择 }, style: { x: 700, y: 100 }, }, { id: 'node3', data: { name: 'Charlie', idNumber: 'IDUSAASD1431921', address: '4040 Elm St, Chicago, IL 60611', expanded: false, selected: true, selectedOption: 0, }, }, { id: 'node4', data: { name: 'David', idNumber: 'IDUSAASD1431922', address: '5050 Oak St, Houston, TX 77002', expanded: false, selected: false, selectedOption: 0, }, }, { id: 'node5', data: { name: 'Eve', idNumber: 'IDUSAASD1431923', address: '6060 Pine St, Phoenix, AZ 85001', expanded: false, selected: false, selectedOption: 0, }, }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }; export const ReactNodeDemo = () => { const containerRef = useRef(); const graphRef = useRef(null); useEffect(() => { // 创建 Graph 实例 const graph = new Graph({ autoFit: 'view', container: containerRef.current, data, node: { type: 'react-node', style: { size: (datum) => (datum.data.expanded ? [340, 236] : [340, 105]), // 调整大小以适应内容 component: (data) => , }, }, behaviors: ['drag-element', 'zoom-canvas', 'drag-canvas'], layout: { type: 'snake', cols: 2, rowGap: 100, colGap: 220, }, }); // 渲染 Graph graph.render(); // 保存 graph 实例 graphRef.current = graph; return () => { graph.destroy(); }; }, []); return
; }; // 渲染 React 组件到 DOM const root = createRoot(document.getElementById('container')); root.render(); ``` #### 常见问题 - Canonical page: https://g6.antv.antgroup.com/zh/manual/faq/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/faq.md - Description: 常见问题 --- title: "常见问题" description: "常见问题" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/faq/" version: "5.1.1" --- ### Extension 和 Plugin 有什么区别? `Extension` 是 G6 中的一个概念,是所有可注册内容的统称,包含元素、交互、布局、插件等。 `Plugin` 是 G6 提供的灵活扩展机制,是一种特殊的 `Extension`。 ### 设置文本超出省略 以 label 为例,设置 `labelWordWrap` 和 `labelWordWrapWidth` 即可实现文本超出省略。 ```typescript {3-4} { labelText: 'This is a long text', labelWordWrap: true, labelWordWrapWidth: 50, } ``` ### 按键不生效 一些插件或交互支持配置触发按键,请使用标准按键名:如 `Control`, `Shift`, `Alt`, `Meta`,以及字母、数字、符号等。 ### 更新数据后画布不更新 请确保数据更新后调用 `graph.draw()` 或者 `graph.render()` 更新画布。 > G6 对于多次数据更新,会在 `draw` 或 `render` 后合并差异并统一更新画布,以提高性能。 ### 交互有冲突如何解决 当多个交互之间存在冲突时,你可以设置交互的启用时机来避免多个交互被同时触发。 以 `drag-canvas` 和 `brush-select` 为例,如果直接配置这两个交互,当指针在画布上进行拖拽时,会导致交互异常。可以设置为在按下 `shift` 键时禁用 `drag-canvas` 交互。 ```typescript {4} behaviors: [ { type: 'drag-canvas', enable: (event) => event.shiftKey === false, }, { type: 'brush-select', }, ]; ``` 此时,当按下 `shift` 键时,`drag-canvas` 交互会被禁用,`brush-select` 交互会不会受到影响。 ### draw 和 render 的区别 `draw` 和 `render` 都会执行绘制操作,但 `render` 会在 `draw` 的基础上额外进行**布局**、**视图自适应**操作。 可以简单理解为:`render` = `draw` + `layout` + `fitView`/`fitCenter`。 ### 数据中的样式不生效 原因一:被样式映射中的样式覆盖 ```typescript {5} { data: [{ id: 'node-1', style: { fill: 'orange' } }], node: { style: { fill: 'pink', // 无论数据中的样式如何,都会被这里的样式覆盖 } } } ``` 解决方式:使用回调方法,优先从数据中获取样式以提高数据优先级 ```typescript {5} { node: { style: (data) => { return { fill: data.style?.fill || 'pink', }; }; } } ``` ### 画布中出现残影 在使用 Canvas 渲染器进行绘制时,可能会出现残影现象,这些图形被称为“脏矩形”。该现象出现的原因是底层渲染引擎为了提高性能,每次绘制时只会绘制发生变化的部分,而不会清空整个画布。 但是,当画布中的图形发生变化时,可能会出现部分图形未被正确清除的情况,从而导致残影现象。 可以通过以下方式解决: 1. 使用 SVG 或 WebGL 渲染器; 2. 检查节点中的图形样式中是否存在非法值,例如 null、NaN 等; 3. 尽量使用整数作为数值型的样式值,例如 r、width、height、fontSize 等; ### 使用原生 JavaScript 对象数据 请避免使用 Vue 响应式数据、Immer.js 等包装过的对象作为 G6 的数据源,因为这些对象会在内部进行深度监听,甚至冻结数据对象,导致 G6 无法正常操作数据。 ### G6 项目启动在编译时警告类型映射指向不存在路径 ```shell WARNING in ./node_modules/@antv/util/esm/path/util/segment-cubic-factory.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-cubic-factory.ts' file: Error: ENOENT: no such file or directory, open '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-cubic-factory.ts' WARNING in ./node_modules/@antv/util/esm/path/util/segment-line-factory.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-line-factory.ts' file: Error: ENOENT: no such file or directory, open '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-line-factory.ts' WARNING in ./node_modules/@antv/util/esm/path/util/segment-quad-factory.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-quad-factory.ts' file: Error: ENOENT: no such file or directory, open '/Users/xxx/workspace/antv-g6-learn/node_modules/@antv/util/esm/path/util/src/path/util/segment-quad-factory.ts' ``` > 解释: [@antv/util](https://github.com/antvis/util) 是 AntV 底层依赖的工具库。 从上面部分警告信息中我们可以得知是 G6 依赖的 `@antv/util` 工具库的类型声明文件存在问题,**该警告不影响项目正常运行**。 该信息只会在 TypeScript 项目中出现,关闭办法如下: 1. 关闭TypeScript 的sourcemap源码映射 在项目根目录下创建`.env`文件,并添加以下内容: ```text GENERATE_SOURCEMAP=false ``` 2. 单独禁用指定模块的源码映射 直接禁用sourcemap映射的方式过于简单粗暴,对于部分可能有调试需求的开发者不太友好,所以也可以通过在构建工具单独配置,单独禁用这些特定模块的源码映射。 a. webpack配置 ```javascript module.exports = { // ...其他配置 module: { rules: [ { test: /node_modules\/@antv\/util\/esm\/path\/util\/.+\.js$/, use: ['source-map-loader'], enforce: 'pre', }, ], }, ignoreWarnings: [/Failed to parse source map/], }; ``` b. vite配置 ```javascript import { defineConfig } from 'vite'; export default defineConfig({ build: { rollupOptions: { onwarn(warning, warn) { // 忽略特定模块的警告 if (warning.code === 'MODULE_LEVEL_DIRECTIVE' && warning.message.includes('@antv/util')) { return; } // 对于其他警告,使用默认的警告处理 warn(warning); }, }, }, }); ``` ### 手动配置色板颜色不生效 > 在 v5 中内置颜色有:export type BuiltInPalette = 'spectral' | 'oranges' | 'greens' | 'blues'; 解决办法如下: ```typescript {10} const graph = new Graph({ container: '#ID', width: number, height: number, data, node: { palette: { field: 'color', // right color: ['red', 'green', 'blue'], // error // color: 'red' }, }, }); ``` ### grid-line 插件不生效 > 在 v5 中内置插件有`bubble-sets` `edge-filter-lens` `grid-line` `background` `contextmenu` `fisheye` `fullscreen` `history` `hull` `legend` `minimap` `snapline` `timebar` `toolbar` `tooltip` >`watermark`. [具体参考](https://github.com/antvis/G6/blob/6e2355020c20b3a1e2e5ca0e0ee97aeb81f932b3/packages/g6/src/registry/build-in.ts#L189) 实际原因: `graph`实例的父容器`
`本身没有设置高度,G6 Graph图 可能无法正确计算出合适的大小。**如果要启用`grid-line`画布插件,需要给父元素 div 设置宽高,在 graph 配置中是无效的**。 ### v5无法使用树图布局 统一使用`new Graph({xxx})`。 > 在 v5 中内置布局有`antv-dagre` `combo-combined` `compact-box` `force-atlas2` `circular` `concentric` `d3-force` `dagre` `dendrogram` `force` `fruchterman` `grid` `indented` `mds` `mindmap` `radial` `random`. [具体参考](https://github.com/antvis/G6/blob/6e2355020c20b3a1e2e5ca0e0ee97aeb81f932b3/packages/g6/src/registry/build-in.ts#L147) v5合并了图和树图,不再通过实例化`G6.TreeGraph`创建树图布局,并且移除该方式。具体参考[特性-合并图与树图](/zh/manual/whats-new/feature/#🌲-合并图与树图) ### edge 没有连接在 node 的边缘中心 配置[portLinkToCenter](/zh/manual/element/node/BaseNode/#portlinktocenter)为 `true`。 ```typescript {6} const graph = new Graph({ container: xxx, node: { type: 'rect', style: { portLinkToCenter: true, }, }, edge: { type: 'xxx', }, }); ``` ### 如何根据label内容长度动态设置node宽度 参考方案:[#6347](https://github.com/antvis/G6/pull/6347#issuecomment-2357515570) ```typescript const measureTextWidth = memoize( (text: string, font: any = {}): TextMetrics => { const { fontSize, fontFamily = 'sans-serif', fontWeight, fontStyle, fontVariant } = font; const ctx = getCanvasContext(); // @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/font ctx.font = [fontStyle, fontWeight, fontVariant, `${fontSize}px`, fontFamily].join(' '); return ctx.measureText(isString(text) ? text : '').width; }, (text: string, font = {}) => [text, ...values(font)].join(''), ); const graph = new G6.Graph({ node: { style: { size: d => [measureTextWidth(d.label, {...}) , xxx] }, } }) ``` ### NodeEvent节点事件对象类型不齐全问题 可以手动指定`IPointerEvent`类型。具体参考[#6346](https://github.com/antvis/G6/issues/6346) ```typescript {4} import { NodeEvent } from '@antv/g6'; import type { IPointerEvent } from '@antv/g6'; graph.on(NodeEvent.CLICK, (event: IPointerEvent) => { // handler }); ``` ### 解除节点所在组合 更新节点数据,`combo` 值设置为 `null`。 ```typescript graph.updateNodeData([{ id: 'node-id', combo: null }]); ``` #### Force 力导向布局 - Canonical page: https://g6.antv.antgroup.com/zh/manual/layout/ForceLayout/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/layout/ForceLayout.md - Description: Force 力导向布局 --- title: "Force 力导向布局" description: "Force 力导向布局" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/layout/ForceLayout/" version: "5.1.1" --- ## 概述 力导向布局是一种基于物理模拟的图布局算法,它通过模拟节点间的引力和斥力来确定节点的位置。这种布局方式特别适合展示复杂的关系网络,如社交网络、知识图谱等。 力导向布局会自动计算并调整节点位置,使得相连的节点保持适当的距离,同时尽量减少边的交叉。布局过程中会模拟物理系统,节点会像带电粒子一样相互排斥,边则像弹簧一样连接节点。 力导向布局的主要特点包括: 1. **自动排列**:不需要手动设置节点位置,系统会自动找到合适的位置 2. **实时调整**:当你拖动某个节点时,其他节点会实时跟随调整位置 3. **灵活配置**: - 可以调整节点间的吸引力和排斥力 - 可以设置边的长度 - 可以防止节点重叠 4. **动画效果**:节点移动时会有平滑的动画,让变化更自然 力导向布局示例 ## 核心概念 ### Force 力导向布局基本原理 力导向布局是一种基于物理模拟的图布局算法,它将图中的节点和边模拟为物理系统: - 节点被视为物理粒子 - 边被视为弹簧 - 整个系统通过物理模拟达到能量最低状态 ### 核心力详解 #### 斥力(Node Repulsion) - **物理模型**:库伦定律(Coulomb's Law) - **作用**:防止节点重叠,让节点分布更均匀,其中 `factor` 和 `coulombDisScale` 控制斥力的总体强度和范围。 - **公式**: 斥力 - k: 斥力系数(`factor` / `coulombDisScale²`) - q1,q2: 节点强度(`nodeStrength`) - r: 节点间距离 #### 边拉力(Edge Attraction) - **物理模型**:胡克定律(Hooke's Law) - **作用**:模拟边的拉力,使节点沿着边的方向移动,其中 `edgeStrength` 和 `linkDistance` 控制边的“硬度”和长度。 - **公式**: 边拉力 - ka: 边拉力强度(`edgeStrength`) - L: 边的长度(`linkDistance`) - r: 实际边长度 #### 向心力(Gravity) - **物理模型**:牛顿万有引力定律(Newton's Universal Law of Gravitational) - **作用**:使节点向画布中心或者聚类中心聚集,其中 `gravity` 和 `center` 控制重力强度和中心点位置 - **公式**: 向心力 - G: 万有引力常数(`gravity`) - xc: 中心点坐标(`center`) - mass: 节点质量(`nodeSize`) #### 三种力的相互作用 - **物理模型**:力的相互作用,产生加速度 - **作用**:斥力、边拉力、向心力共同作用,通过加速度叠加影响节点运动,最终达到能量最低状态。 - **公式**: 力的相互作用 ### 物理系统 #### 节点运动速度公式 - **公式**: 节点运动速度公式 - v: 速度 - a: 加速度 - dt: 时间步长(`interval`) - damping: 阻尼系数(`damping`) - **作用**: 1. 控制节点移动的稳定性 2. 阻尼系数防止系统震荡 3. 时间步长影响每次迭代的位移 #### 节点位置公式 - **公式**: 节点位置公式 - x: 节点位置 - v: 节点速度 - dt: 时间步长(`interval`) - **作用**: 1. 根据速度更新节点位置 2. 确保运动连续性 3. 通过 `preventOverlap` 防止节点重叠 #### 聚类中心计算 - **公式**: 聚类中心计算 - n: 聚类内节点数量 - (xi​,yi​): 每个节点的位置 - **作用**: 1. 计算聚类中心 2. 向心力将节点拉向所属聚类中心 3. 聚类中心可动态变化 #### 聚类强度计算 - **公式**: 聚类强度计算 - s: 聚类强度(`clusterNodeStrength`) - xc​: 聚类中心 - **作用**: 1. 控制聚类的紧密程度 2. 聚类强度越大,聚类越紧凑 3. 可根据节点属性动态调整 #### 质量对力的影响 - **公式**: 质量对力的影响 - a: 加速度 - F: 力(斥力、边拉力、向心力) - mass: 节点质量 - **作用**: 1. 质量大的节点移动较小 2. 质量小的节点移动较大 3. 通过 `getMass` 可自定义质量计算 #### 能量计算 - **公式**: 能量计算 - m: 节点质量 - v: 节点速度 - **作用**: 1. 监控布局收敛情况 2. 能量趋近于零时系统趋于稳定 #### 系统收敛条件 - **公式**: 系统收敛条件 - **作用**: 1. 控制迭代次数 2. 移动量小于阈值时停止 3. 通过 `distanceThresholdMode` 可选择平均值、最大值或最小值 ### 力相互作用图 力作用模拟图 ## 配置项 根据上述力导向布局的物理特性,有以下配置项: ### 基础配置 | 属性 | 描述 | 默认值 | 必选 | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ---- | | type | 布局类型 | `force` | ✓ | | dimensions | 布局维度,2表示2D布局,3表示3D布局 | 2 | | | width | 布局宽度 | 画布宽度 | | | height | 布局高度 | 画布高度 | | | center | 布局的中心点 | 图中心 | | | maxIteration | 最大迭代次数,若为 0 则将自动调整 | 0 | | | minMovement | 当平均移动距离小于0.4时停止迭代 | 0.4 | | | distanceThresholdMode | 移动距离的计算模式:mean: 平均移动距离小于 `minMovement` 时停止迭代;max: 最大移动距离小于时 `minMovement` 时停止迭代;min: 最小移动距离小于时 `minMovement` | `mean` | | | maxDistance | 最大距离 | | | ### 力相关配置 #### 斥力配置 | 属性 | 描述 | 默认值 | 必选 | | --------------- | ------------------------------------------------------------------ | ------ | ---- | | nodeStrength | 节点作用力,正数代表节点之间的引力作用,负数代表节点之间的斥力作用 | 1000 | | | factor | 斥力系数,数值越大,斥力越大 | 1 | | | coulombDisScale | 库伦系数,斥力的一个系数,数字越大,节点之间的斥力越大 | 0.005 | | #### 边拉力配置 | 属性 | 描述 | 默认值 | 必选 | | ------------ | ------------------------------------------------------------------ | ------ | ---- | | edgeStrength | 边的作用力(引力)大小,固定作用力或回调函数动态返回不同边的作用力 | 500 | | | linkDistance | 边的长度,固定长度或回调函数动态返回不同边的长度 | 200 | | #### 向心力配置 | 属性 | 描述 | 默认值 | 必选 | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | ---- | | gravity | 向中心力大小,指所有节点被吸引到 center 的力。数字越大,布局越紧凑 | 10 | | | centripetalOptions | 向心力配置,包括叶子节点、离散点、其他节点的向心中心及向心力大小。leaf: 叶子节点向心力;single: 单点向心力;others: 其他节点向心力;center: 自定义中心点函数 | [0, 0] | | #### 聚类配置 | 属性 | 描述 | 默认值 | 必选 | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ---- | | clustering | 是否需要全部节点聚类,若为 `true`,将使用 `nodeClusterBy` 配置的节点数据中的字段作为聚类依据。 `centripetalOptions.single`、`centripetalOptions.leaf`、`centripetalOptions.others` 将使用 `getClusterNodeStrength` 返回值;`leaf`、`centripetalOptions.center` 将使用当前节点所属聚类中所有节点的平均中心 | `false` | | | nodeClusterBy | 指定节点数据中的字段名称作为节点聚类的依据,`clustering` 为 true 时生效,自动生成 `centripetalOptions`,可配合 `clusterNodeStrength` 使用 | | | | clusterNodeStrength | 配合 `clustering` 和 `nodeClusterBy` 使用,指定聚类向心力的大小 | | | | leafCluster | 是否需要叶子节点聚类,若为 `true`,则 `centripetalOptions.single` 将为 100;`centripetalOptions.leaf` 将使用 `getClusterNodeStrength` 返回值;`getClusterNodeStrength.center` 将为叶子节点返回当前所有叶子节点的平均中心 | false | | #### 性能与优化配置 | 属性 | 描述 | 默认值 | 必选 | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---- | | damping | 阻尼系数,取值范围 [0, 1]。数字越大,速度降低得越慢 | 0.9 | | | maxSpeed | 一次迭代的最大移动长度 | 200 | | | interval | 控制每个迭代节点的移动速度 | 0.02 | | | preventOverlap | 是否防止重叠,必须配合下面属性 `nodeSize` 或节点数据中的 `data.size` 属性,只有在数据中设置了 `data.size` 或在该布局中配置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测 | true | | | nodeSize | 节点大小(直径)。用于防止节点重叠时的碰撞检测,固定大小或者回调函数动态返回节点大小 | | | | nodeSpacing | `preventOverlap` 为 `true` 时生效, 防止重叠时节点边缘间距的最小值。可以是回调函数, 为不同节点设置不同的最小间距 | | | | collideStrength | 防止重叠的力强度,范围 [0, 1] | 1 | | #### 其他配置 | 属性 | 描述 | 默认值 | 必选 | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---- | | getMass | 获取节点质量的回调函数,入参为节点内部流转数据,用于计算节点质量大小 | | | | getCenter | 每个节点中心力的 x、y、强度的回调函数,若不指定,则没有额外中心力 | | | | onTick | 每一次迭代的回调函数 | | | | monitor | 每个迭代的监控信息回调,energy 表示布局的收敛能量。若配置可能带来额外的计算能量性能消耗,不配置则不计算。入参为迭代监控信息 `{ energy: number; nodes: Node[]; edges: Edge[]; iterations: number; }` | | | ## 代码示例 ### 基础用法 ```js const graph = new Graph({ container: 'container', layout: { type: 'force', // 防止节点重叠 preventOverlap: true, // 节点大小 nodeSize: 20, // 布局宽度 width: 800, // 布局高度 height: 600, }, }); ``` ### 防止节点重叠 ```js const graph = new Graph({ layout: { type: 'force', // 防止节点重叠 preventOverlap: true, // 节点大小 nodeSize: 20, }, }); ``` ### 力导向布局 该示例展示了如何使用力导向布局创建一个基础的力导向图。 ```js import { Graph, NodeEvent } from '@antv/g6'; const data = { nodes: [ { id: 'node1', label: 'Node 1', size: 30 }, { id: 'node2', label: 'Node 2', size: 20 }, { id: 'node3', label: 'Node 3', size: 20 }, { id: 'node4', label: 'Node 4', size: 20 }, { id: 'node5', label: 'Node 5', size: 30 }, { id: 'node6', label: 'Node 6', size: 20 }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node4' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, { source: 'node5', target: 'node6' }, ], }; const graph = new Graph({ container: 'container', data, autoFit: 'view', modes: { default: ['drag-canvas', 'zoom-canvas'], }, layout: { type: 'force', // 防止节点重叠 preventOverlap: true, // 节点大小 nodeSize: 20, // 向心力 gravity: 0.9, // 迭代次数 iterations: 100, }, node: { style: { size: (d) => d.size, fill: '#9EC9FF', stroke: '#69C8FF', label: (d) => d.label, labelPlacement: 'center', labelFill: '#333', }, }, edge: { style: { stroke: '#e2e2e2', }, }, }); graph.on(NodeEvent.CLICK, async (e) => { const nodeId = e.target.id; graph.updateNodeData([{ id: nodeId, size: 200 }]); await graph.render(); }); graph.render(); ``` 主要配置说明: - `preventOverlap`: 开启节点重叠检测 - `nodeSize`: 设置节点大小 - `gravity`: 设置节点向心力 - `iterations`: 设置布局计算的精确程度 还可以参考 [查看示例](/zh/examples/layout/force-directed/force/) 获取更多用法。 #### 对齐线 Snapline - Canonical page: https://g6.antv.antgroup.com/zh/manual/plugin/Snapline/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/plugin/Snapline.md - Description: 对齐线 Snapline --- title: "对齐线 Snapline" description: "对齐线 Snapline" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/plugin/Snapline/" version: "5.1.1" --- ## 概述 对齐线插件为画布提供智能对齐参考线,在移动节点时自动显示辅助线并支持自动吸附,帮助用户实现精确对齐,是图形编辑中提升效率和精确度的重要工具。 ## 使用场景 对齐线插件主要适用于以下场景: - 手动调整节点位置时,需要与其他节点精确对齐 - 拖拽移动多个节点时,保持它们之间的对齐关系 - 制作规范的图形布局时,确保节点间距和位置的一致性 - 通过自动吸附功能提高节点排版效率 ## 基本用法 以下是一个简单的 Snapline 插件初始化示例: ```js const graph = new Graph({ plugins: [ { type: 'snapline', key: 'my-snapline', // 指定唯一标识符 tolerance: 5, // 对齐吸附阈值 offset: 20, // 对齐线延伸距离 autoSnap: true, // 启用自动吸附 }, ], }); ``` ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [ { id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }, ], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }, layout: { type: 'grid' }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { type: 'grid-line', key: 'grid-line', size: 30 }, { type: 'snapline', key: 'snapline', tolerance: 5, offset: 20, verticalLineStyle: { stroke: '#F08F56', lineWidth: 2 }, horizontalLineStyle: { stroke: '#17C76F', lineWidth: 2 }, }, ], }, { width: 600, height: 300 }, (gui, graph) => { const options = { type: 'snapline', tolerance: 5, offset: 20, autoSnap: true, }; const optionFolder = gui.addFolder('Snapline Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'tolerance', 1, 20, 1); optionFolder.add(options, 'offset', 1, 50, 1); optionFolder.add(options, 'autoSnap'); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'snapline', [property]: value, }); graph.render(); }); }, ); ``` ## 配置项 | 属性 | 描述 | 类型 | 默认值 | 必选 | | ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ---- | | type | 插件类型 | string | `'snapline'` | ✓ | | key | 插件唯一标识符 | string | - | | | tolerance | 对齐精度,即触发对齐的距离阈值 | number | 5 | | | offset | 对齐线头尾的延伸距离 | number | 20 | | | autoSnap | 是否启用自动吸附 | boolean | true | | | shape | 指定元素的参照图形:
- `'key'`: 使用元素的主图形作为参照图形
- `Function`: 传入函数时接收元素对象,返回一个图形 | string \| ((node: Node) => DisplayObject) | `'key'` | | | verticalLineStyle | 垂直对齐线样式 | 支持[BaseStyleProps](/zh/manual/element/shape/properties/#baseshapestyle) 下的部分配置,详见[「对齐线样式配置项」](#对齐线样式配置) | `{ stroke: '#1783FF' }` | | | horizontalLineStyle | 水平对齐线样式 | 支持[BaseStyleProps](/zh/manual/element/shape/properties/#baseshapestyle) 下的部分配置,详见[「对齐线样式配置项」](#对齐线样式配置) | `{ stroke: '#1783FF' }` | | | filter | 过滤不需要参与对齐的节点 | (node: Node) => boolean | `() => true` | | ### shape `shape` 属性用于指定元素的参照图形,支持以下配置方式: ```js // 使用主图形作为参照 { type: 'snapline', shape: 'key' } // 使用自定义函数返回参照图形 { type: 'snapline', shape: (node) => { return node.getShape('custom-shape'); } } ``` ### 对齐线样式配置 | 配置项 | 说明 | 类型 | 默认值 | | -------------- | --------------- | ---------------------------------------- | ----------- | | stroke | 线条颜色 | string \| Pattern \| null | `'#1783FF'` | | opacity | 整体透明度 | number \| string | 1 | | strokeOpacity | 描边透明度 | number \| string | 1 | | lineWidth | 线宽度 | number \| string | 1 | | lineCap | 线段端点样式 | `'butt'` \| `'round'` \| `'square'` | `'butt'` | | lineJoin | 线段连接处样式 | `'miter'` \| `'round'` \| `'bevel'` | `'miter'` | | lineDash | 虚线配置 | number \| string \| (string \| number)[] | - | | lineDashOffset | 虚线偏移量 | number | 0 | | shadowBlur | 阴影模糊程度 | number | 0 | | shadowColor | 阴影颜色 | string | - | | shadowOffsetX | 阴影 X 方向偏移 | number | 0 | | shadowOffsetY | 阴影 Y 方向偏移 | number | 0 | | cursor | 鼠标样式 | string | `'default'` | | zIndex | 渲染层级 | number | 0 | 示例配置 ```js { type: 'snapline', horizontalLineStyle: { stroke: '#F08F56', strokeOpacity: 0.8, lineWidth: 2, lineDash: [4, 4], lineDashOffset: 0, opacity: 1, cursor: 'move', }, verticalLineStyle: { stroke: '#17C76F', strokeOpacity: 0.8, lineWidth: 2, lineDash: [4, 4], lineDashOffset: 0, opacity: 1, cursor: 'move', }, } ``` ## 代码示例 ### 基础对齐线 最简单的使用方式: ```js const graph = new Graph({ plugins: ['snapline'], }); ``` ### 自定义配置 可以根据需要自定义对齐线的行为: ```js const graph = new Graph({ plugins: [ { type: 'snapline', tolerance: 8, // 更大的吸附范围 offset: 30, // 更长的延伸线 horizontalLineStyle: { stroke: '#1890ff', lineWidth: 2, }, filter: (node) => node.id !== 'node-0', // 根据id过滤节点,不参与对齐 }, ], }); ``` ## 实际案例 ```ts import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { type: 'snapline', key: 'snapline', verticalLineStyle: { stroke: '#F08F56', lineWidth: 2 }, horizontalLineStyle: { stroke: '#17C76F', lineWidth: 2 }, autoSnap: false, }, ], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 滚动画布 ScrollCanvas - Canonical page: https://g6.antv.antgroup.com/zh/manual/behavior/ScrollCanvas/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/behavior/ScrollCanvas.md - Description: 滚动画布 ScrollCanvas --- title: "滚动画布 ScrollCanvas" description: "滚动画布 ScrollCanvas" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/ScrollCanvas/" version: "5.1.1" --- ## 概述 ScrollCanvas 是 G6 中用于实现画布滚动功能的内置交互,支持通过鼠标滚轮或键盘方向键平移画布。这种交互方式对于浏览较大的图表特别有用,能让用户在不改变缩放比例的情况下探索图表的不同区域。 ## 使用场景 这一交互主要用于: - 浏览超出可视区域的大型图表内容 - 在保持当前缩放比例的情况下探索图的不同部分 - 精确调整查看位置,尤其是在一维方向上需要精确滚动时 ## 在线体验 ```ts import { createGraph } from '/demo-runtime.ts'; createGraph( { data: { nodes: [{ id: 'node-1' }] }, layout: { type: 'force' }, behaviors: [ { type: 'scroll-canvas', key: 'scroll-canvas', }, ], node: { style: { fill: '#873bf4' } }, edge: { style: { stroke: '#8b9baf' } }, plugins: [{ type: 'grid-line', size: 30 }], }, { width: 600, height: 300 }, (gui, graph) => { const options = { key: 'scroll-canvas', type: 'scroll-canvas', direction: 'No limit', enable: true, sensitivity: 1, trigger: 'Use wheel by default', }; const optionFolder = gui.addFolder('ZoomCanvas Options'); optionFolder.add(options, 'type').disable(true); optionFolder.add(options, 'direction', { 'No limit': '', 'Only allow horizontal scrolling': 'x', 'Only allow vertical scrolling': 'y', }); optionFolder.add(options, 'enable'); optionFolder.add(options, 'sensitivity', 0, 10, 1); optionFolder.add(options, 'trigger', { 'Use wheel by default': [], 'Shift+Arrow Key': { up: ['Shift', 'ArrowUp'], down: ['Shift', 'ArrowDown'], left: ['Shift', 'ArrowLeft'], right: ['Shift', 'ArrowRight'], }, }); optionFolder.onChange(({ property, value }) => { graph.updateBehavior({ key: 'scroll-canvas', [property]: value, }); graph.render(); }); }, ); ``` ## 基本用法 在图配置中添加这一交互: **1. 快速配置(静态)** 使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['scroll-canvas'], }); ``` **2. 对象配置(推荐)** 使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置: ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'scroll-canvas', key: 'scroll-canvas-1', // 为交互指定标识符,方便动态更新 sensitivity: 1.5, // 设置灵敏度 direction: 'y', // 只允许垂直方向滚动 }, ], }); ``` ## 配置项 | 配置项 | 说明 | 类型 | 默认值 | 必选 | | -------------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | ---- | | type | 交互类型名称 | string | `scroll-canvas` | ✓ | | enable | 是否启用该交互 | boolean \| ((event: [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent) \| [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)) => boolean) | true | | | direction | 允许的滚动方向,[配置项](#direction) | `'x'` \| `'y'` \| `undefined` | `undefined` (不限制方向) | | | range | 可滚动的视口范围(以视口大小为单位),[配置项](#range) | number \| number[] | 1 | | | sensitivity | 滚动灵敏度,值越大滚动速度越快 | number | 1 | | | trigger | 触发滚动的键盘快捷键,[配置项](#trigger) | object | - | | | onFinish | 滚动完成时的回调函数 | () => void | - | | | preventDefault | 是否阻止浏览器默认事件 | boolean | true | | ### Direction `direction` 用于限制滚动的方向: - 不设置或设为 `undefined`:允许在任意方向滚动 - 设为 `'x'`:只允许水平方向滚动 - 设为 `'y'`:只允许垂直方向滚动 这在特定的可视化场景下很有用,例如在时间轴图表中可能只需要水平滚动。 ### Range `range` 用于控制画布可滚动的范围: - 设置为单个数字:四个方向使用相同的值 - 设置为数组:分别指定 [上, 右, 下, 左] 四个方向的范围 例如: ```javascript range: 2; // 在任何方向上都可以滚动2个视口的距离 range: [1, 2, 1, 2]; // 上下方向可滚动1个视口,左右方向可滚动2个视口 ``` 每个方向的取值范围是 [0, Infinity],0表示不能滚动,Infinity表示无限滚动。 ### Trigger `trigger` 允许你配置键盘方向键来控制画布滚动: ```javascript { trigger: { up: ['ArrowUp'], // 向上滚动的快捷键 down: ['ArrowDown'], // 向下滚动的快捷键 left: ['ArrowLeft'], // 向左滚动的快捷键 right: ['ArrowRight'] // 向右滚动的快捷键 } } ``` 你也可以配置组合键: ```javascript { trigger: { up: ['Control', 'ArrowUp'], // Ctrl + 上箭头 down: ['Control', 'ArrowDown'], // Ctrl + 下箭头 left: ['Control', 'ArrowLeft'], // Ctrl + 左箭头 right: ['Control', 'ArrowRight'] // Ctrl + 右箭头 } } ``` ## 代码示例 ### 基础滚动功能 ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['scroll-canvas'], }); ``` ### 只允许水平滚动 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'scroll-canvas', direction: 'x', // 只允许水平滚动 }, ], }); ``` ### 自定义滚动灵敏度和范围 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'scroll-canvas', sensitivity: 1.8, // 提高滚动灵敏度 range: [0.5, 2, 0.5, 2], // 上下方向限制较小,左右方向限制较大 }, ], }); ``` ### 使用键盘方向键控制滚动 ```javascript const graph = new Graph({ // 其他配置... behaviors: [ { type: 'scroll-canvas', trigger: { up: ['ArrowUp'], down: ['ArrowDown'], left: ['ArrowLeft'], right: ['ArrowRight'], }, }, ], }); ``` ## 常见问题 ### 1. ScrollCanvas 和 ZoomCanvas 有什么区别? - `ScrollCanvas` 用于平移画布,不改变缩放比例 - `ZoomCanvas` 用于缩放画布,改变视图的缩放比例 两者常结合使用,提供完整的画布导航功能: ```javascript const graph = new Graph({ // 其他配置... behaviors: ['drag-canvas', 'zoom-canvas', 'scroll-canvas'], }); ``` ### 实际案例 ```ts import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', layout: { type: 'grid', }, data: { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node1', target: 'node4' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }, behaviors: ['scroll-canvas'], }); graph.render(); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` #### 参与贡献 - Canonical page: https://g6.antv.antgroup.com/zh/manual/contribute/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/contribute.md - Description: 参与贡献 --- title: "参与贡献" description: "参与贡献" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/contribute/" version: "5.1.1" --- 要参与贡献,你需要了解 G6 的代码结构和开发流程。G6 的代码仓库地址是:https://github.com/antvis/G6 如果你想要修复一个 bug 或者增加一个新功能,你需要先 fork 一份代码到你的仓库,然后在你的仓库中进行修改,最后提交 PR 到 G6 的仓库。 ## 项目结构
  • packages
    • g6 G6 核心实现
      • __tests__ 测试及开发环境
        • assets 测试静态资源
        • bugs Bug 修复测试用例
        • dataset 测试数据集
        • demos 开发示例
        • snapshots 测试截图
        • perf 性能测试用例
        • perf-report 性能测试报告
        • unit 测试用例
        • utils 测试工具函数
      • src
        • animations 动画执行器及内置动画
        • behaviors 内置交互
        • constants 常量及枚举值
        • elements 内置元素
          • combos 内置组合
          • edges 内置边
          • nodes 内置节点
          • shapes 复合图形
        • layouts 布局引用及封装
        • palettes 内置色板
        • plugins 内置插件
        • registry 注册模块
        • runtime Graph 及核心控制器
        • spec Specification 类型定义
        • themes 内置主题
        • transforms 内置数据转换
        • types 类型定义
        • utils 工具函数
        • exports.ts 导出项
        • preset.ts 预操作
      • vite.config.js 开发环境 Vite 配置
    • g6-extension-3d/src 3D 扩展
      • behaviors 3D 交互
      • elements 3D 元素
      • plugins 3D 插件
      • renderer.ts 3D 渲染器
    • g6-extension-react/src React 节点扩展
      • elements React 元素
      • graph React Graph 封装
    • site 官网及文档
      • docs 教程及 API
      • examples 图表示例
      • astro.config.mjs 配置文件
## 开发流程 1. Fork 并拉取代码 在 Github 中 Fork [G6](https://github.com/antvis/G6) 到你的仓库,并拉取到本地。 ```bash # 进入你的工作目录 cd /path/to/your/workspace # 克隆 G6 代码 git clone git@github.com:[your username]/G6.git ``` 2. 安装依赖 :::warning{title=注意} 请验证你的本地环境是否符合要求: - [Node.js](https://nodejs.org/) 版本 >= 18 - [pnpm](https://pnpm.io/) 版本 >= 8 ::: ```bash # 进入 G6 代码目录 cd G6 # 安装依赖 pnpm install ``` 3. 启动开发环境 ```bash # 进入 G6 代码目录 cd ./packages/g6 # 启动开发环境 pnpm dev ``` 此时,你可以在浏览器中访问 `http://127.0.0.1:8080` 查看 G6 的开发环境并预览开发示例。 4. 开发新功能或修复 bug 切换到开发分支: ```bash git checkout -b [branch name] ``` 根据你的需求,修改代码并在本地测试。 5. 编写测试用例 在 `packages/g6/__tests__/unit` 目录下编写测试用例,确保你的代码符合预期。 确保你的代码通过测试: ```bash pnpm test ``` 6. 提交 PR ```bash # 添加修改 git add . # 提交修改 git commit -m "[commit type]: commit message" # 推送到你的仓库 git push ``` 在 Github 中提交 PR 到 G6 仓库。 ### 官网开发 官网位于 `packages/site`,使用 Astro 与 `@antv/astro-theme-antv`,需要 Node.js >= 22.12.0 和 pnpm 10.34.5。在仓库根目录运行: ```bash pnpm install pnpm site ``` 站点配置在 `packages/site/astro.config.mjs`,首页组件在 `src/components`。纯文档保留 `.md`,需要 `Demo` 等组件时使用 `.mdx`;双语页面使用 `/zh/`、`/en/` 前缀。`docs/demos` 中的源码供文档复用,`examples` 保留独立示例与注册元数据。 文档和独立示例共用的 `createGraph`、`addPanel` 放在 `src/demo-runtime.ts`,通过 `/demo-runtime.ts` 导入。新增通用行为时修改此模块,不在各示例中复制;对应的模块映射由站点配置维护。 完整站点构建使用 `pnpm --filter @antv/g6-site build`,产物位于 `packages/site/dist`,`public/CNAME` 随产物发布。只验证当前修改涉及的页面和示例;不要默认运行完整构建或库测试。主题兼容补丁通过 pnpm 安装,涵盖 Demo JSX/导出与加载状态、Markdown 空文档和可选字体变量;升级到包含这些能力的主题版本后移除相应补丁并定向验证。 ## 测试与覆盖率 G6 使用 Jest 进行单元测试,测试用例位于 `packages/g6/__tests__/unit` 目录下。 我们要求所有的代码提交都需要通过测试,确保代码质量。 当前 PR 提交的覆盖率不建议低于当前代码库的覆盖率,且不得低于 90%。 ### 更新测试截图 G6 扩展了 Jest 测试,提供了 `toMatchSnapshot` 断言用于生成以及对比快照。 如果当前可能修改影响了部分截图的生成,需要通过执行 `pnpm test` 检查是否有测试用例失败。 当发现测试失败的用例时,控制台会打印出失败的测试路径,以及基准截图和当前截图的路径信息。你可以按住 `Ctrl` 或 `Command` 键并点击路径,查看具体的测试用例或截图。 如果确认本次修改是正确的,那么请手动删除对应的基准截图,并重新生成截图: **重新生成全部截图**: 1. 删除 `packages/g6/__tests__/unit/snapshots` 目录下的所有文件 2. 执行 `pnpm test` **重新生成单个截图**: 1. 删除 `packages/g6/__tests__/snapshots` 目录下对应的文件(`unit`目录下测试用例会在`snapshots`下生成对应的目录) 2. 执行 `npx jest __tests__/unit/xx/xxx.spec.ts` ## 代码规范 G6 编码尊循以下规范: - eslint:recommended - @typescript-eslint/recommended - jsdoc/recommended-error ## 提交规范 G6 采用 [Conventional Commits](https://www.conventionalcommits.org/) 规范,提交信息格式如下: ``` [optional scope]: ``` type 有以下几种: - feat: 新功能 - fix: 修复 bug - docs: 文档更新 - style: 代码格式(不影响代码运行的变动) - refactor: 重构 - perf: 性能优化 - test: 测试 - build: 构建工具相关的变动 - ci: CI 配置 - chore: 其他无关紧要的变动 - revert: 撤销 例如: ``` feat: add new feature refactor(behavior): refactor drag-canvas behavior ``` 请确保你的提交信息符合规范,并尽量使用英文描述,这样有助于我们更好地管理代码。 ## PR 规范 完成上述步骤后,你可以提交 PR 到 G6 仓库。请确保你的 PR 符合以下规范: - 一个 PR 只解决一个问题 - PR 的标题简洁明了 - PR 的描述清晰详细,涉及视图的变动请附上截图 - PR 必需能够通过 CI 检查 ## 代码 Review PR 提交后,我们会对你的代码进行 Review。请耐心等待 Review 结果,如果有需要修改的地方,我们会在 PR 中提出。 ## 发布流程 我们会定期发布新版本,如果你的 PR 是非紧急缺陷修复,我们会在下一个版本中发布。如果你的 PR 是紧急缺陷修复,我们会尽快发布新版本。 本项目通过 changeset 来管理版本发布,具体的发布流程如下: 1. 完成相关的开发工作 2. 从 v5 分支创建一个分支(任意分支名均可) 3. 根目录执行 `npm run version` 命令,根据提示填写相关信息,会自动更新版本号 4. 将变更提交到远程仓库 5. 在 GitHub 上创建一个 PR,并添加 `publish` 标签,将该分支合并到 v5 分支 6. 分支合并后,会自动触发 GitHub Actions,发布到 npm 7. 发布后,需更新 Release note,在 packages/g6 目录下执行 pnpm tag 8. 在新打开的 Github 链接填写 tag 信息,先选择前一个 tag, 然后选择当前 tag 后得到变更,确认没有问题后发布 #### 使用 Vue 定义节点 - Canonical page: https://g6.antv.antgroup.com/zh/manual/element/node/vue-node/ - Markdown source: https://g6.antv.antgroup.com/zh/manual/element/node/vue-node.md - Description: 使用 Vue 定义节点 --- title: "使用 Vue 定义节点" description: "使用 Vue 定义节点" language: "zh" canonical: "https://g6.antv.antgroup.com/zh/manual/element/node/vue-node/" version: "5.1.1" --- 在 G6 中,自定义节点通常需要操作 DOM 或 Canvas 元素,但借助 [`g6-extension-vue`](https://github.com/Child-qjj/g6-extension-vue) 社区生态库,可以直接使用 Vue 组件作为节点内容,提升开发效率与可维护性。 ### G6 节点 ✅ **推荐场景:** - 节点只是简单的几何图形 - 需要高效渲染超过 2,000 个节点的场景 - 需要直接操作图形实例进行精细控制 > 有关如何使用 Canvas 图形自定义节点的详细信息,请参阅 [自定义节点](/zh/manual/element/node/custom-node/) 文档 ### Vue Node ✅ **推荐场景:** - 需要集成 Element Plus / Ant Design Vue 等 UI 库的业务系统 - 节点包含表单输入、状态切换等交互逻辑 - 已有 Vue 设计系统需要复用的场景 ## 快速入门 ### 环境准备 在开始之前,请确保您已经: - **安装 Vue 项目**:确保已安装并创建 Vue 项目。 - **Vue 版本要求**:确保使用的 Vue 版本 >=2.6.0。(推荐使用 Vue 3) ### 安装依赖 要使用 [`g6-extension-vue`](https://github.com/Child-qjj/g6-extension-vue),请运行以下命令: :::code-group ```bash [npm] npm install g6-extension-vue ``` ```bash [yarn] yarn add g6-extension-vue ``` ```bash [pnpm] pnpm add g6-extension-vue ``` ::: ### 组件集成 #### 1. 注册 Vue 节点类型 通过扩展机制注册 Vue 节点类型: ```jsx import { ExtensionCategory, register } from '@antv/g6'; import { VueNode } from 'g6-extension-vue'; register(ExtensionCategory.NODE, 'vue-node', VueNode); ``` `register` 方法需要三个参数: - 扩展类别:`ExtensionCategory.NODE` 表示这是一个节点类型 - 类型名称:`vue-node` 是我们给这个自定义节点起的名字,后续会在配置中使用 - 类定义:VueNode 是 `g6-extension-vue` 导出的实现类 #### 2. 定义业务组件 定义一个简单的 Vue 组件作为节点的内容: ```jsx import { defineComponent, h } from 'vue'; const MyVueNode = defineComponent({ setup(props, { attrs, slots, expose }) { return () => { return h('div', 'vue node'); }; }, }); ``` #### 3. 使用组件 在图配置中使用自定义的 Vue 节点。通过在图配置中指定节点类型和样式,来使用自定义的 Vue 组件。 - `type`:指定节点类型为 `vue-node` (使用与注册时起的名字) - `style.component`:定义节点的 Vue 组件内容 ```jsx const graph = new Graph({ node: { type: 'vue-node', style: { component: () => , }, }, }); graph.render(); ``` ## 高级功能 ### 状态管理 在复杂图可视化场景中,节点需要动态响应交互状态。我们提供两种互补的状态管理方案: #### 响应内置交互状态 G6 提供内置的交互状态管理状态,如 `hover-activate` 和 `click-select`。可以通过节点数据中的 `data.states` 字段获取当前节点状态,并根据状态调整节点样式。 **示例**:在节点被 hover 时改变背景颜色。 ```jsx import { ExtensionCategory, register, Graph } from '@antv/g6'; import { VueNode } from 'g6-extension-vue'; import { computed, defineComponent } from 'vue'; register(ExtensionCategory.NODE, 'vue-node', VueNode); const StatefulNode = defineComponent({ setup(props, { attrs, slots, expose }) { const isActive = computed(() => props.data.states?.includes('active')); const label = computed(() => props.data.data?.label); return (
{label.value}
); }, }); const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 200 }, data: { label: 'node1' } }, { id: 'node2', style: { x: 300, y: 200 }, data: { label: 'node2' } }, ], }, node: { type: 'vue-node', style: { component: (data) => , // data是非响应式数据,需要通过改变引用来触发Vue的props副作用 }, }, behaviors: ['hover-activate'], }); graph.render(); ``` #### 自定义业务状态 当需要管理业务相关状态(如审批状态、风险等级)时,可通过扩展节点数据实现: **示例**:通过 data 添加 `selected` 变量,实现节点选中和取消选中的样式变化。 ```jsx import { ExtensionCategory, register, Graph } from '@antv/g6'; import { VueNode } from 'g6-extension-vue'; import { defineComponent, computed } from 'vue'; register(ExtensionCategory.NODE, 'vue-node', VueNode); const MyVueNode = defineComponent({ setup(props, { attrs, slots, expose }) { const isSelected = computed(() => props.data.data.selected); const handleClick = () => { graph.updateNodeData([{ id: props.data.id, data: { selected: !isSelected.value } }]); graph.draw(); }; return (
Node
); }, }); const graph = new Graph({ data: { nodes: [ { id: 'node1', style: { x: 100, y: 100 }, data: { selected: true }, }, ], }, node: { type: 'vue-node', style: { component: (data) => , // data是非响应式数据,需要通过改变引用来触发Vue的props副作用 }, }, }); graph.render(); ``` ### 事件交互 实现节点与图实例的双向通信,使节点和图实例可以相互更新。 **示例**:通过自定义节点操作图数据,并重新渲染图形。 ```jsx import { ExtensionCategory, register, Graph } from '@antv/g6'; import { VueNode } from 'g6-extension-vue'; import { defineComponent, computed } from 'vue'; register(ExtensionCategory.NODE, 'vue-node', VueNode); const IDCardNode = defineComponent({ setup(props, { attrs, slots, expose }) { const isSelected = computed(() => props.data.data.selected); const handleSelect = () => { graph.updateNodeData([{ id: props.data.id, data: { selected: true } }]); graph.draw(); }; return { const url = event.target.value; onChange?.(url); }} /> ); }; export const ReactNodeDemo = () => { const containerRef = useRef(); useEffect(() => { const graph = new Graph({ container: containerRef.current, data: { nodes: [ { id: 'local-server-1', data: { status: 'success', type: 'local', url: 'http://localhost:3000' }, style: { x: 50, y: 50 }, }, { id: 'remote-server-1', data: { status: 'warning', type: 'remote' }, style: { x: 350, y: 50 }, }, ], edges: [{ source: 'local-server-1', target: 'remote-server-1' }], }, node: { type: 'react', style: { size: [240, 100], component: (data) => , }, }, behaviors: ['drag-element', 'zoom-canvas', 'drag-canvas'], }); graph.render(); }, []); return
; }; const root = createRoot(document.getElementById('container')); root.render(); ``` ### React 节点 身份证 - zh page: https://g6.antv.antgroup.com/zh/examples/element/custom-node/reactnode-idcard/ - Source path: examples/element/custom-node/demo/reactnode-idcard.jsx ```jsx import { UserOutlined } from '@ant-design/icons'; import { ExtensionCategory, Graph, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; import { Avatar, Button, Card, Descriptions, Select, Space, Typography } from 'antd'; import React, { useEffect, useRef } from 'react'; import { createRoot } from 'react-dom/client'; const { Title, Text } = Typography; const { Option } = Select; register(ExtensionCategory.NODE, 'react-node', ReactNode); const IDCardNode = ({ id, data }) => { const { name, idNumber, address, expanded, selected, graph } = data; const toggleExpand = (e) => { e.stopPropagation(); graph.updateNodeData([ { id, data: { expanded: !expanded }, }, ]); graph.render(); }; const handleSelect = (value) => { graph.updateNodeData([ { id, data: { selected: value !== 0 }, }, ]); if (value === 2) { // 获取与当前节点相连的所有节点 const connectedNodes = graph.getNeighborNodesData(id); connectedNodes.forEach((node) => { graph.updateNodeData([ { id: node.id, data: { selected: true }, }, ]); }); } graph.render(); }; const CardTitle = (
} /> {name}
); return ( {expanded ? ( {idNumber} {address} ) : ( IDCard Information )} ); }; // 定义 Graph 数据 const data = { nodes: [ { id: 'node1', data: { name: 'Alice', idNumber: 'IDUSAASD2131734', address: '1234 Broadway, Apt 5B, New York, NY 10001', expanded: false, // 初始状态为收缩 selected: false, // 初始状态为未选中 selectedOption: 1, // 初始选择本节点 }, style: { x: 50, y: 50 }, }, { id: 'node2', data: { name: 'Bob', idNumber: 'IDUSAASD1431920', address: '3030 Chestnut St, Philadelphia, PA 19104', expanded: false, // 初始状态为收缩 selected: false, // 初始状态为未选中 selectedOption: 0, // 初始不选择 }, style: { x: 700, y: 100 }, }, { id: 'node3', data: { name: 'Charlie', idNumber: 'IDUSAASD1431921', address: '4040 Elm St, Chicago, IL 60611', expanded: false, selected: true, selectedOption: 0, }, }, { id: 'node4', data: { name: 'David', idNumber: 'IDUSAASD1431922', address: '5050 Oak St, Houston, TX 77002', expanded: false, selected: false, selectedOption: 0, }, }, { id: 'node5', data: { name: 'Eve', idNumber: 'IDUSAASD1431923', address: '6060 Pine St, Phoenix, AZ 85001', expanded: false, selected: false, selectedOption: 0, }, }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, { source: 'node3', target: 'node4' }, { source: 'node4', target: 'node5' }, ], }; export const ReactNodeDemo = () => { const containerRef = useRef(); const graphRef = useRef(null); useEffect(() => { // 创建 Graph 实例 const graph = new Graph({ autoFit: 'view', container: containerRef.current, data, node: { type: 'react-node', style: { size: (datum) => (datum.data.expanded ? [340, 236] : [340, 105]), // 调整大小以适应内容 component: (data) => , }, }, behaviors: ['drag-element', 'zoom-canvas', 'drag-canvas'], layout: { type: 'snake', cols: 2, rowGap: 100, colGap: 220, }, }); // 渲染 Graph graph.render(); // 保存 graph 实例 graphRef.current = graph; return () => { graph.destroy(); }; }, []); return
; }; // 渲染 React 组件到 DOM const root = createRoot(document.getElementById('container')); root.render(); ``` ### 箭头 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/arrows/ - Source path: examples/element/edge/demo/arrows.js ```js import { Graph } from '@antv/g6'; const data = { nodes: new Array(16).fill(0).map((_, i) => ({ id: `node${i + 1}` })), edges: [ 'default-arrow', 'triangle-arrow', 'simple-arrow', 'vee-arrow', 'circle-arrow', 'rect-arrow', 'diamond-arrow', 'triangleRect-arrow', ].map((id, i) => ({ id, source: `node${i * 2 + 1}`, target: `node${i * 2 + 2}`, })), }; const graph = new Graph({ data, edge: { style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, endArrowType: (d) => d.id.split('-')[0], }, }, layout: { type: 'grid', cols: 2, }, }); graph.render(); ``` ### 三次贝塞尔曲线 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/cubic/ - Source path: examples/element/edge/demo/cubic.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'cubic', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### 三次贝塞尔曲线-水平 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/horizontal-cubic/ - Source path: examples/element/edge/demo/horizontal-cubic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { port: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, }, edge: { type: 'cubic-horizontal', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, }, }, layout: { type: 'antv-dagre', rankdir: 'LR', nodesep: 20, ranksep: 120, }, }); graph.render(); ``` ### 直线 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/line/ - Source path: examples/element/edge/demo/line.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'line', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### 曲线自环边 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/loop-curve/ - Source path: examples/element/edge/demo/loop-curve.js ```js import { Graph, idOf } from '@antv/g6'; const data = { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3-ports' }, { id: 'node4-ports' }], edges: [ { id: 'loop-1', source: 'node1', target: 'node1', style: { placement: 'top' }, }, { id: 'loop-2', source: 'node1', target: 'node1', style: { placement: 'right' }, }, { id: 'loop-3', source: 'node1', target: 'node1', style: { placement: 'bottom' }, }, { id: 'loop-4', source: 'node1', target: 'node1', style: { placement: 'left' }, }, { id: 'loop-5', source: 'node2', target: 'node2', style: { placement: 'top-right' }, }, { id: 'loop-6', source: 'node2', target: 'node2', style: { placement: 'bottom-right' }, }, { id: 'loop-7', source: 'node2', target: 'node2', style: { placement: 'bottom-left' }, }, { id: 'loop-8', source: 'node2', target: 'node2', style: { placement: 'top-left' }, }, { id: 'loop-9', source: 'node3-ports', target: 'node3-ports', style: { sourcePort: 'port1', targetPort: 'port2' }, }, { id: 'loop-10', source: 'node4-ports', target: 'node4-ports', style: { sourcePort: 'port2', targetPort: 'port2' }, }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { size: [80, 30], port: (d) => idOf(d).includes('ports'), portR: 3, ports: [ { key: 'port1', placement: [0.7, 0], }, { key: 'port2', placement: 'right', }, ], }, }, edge: { type: 'line', style: { sourcePort: (d) => d.style.sourcePort, targetPort: (d) => d.style.targetPort, endArrow: true, loopPlacement: (d) => d.style.placement, }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 嵌套自环边 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/loop-nested/ - Source path: examples/element/edge/demo/loop-nested.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', style: { x: 150, y: 150 } }, { id: 'node2', style: { x: 400, y: 150 } }, { id: 'node3', style: { x: 275, y: 300 } }, ], edges: [ // Node 1: 3 nested loops at 'top' position with different colors { id: 'loop-1', source: 'node1', target: 'node1', style: { loopPlacement: 'top', stroke: '#5B8FF9' } }, { id: 'loop-2', source: 'node1', target: 'node1', style: { loopPlacement: 'top', stroke: '#5AD8A6' } }, { id: 'loop-3', source: 'node1', target: 'node1', style: { loopPlacement: 'top', stroke: '#F6BD16' } }, // Node 2: nested loops at different positions { id: 'loop-4', source: 'node2', target: 'node2', style: { loopPlacement: 'right', stroke: '#E86452' } }, { id: 'loop-5', source: 'node2', target: 'node2', style: { loopPlacement: 'right', stroke: '#6DC8EC' } }, { id: 'loop-6', source: 'node2', target: 'node2', style: { loopPlacement: 'bottom', stroke: '#945FB9' } }, { id: 'loop-7', source: 'node2', target: 'node2', style: { loopPlacement: 'bottom', stroke: '#FF9C6E' } }, // Node 3: mixed - some nested, some spread { id: 'loop-8', source: 'node3', target: 'node3', style: { loopPlacement: 'left', stroke: '#5B8FF9' } }, { id: 'loop-9', source: 'node3', target: 'node3', style: { loopPlacement: 'left', stroke: '#5AD8A6' } }, { id: 'loop-10', source: 'node3', target: 'node3', style: { loopPlacement: 'top-right', stroke: '#F6BD16' } }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'circle', style: { size: 60, labelText: (d) => d.id, }, }, edge: { type: 'quadratic', style: { endArrow: true, lineWidth: 2, labelText: (d) => d.id, labelFill: '#333', labelFontSize: 12, labelOffsetY: -10, labelBackground: true, labelBackgroundFill: '#fff', labelBackgroundOpacity: 0.9, labelBackgroundRadius: 4, labelPadding: [2, 4], }, }, transforms: [ { type: 'process-parallel-edges', loopMode: 'nested', // Enable nested mode for self-loops loopDistance: 30, // Distance between nested loops }, ], }); graph.render(); ``` ### 折线自环边 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/loop-polyline/ - Source path: examples/element/edge/demo/loop-polyline.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3-ports' }, { id: 'node4-ports' }], edges: [ { id: 'loop-1', source: 'node1', target: 'node1', placement: 'top', }, { id: 'loop-2', source: 'node1', target: 'node1', placement: 'right', }, { id: 'loop-3', source: 'node1', target: 'node1', placement: 'bottom', }, { id: 'loop-4', source: 'node1', target: 'node1', placement: 'left', }, { id: 'loop-5', source: 'node2', target: 'node2', placement: 'top-right', }, { id: 'loop-6', source: 'node2', target: 'node2', placement: 'bottom-right', }, { id: 'loop-7', source: 'node2', target: 'node2', placement: 'bottom-left', }, { id: 'loop-8', source: 'node2', target: 'node2', placement: 'top-left', }, { id: 'loop-9', source: 'node3-ports', target: 'node3-ports', style: { sourcePort: 'port1', targetPort: 'port2' }, }, { id: 'loop-10', source: 'node4-ports', target: 'node4-ports', style: { sourcePort: 'port2', targetPort: 'port2' }, }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { size: [80, 30], port: (d) => d.id.includes('ports'), portR: 3, ports: [ { key: 'port1', placement: [0.7, 0], }, { key: 'port2', placement: 'right', }, ], }, }, edge: { type: 'polyline', style: { sourcePort: (d) => d.style.sourcePort, targetPort: (d) => d.style.targetPort, endArrow: true, loopPlacement: (d) => d.placement, }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 折线-带控制点 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/polyline/ - Source path: examples/element/edge/demo/polyline.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 200, y: 200 } }, { id: 'node-2', style: { x: 350, y: 120 } }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2', controlPoints: [[300, 190]], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'polyline', style: { controlPoints: (d) => d.controlPoints, }, }, behaviors: [{ type: 'drag-element' }], }); graph.render(); ``` ### 正交线 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/polyline-orth/ - Source path: examples/element/edge/demo/polyline-orth.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 200, y: 200 } }, { id: 'node-2', style: { x: 350, y: 120 } }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2', }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'polyline', style: { router: { type: 'orth', }, }, }, behaviors: [{ type: 'drag-element' }], }); graph.render(); ``` ### 正交线-带控制点 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/polyline-orth-with-cps/ - Source path: examples/element/edge/demo/polyline-orth-with-cps.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 200, y: 200 } }, { id: 'node-2', style: { x: 350, y: 120 } }, { id: 'node-cp', style: { x: 300, y: 190, size: 5, fill: 'rgb(244, 109, 67)' } }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2', style: { controlPoints: [[300, 190]] }, }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'polyline', style: { router: { type: 'orth', }, controlPoints: (d) => d.style.controlPoints, }, }, behaviors: [{ type: 'drag-element' }], }); graph.render(); ``` ### 二次贝塞尔曲线 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/quadratic/ - Source path: examples/element/edge/demo/quadratic.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, edge: { type: 'quadratic', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, badge: true, badgeText: '\ue603', badgeFontFamily: 'iconfont', badgeBackgroundWidth: 12, badgeBackgroundHeight: 12, }, }, layout: { type: 'radial', unitRadius: 220, linkDistance: 220, }, }); graph.render(); ``` ### 三次贝塞尔曲线-垂直 - zh page: https://g6.antv.antgroup.com/zh/examples/element/edge/vertical-cubic/ - Source path: examples/element/edge/demo/vertical-cubic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', }, { id: 'node2', }, { id: 'node3', }, { id: 'node4', }, { id: 'node5', }, { id: 'node6', }, ], edges: [ { id: 'line-default', source: 'node1', target: 'node2', }, { id: 'line-active', source: 'node1', target: 'node3', states: ['active'], }, { id: 'line-selected', source: 'node1', target: 'node4', states: ['selected'], }, { id: 'line-highlight', source: 'node1', target: 'node5', states: ['highlight'], }, { id: 'line-inactive', source: 'node1', target: 'node6', states: ['inactive'], }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { port: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }, }, edge: { type: 'cubic-vertical', style: { labelText: (d) => d.id, labelBackground: true, endArrow: true, }, }, layout: { type: 'antv-dagre', begin: [50, 50], rankdir: 'TB', nodesep: 20, ranksep: 120, }, }); graph.render(); ``` ### 背景颜色 - zh page: https://g6.antv.antgroup.com/zh/examples/element/label/background/ - Source path: examples/element/label/demo/background.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node1', style: { x: 150, y: 100 } }, { id: 'node2', style: { x: 250, y: 200 } }, { id: 'node3', style: { x: 450, y: 200 } }, ], edges: [ { source: 'node1', target: 'node2' }, { source: 'node1', target: 'node3' }, { source: 'node2', target: 'node3' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.id, labelPosition: 'bottom', labelFill: '#e66465', labelFontSize: 12, labelFontStyle: 'italic', labelBackground: true, labelBackgroundFill: 'linear-gradient(#e66465, #9198e5)', labelBackgroundStroke: '#9ec9ff', labelBackgroundRadius: 2, }, }, edge: { style: { labelText: (d) => d.id, labelPosition: 'center', labelTextBaseline: 'top', labelDy: 5, labelFontSize: 12, labelFontWeight: 'bold', labelFill: '#1890ff', labelBackground: true, labelBackgroundFill: 'linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)', labelBackgroundStroke: '#9ec9ff', labelBackgroundRadius: 2, }, }, layout: { type: 'force', }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 复制 - zh page: https://g6.antv.antgroup.com/zh/examples/element/label/copy/ - Source path: examples/element/label/demo/copy.js ```js import { Graph, NodeEvent } from '@antv/g6'; const data = { nodes: [ { id: 'node1', data: { label: 'Click to copy this label which is too long to be displayed', }, }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { x: 200, y: 200, size: 150, labelPlacement: 'center', labelText: (d) => d.data.label, labelWordWrap: true, labelMaxWidth: '90%', labelBackground: true, labelBackgroundFill: '#eee', labelBackgroundFillOpacity: 0.5, labelBackgroundRadius: 4, labelPointerEvents: 'none', labelBackgroundPointerEvents: 'none', }, }, behaviors: ['drag-element'], plugins: [ { type: 'tooltip', getContent: (e, items) => { let result = `

Node Label:

`; items.forEach((item) => { result += `

${item.data.label}

`; }); return result; }, }, ], }); graph.render(); graph.on('node:click', (e) => { const node = graph.getNodeData(e.target.id); const label = node?.data?.label; navigator.clipboard.writeText(label); alert('copied to clipboard!'); }); graph.on(NodeEvent.POINTER_ENTER, (e) => { graph.setElementState({ [e.target.id]: 'active' }); }); graph.on(NodeEvent.POINTER_OUT, (e) => { graph.setElementState({ [e.target.id]: [] }); }); ``` ### 文本省略 - zh page: https://g6.antv.antgroup.com/zh/examples/element/label/ellipsis/ - Source path: examples/element/label/demo/ellipsis.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 100, y: 150, size: 100 } }, { id: 'node-2', style: { x: 400, y: 150, size: 150 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }; const graph = new Graph({ container: 'container', data, node: { style: { labelPlacement: 'center', labelText: 'This label is too long to be displayed', labelWordWrap: true, // enable label ellipsis labelMaxWidth: '90%', labelBackground: true, labelBackgroundFill: '#eee', labelBackgroundFillOpacity: 0.5, labelBackgroundRadius: 4, }, }, edge: { style: { labelOffsetY: -4, labelTextBaseline: 'bottom', labelText: 'This label is too long to be displayed', labelWordWrap: true, labelMaxWidth: '80%', labelBackground: true, labelBackgroundFill: 'red', labelBackgroundFillOpacity: 0.5, labelBackgroundRadius: 4, }, }, behaviors: ['drag-element'], }); graph.render(); ``` ### 文本换行 - zh page: https://g6.antv.antgroup.com/zh/examples/element/label/word-wrap/ - Source path: examples/element/label/demo/word-wrap.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', style: { x: 100, y: 150, size: 100 } }, { id: 'node-2', style: { x: 400, y: 150, size: 150 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }; const graph = new Graph({ container: 'container', fitCenter: true, data, node: { type: 'rect', style: { labelPlacement: 'bottom', labelText: 'This label is too long to be displayed', labelMaxWidth: '90%', labelBackground: true, labelBackgroundFill: '#eee', labelBackgroundFillOpacity: 0.5, labelBackgroundRadius: 4, labelWordWrap: true, labelMaxLines: 4, }, }, edge: { style: { labelOffsetY: -4, labelTextBaseline: 'bottom', labelText: 'This label is too long to be displayed', labelMaxWidth: '80%', labelBackground: true, labelBackgroundFill: 'red', labelBackgroundFillOpacity: 0.5, labelBackgroundRadius: 4, labelWordWrap: true, labelMaxLines: 4, }, }, behaviors: ['drag-element'], }); graph.render(); ``` ### 3D 节点 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/3d-node/ - Source path: examples/element/node/demo/3d-node.js ```js import { ExtensionCategory, Graph, register } from '@antv/g6'; import { Capsule, Cone, Cube, Cylinder, Light, ObserveCanvas3D, Plane, Sphere, Torus, renderer, } from '@antv/g6-extension-3d'; register(ExtensionCategory.PLUGIN, '3d-light', Light); register(ExtensionCategory.NODE, 'sphere', Sphere); register(ExtensionCategory.NODE, 'plane', Plane); register(ExtensionCategory.NODE, 'cylinder', Cylinder); register(ExtensionCategory.NODE, 'cone', Cone); register(ExtensionCategory.NODE, 'cube', Cube); register(ExtensionCategory.NODE, 'capsule', Capsule); register(ExtensionCategory.NODE, 'torus', Torus); register(ExtensionCategory.BEHAVIOR, 'observe-canvas-3d', ObserveCanvas3D); const nodes = [ { id: 'node-1', type: 'sphere', style: { texture: 'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*cdTdTI2bNl8AAAAAAAAAAAAADmJ7AQ/original', }, }, { id: 'node-2', type: 'plane', style: { size: 50 } }, { id: 'node-3', type: 'cylinder' }, { id: 'node-4', type: 'cone' }, { id: 'node-5', type: 'cube', style: { texture: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*8TlCRIsKeUkAAAAAAAAAAAAAARQnAQ', }, }, { id: 'node-6', type: 'capsule' }, { id: 'node-7', type: 'torus' }, ]; const graph = new Graph({ container: 'container', renderer, data: { nodes, }, node: { style: { materialType: 'phong', labelText: (d) => d.id, x: (d) => 100 + (nodes.findIndex((n) => n.id === d.id) % 5) * 100, y: (d) => 100 + Math.floor(nodes.findIndex((n) => n.id === d.id) / 5) * 100, }, }, plugins: [ { type: '3d-light', directional: { direction: [0, 0, 1], }, }, ], behaviors: ['observe-canvas-3d'], }); graph.render(); ``` ### 圆形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/circle/ - Source path: examples/element/node/demo/circle.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'circle', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 菱形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/diamond/ - Source path: examples/element/node/demo/diamond.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'diamond', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 甜甜圈 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/donut/ - Source path: examples/element/node/demo/donut.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default', index: 0 }, { id: 'halo', index: 1 }, { id: 'badges', index: 2 }, { id: 'ports', index: 3 }, { id: 'active', states: ['active'], index: 4, }, { id: 'selected', states: ['selected'], index: 5, }, { id: 'highlight', states: ['highlight'], index: 6, }, { id: 'inactive', states: ['inactive'], index: 7, }, { id: 'disabled', states: ['disabled'], index: 8, }, ], }; const graph = new Graph({ container: 'container', animation: false, data, node: { type: 'donut', style: { size: 80, fill: '#DB9D0D', innerR: 20, donuts: (item) => { const { index } = item; if (index === 0) return [1, 2, 3]; // donuts数据类型为number[]时,根据值的大小决定环的占比 if (index === 1) { return [ { value: 50, color: 'red' }, { value: 150, color: 'green' }, { value: 100, color: 'blue' }, ]; } if (index === 4) { return [ { value: 150, fill: 'pink', stroke: '#fff', lineWidth: 1 }, { value: 250, stroke: '#fff', lineWidth: 1 }, { value: 200, stroke: '#fff', lineWidth: 1 }, ]; } return [100, 200, 100, 200]; }, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 椭圆 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/ellipse/ - Source path: examples/element/node/demo/ellipse.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'ellipse', style: { size: [45, 35], labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 六边形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/hexagon/ - Source path: examples/element/node/demo/hexagon.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'hexagon', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], outerR: 30, // 外半径 portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### HTML节点 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/html/ - Source path: examples/element/node/demo/html.js ```js import { Graph } from '@antv/g6'; const ICON_MAP = { error: '❌', overload: '⚡', running: '✅', }; const COLOR_MAP = { error: '#f5222d', overload: '#faad14', running: '#52c41a', }; const graph = new Graph({ container: 'container', data: { nodes: [ { id: 'node-1', data: { location: 'East', status: 'error', ip: '192.168.1.2' } }, { id: 'node-2', data: { location: 'West', status: 'overload', ip: '192.168.1.3' } }, { id: 'node-3', data: { location: 'South', status: 'running', ip: '192.168.1.4' } }, ], }, node: { type: 'html', style: { size: [240, 80], dx: -120, dy: -40, innerHTML: (d) => { const { data: { location, status, ip }, } = d; const color = COLOR_MAP[status]; return `
${location} Node
status: ${status} ${ICON_MAP[status]}
${ip}
`; }, }, }, layout: { type: 'grid', }, behaviors: ['drag-element', 'zoom-canvas'], }); graph.render(); ``` ### 图片 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/image/ - Source path: examples/element/node/demo/image.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'image', style: { size: 40, labelText: (d) => d.id, src: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', haloStroke: '#227eff', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, state: { inactive: { fillOpacity: 0.5, }, disabled: { fillOpacity: 0.2, }, }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 连接桩 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/port/ - Source path: examples/element/node/demo/port.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', type: 'circle', style: { x: 80, y: 200, size: 30 } }, { id: 'node-2', type: 'rect', style: { x: 250, y: 200, size: 50, port: true, ports: [ { key: 'port-1', placement: [0, 0.15] }, { key: 'port-2', placement: [0, 0.5] }, { key: 'port-3', placement: [0, 0.85] }, ], }, }, ], edges: [ { id: 'edge-1', source: 'node-1', target: 'node-2', style: { targetPort: 'port-1' } }, { id: 'edge-2', source: 'node-1', target: 'node-2', style: { targetPort: 'port-2' } }, { id: 'edge-3', source: 'node-1', target: 'node-2', style: { targetPort: 'port-3' } }, ], }; const graph = new Graph({ data, edge: { style: { endArrow: true, }, }, }); graph.render(); addPanel((gui) => { const config = { show: false, position: 'outline' }; gui.add(config, 'position', ['outline', 'center']).onChange((value) => { graph.updateNodeData([{ id: 'node-2', style: { portLinkToCenter: value === 'center' } }]); graph.draw(); }); gui .add(config, 'show') .onChange((value) => { graph.updateNodeData([{ id: 'node-2', style: { portR: value ? 5 : 0 } }]); graph.draw(); }) .name('show ports'); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 矩形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/rect/ - Source path: examples/element/node/demo/rect.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 圆角矩形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/rounded-rect/ - Source path: examples/element/node/demo/rounded-rect.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { radius: 4, // 👈🏻 Set the radius. size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 星形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/star/ - Source path: examples/element/node/demo/star.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'star', style: { size: 40, labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 三角形 - zh page: https://g6.antv.antgroup.com/zh/examples/element/node/triangle/ - Source path: examples/element/node/demo/triangle.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const data = { nodes: [ { id: 'default' }, { id: 'halo' }, { id: 'badges' }, { id: 'ports' }, { id: 'active', states: ['active'], }, { id: 'selected', states: ['selected'], }, { id: 'highlight', states: ['highlight'], }, { id: 'inactive', states: ['inactive'], }, { id: 'disabled', states: ['disabled'], }, ], }; const graph = new Graph({ container: 'container', data, node: { type: 'triangle', style: { size: 40, direction: (d) => (d.id === 'ports' ? 'left' : undefined), labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue602', halo: (d) => (d.id === 'halo' ? true : false), badges: (d) => d.id === 'badges' ? [ { text: 'A', placement: 'right-top', }, { text: 'Important', placement: 'right', }, { text: 'Notice', placement: 'right-bottom', }, ] : [], badgeFontSize: 8, badgePadding: [1, 4], portR: 3, ports: (d) => d.id === 'ports' ? [{ placement: 'left' }, { placement: 'right' }, { placement: 'top' }, { placement: 'bottom' }] : [], }, }, layout: { type: 'grid', }, }); graph.render(); ``` ### 3D大数据 - zh page: https://g6.antv.antgroup.com/zh/examples/feature/default/3d-massive/ - Source path: examples/feature/default/demo/3d-massive.js ```js import { CameraSetting, ExtensionCategory, Graph, register } from '@antv/g6'; import { Light, Line3D, ObserveCanvas3D, Sphere, ZoomCanvas3D, renderer } from '@antv/g6-extension-3d'; register(ExtensionCategory.PLUGIN, '3d-light', Light); register(ExtensionCategory.NODE, 'sphere', Sphere); register(ExtensionCategory.EDGE, 'line3d', Line3D); register(ExtensionCategory.PLUGIN, 'camera-setting', CameraSetting); register(ExtensionCategory.BEHAVIOR, 'zoom-canvas-3d', ZoomCanvas3D); register(ExtensionCategory.BEHAVIOR, 'observe-canvas-3d', ObserveCanvas3D); await fetch('https://assets.antv.antgroup.com/g6/eva-3d-data.json') .then((res) => res.json()) .then(({ nodes, edges }) => { const degree = new Map(); edges.forEach(({ source, target }) => { if (!degree.has(source)) degree.set(source, 0); if (!degree.has(target)) degree.set(target, 0); degree.set(source, degree.get(source) + 1); degree.set(target, degree.get(target) + 1); }); nodes.forEach((node) => { const { id } = node; Object.assign(node.data, { degree: degree.get(id) ?? 0 }); return node; }); return { nodes, edges }; }) .then((data) => { const graph = new Graph({ container: 'container', renderer, data, animation: false, node: { type: 'sphere', style: { materialType: 'phong', size: (d) => 50 + d.data.degree, x: (d) => d.data.x, y: (d) => d.data.y, z: (d) => d.data.z, }, palette: { color: 'tableau', type: 'group', field: 'cluster', }, }, edge: { type: 'line3d', style: { // Line3D joins centers directly; its self-edges must not use the 2D loop path. loop: false, lineWidth: 0.4, opacity: 0.4, stroke: '#fff', }, }, behaviors: ['observe-canvas-3d', 'zoom-canvas-3d'], plugins: [ { type: 'camera-setting', projectionMode: 'orthographic', near: 1, far: 10000, fov: 45, aspect: 1, }, { type: '3d-light', directional: { direction: [0, 0, 1], }, }, { type: 'background', background: '#000', }, ], }); return graph.draw().then(() => { const camera = graph.getCanvas().getCamera(); let frame; let counter = 0; const tick = () => { if (counter < 80) { camera.dolly(4); } camera.rotate(0.4, 0); counter++; frame = requestAnimationFrame(tick); if (counter > 160 && frame) { cancelAnimationFrame(frame); } }; tick(); }); }); ``` ### 精简太阳系 - zh page: https://g6.antv.antgroup.com/zh/examples/feature/default/lite-solar-system/ - Source path: examples/feature/default/demo/lite-solar-system.js ```js import { ExtensionCategory, Graph, register } from '@antv/g6'; import { Light, Sphere, renderer } from '@antv/g6-extension-3d'; register(ExtensionCategory.PLUGIN, 'light', Light); register(ExtensionCategory.NODE, 'sphere', Sphere); const graph = new Graph({ renderer, data: { nodes: [ { id: 'sum', style: { x: 300, y: 300, radius: 100, texture: 'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*-mZfQr8LtPUAAAAAAAAAAAAADmJ7AQ/original', }, }, { id: 'mars', style: { x: 430, y: 300, z: 0, radius: 20, texture: 'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*mniGTZktpecAAAAAAAAAAAAADmJ7AQ/original', }, }, { id: 'earth', style: { x: 500, y: 300, z: 0, radius: 30, texture: 'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*cdTdTI2bNl8AAAAAAAAAAAAADmJ7AQ/original', }, }, { id: 'jupiter', style: { x: 600, y: 300, z: 0, radius: 50, texture: 'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*t_mQSZYAT70AAAAAAAAAAAAADmJ7AQ/original', }, }, ], }, node: { type: 'sphere', style: { materialShininess: 0, labelText: (d) => d.id, labelFill: '#fff', }, }, plugins: [ { type: '3d-light', directional: { direction: [0, 0, 1], }, }, { type: 'background', backgroundImage: 'url(https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*M_OaRrzIZOEAAAAAAAAAAAAADmJ7AQ/original)', backgroundPosition: 'center', }, ], }); graph.draw().then(() => { const element = graph.context.element; const sum = element.getElement('sum'); const mars = element.getElement('mars'); const earth = element.getElement('earth'); const jupiter = element.getElement('jupiter'); const setRotation = (element, speed) => { setInterval(() => { element.rotate(0, -speed, 0); }, 30); }; setRotation(sum, 0.1); setRotation(mars, 0.8); setRotation(earth, 1); setRotation(jupiter, 0.5); const setRevolution = (element, center, speed) => { setInterval(() => { const [x, y, z] = element.getPosition(); const [cx, , cz] = center; const angle = (speed * Math.PI) / 180; const newX = (x - cx) * Math.cos(angle) + (z - cz) * Math.sin(angle) + cx; const newZ = -(x - cx) * Math.sin(angle) + (z - cz) * Math.cos(angle) + cz; element.setPosition(newX, y, newZ); }, 30); }; setRevolution(mars, [300, 300, 0], 1.5); setRevolution(earth, [300, 300, 0], 1); setRevolution(jupiter, [300, 300, 0], 0.5); }); ``` ### 主题切换 - zh page: https://g6.antv.antgroup.com/zh/examples/feature/default/theme/ - Source path: examples/feature/default/demo/theme.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const themes = { '🌞 Light': { theme: 'light', node: { style: { size: 4 }, palette: { type: 'group', field: 'cluster', }, }, plugins: [{ type: 'background', background: '#fff' }], }, '🌚 Dark': { theme: 'dark', node: { style: { size: 4 }, palette: { type: 'group', field: 'cluster', }, }, plugins: [{ type: 'background', background: '#000' }], }, '🌎 Blue': { theme: 'light', node: { style: { size: 4 }, palette: { type: 'group', field: 'cluster', color: 'blues', invert: true, }, }, plugins: [{ type: 'background', background: '#f3faff' }], }, '🌕 Yellow': { background: '#fcf9f1', theme: 'light', node: { style: { size: 4 }, palette: { type: 'group', field: 'cluster', color: ['#ffe7ba', '#ffd591', '#ffc069', '#ffa940', '#fa8c16', '#d46b08', '#ad4e00', '#873800', '#612500'], }, }, plugins: [{ type: 'background', background: '#fcf9f1' }], }, }; fetch('https://assets.antv.antgroup.com/g6/20000.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', animation: false, padding: 20, autoFit: 'view', theme: 'light', data, node: { style: { size: 4 }, palette: { type: 'group', field: 'cluster', }, }, behaviors: ['drag-canvas', 'zoom-canvas'], plugins: [{ type: 'background', background: '#fff' }], }); graph.render(); addPanel((gui) => { gui.add({ theme: '🌞 Light' }, 'theme', Object.keys(themes)).onChange((theme) => { graph.setOptions(themes[theme]); graph.draw(); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 信息密度 - zh page: https://g6.antv.antgroup.com/zh/examples/feature/default/unicorns-investors/ - Source path: examples/feature/default/demo/unicorns-investors.js ```js import { Graph } from '@antv/g6'; /** * Inspired by https://graphcommons.com/graphs/be8bc972-5b26-4f5c-837d-a34704f33a9e */ fetch('https://assets.antv.antgroup.com/g6/unicorns-investors.json') .then((res) => res.json()) .then((data) => { const size = (node) => Math.max(...node.style.size); const graph = new Graph({ data, autoFit: 'view', node: { style: { fillOpacity: 1, label: true, labelText: (d) => d.data?.name, labelBackground: true, icon: true, iconText: (d) => (d.data?.type === 'Investor' ? '💰' : '🦄️'), fill: (d) => (d.data?.type === 'Investor' ? '#6495ED' : '#FFA07A'), }, state: { inactive: { fillOpacity: 0.3, icon: false, label: false, }, }, }, edge: { style: { label: false, labelText: (d) => d.data?.type, labelBackground: true, }, state: { active: { label: true, }, inactive: { strokeOpacity: 0, }, }, }, layout: { type: 'd3-force', link: { distance: (edge) => size(edge.source) + size(edge.target) }, collide: { radius: (node) => size(node) }, manyBody: { strength: (node) => -4 * size(node) }, animation: false, }, transforms: [ { type: 'map-node-size', scale: 'linear', maxSize: 60, minSize: 20, mapLabelSize: [12, 24], }, ], behaviors: [ 'drag-canvas', 'zoom-canvas', function () { return { key: 'hover-activate', type: 'hover-activate', enable: (e) => e.targetType === 'node', degree: 1, inactiveState: 'inactive', onHover: (e) => { this.frontElement(e.target.id); e.view.setCursor('pointer'); }, onHoverEnd: (e) => { e.view.setCursor('default'); }, }; }, { type: 'fix-element-size', enable: true, }, 'auto-adapt-label', ], animation: false, }); graph.render(); }); const container = document.getElementById('container'); const descriptionDiv = document.createElement('div'); descriptionDiv.innerHTML = 'Network Map of 🦄 Unicorns and Their 💰Investors - 1086 nodes, 1247 edges'; container.appendChild(descriptionDiv); ``` ### 基本 Circular 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/circular/basic/ - Source path: examples/layout/circular/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 按照节点度数排序 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/circular/degree/ - Source path: examples/layout/circular/demo/degree.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', ordering: 'degree', }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 分割环形布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/circular/division/ - Source path: examples/layout/circular/demo/division.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', divisions: 5, radius: 200, startAngle: Math.PI / 4, endAngle: Math.PI, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 螺旋线布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/circular/spiral/ - Source path: examples/layout/circular/demo/spiral.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelText: (d) => d.id, labelFill: '#fff', labelPlacement: 'center', }, }, layout: { type: 'circular', startRadius: 10, endRadius: 300, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### ComboCombined 组合布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/combo-layout/combo-combined/ - Source path: examples/layout/combo-layout/demo/combo-combined.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/combo.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, layout: { type: 'combo-combined', comboPadding: 2, }, node: { style: { size: 20, labelText: (d) => d.id, }, palette: { type: 'group', field: (d) => d.combo, }, }, edge: { style: (model) => { const { size, color } = model.data; return { stroke: color || '#99ADD1', lineWidth: size || 1, }; }, }, behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas'], autoFit: 'view', }); graph.render(); }); ``` ### 紧凑树 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/compact-box/basic/ - Source path: examples/layout/compact-box/demo/basic.js ```js import { Graph, treeToGraphData } from '@antv/g6'; /** * If the node is a leaf node * @param {*} d - node data * @returns {boolean} - whether the node is a leaf node */ function isLeafNode(d) { return !d.children || d.children.length === 0; } fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], node: { style: { labelText: (d) => d.id, labelPlacement: (d) => (isLeafNode(d) ? 'right' : 'left'), labelBackground: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'compact-box', direction: 'LR', getHeight: function getHeight() { return 32; }, getWidth: function getWidth() { return 32; }, getVGap: function getVGap() { return 10; }, getHGap: function getHGap() { return 100; }, }, }); graph.render(); }); ``` ### 径向布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/compact-box/radial/ - Source path: examples/layout/compact-box/demo/radial.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], node: { style: { labelText: (d) => d.id, labelBackground: true, }, animation: { enter: false, }, }, layout: { type: 'compact-box', radial: true, direction: 'RL', getId: function getId(d) { return d.id; }, getHeight: () => { return 26; }, getWidth: () => { return 26; }, getVGap: () => { return 20; }, getHGap: () => { return 40; }, }, }); graph.render(); }); ``` ### 从上向下布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/compact-box/vertical/ - Source path: examples/layout/compact-box/demo/vertical.js ```js import { Graph, treeToGraphData } from '@antv/g6'; /** * If the node is a leaf node * @param {*} d - node data * @returns {boolean} - whether the node is a leaf node */ function isLeafNode(d) { return !d.children || d.children.length === 0; } fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], node: { style: (d) => { const style = { labelText: d.id, labelPlacement: 'right', labelOffsetX: 2, labelBackground: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }; if (isLeafNode(d)) { Object.assign(style, { labelTransform: [ ['rotate', 90], ['translate', 18], ], labelBaseline: 'center', labelTextAlign: 'left', }); } return style; }, animation: { enter: false, }, }, edge: { type: 'cubic-vertical', animation: { enter: false, }, }, layout: { type: 'compact-box', direction: 'TB', getHeight: function getHeight() { return 16; }, getWidth: function getWidth() { return 16; }, getVGap: function getVGap() { return 80; }, getHGap: function getHGap() { return 20; }, }, }); graph.render(); }); ``` ### Concentric 同心圆布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/concentric/basic/ - Source path: examples/layout/concentric/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/basement_prod/8dacf27e-e1bc-4522-b6d3-4b6d9b9ed7df.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, edge: { type: 'line', }, layout: { type: 'concentric', nodeSize: 32, maxLevelDiff: 0.5, sortBy: 'degree', preventOverlap: true, }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], animation: false, }); graph.render(); }); ``` ### 弧线图 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/custom/arc/ - Source path: examples/layout/custom/demo/arc.js ```js import { BaseEdge, BaseLayout, ExtensionCategory, Graph, register } from '@antv/g6'; class ArcLayout extends BaseLayout { async execute(data, options) { const { nodeSep = 20, nodeSize } = { ...this.options, ...options }; const { nodes } = data; return { nodes: nodes.map((node, index) => ({ id: node.id, style: { x: index * (nodeSep + nodeSize), y: 0, }, })), }; } } class ArcEdge extends BaseEdge { getKeyPath(attributes) { const [sourcePoint, targetPoint] = this.getEndpoints(attributes); const [sx, sy] = sourcePoint; const [tx] = targetPoint; const r = Math.abs(tx - sx) / 2; return [ ['M', sx, sy], ['A', r, r, 0, 0, sx < tx ? 1 : 0, tx, sy], ]; } } register(ExtensionCategory.LAYOUT, 'arc', ArcLayout); register(ExtensionCategory.EDGE, 'arc', ArcEdge); const palette = { analytics: 'rgb(158, 1, 66)', data: 'rgb(213, 62, 79)', animate: 'rgb(244, 109, 67)', display: 'rgb(253, 174, 97)', flex: 'rgb(254, 224, 139)', physics: 'rgb(230, 245, 152)', query: 'rgb(171, 221, 164)', scale: 'rgb(102, 194, 165)', util: 'rgb(50, 136, 189)', vis: 'rgb(94, 79, 162)', }; fetch('https://gw.alipayobjects.com/os/basement_prod/70cde3be-22e8-4291-98f1-4d5a5b75b62f.json') .then((res) => res.json()) .then((data) => { const getCluster = (id) => data.nodes.find((node) => node.id === id).cluster; const graph = new Graph({ container: 'container', data, autoFit: 'view', node: { style: { size: 20, fill: (d) => palette[d.cluster], ports: [{ position: 'top' }], labelText: (d) => d.name, labelTextAlign: 'start', labelTextBaseline: 'middle', labelTransform: [['rotate', 90]], }, }, edge: { type: 'arc', style: { stroke: (d) => `linear-gradient(${palette[getCluster(d.source)]}, ${palette[getCluster(d.source)]})`, strokeOpacity: 0.5, }, }, layout: { type: 'arc', nodeSize: 20, preLayout: true, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 二分图布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/custom/bi-graph/ - Source path: examples/layout/custom/demo/bi-graph.js ```js import { BaseLayout, ExtensionCategory, Graph, register } from '@antv/g6'; const data = { nodes: [ { id: '0', data: { cluster: 'A' } }, { id: '1', data: { cluster: 'A' } }, { id: '2', data: { cluster: 'A' } }, { id: '3', data: { cluster: 'A' } }, { id: '4', data: { cluster: 'A' } }, { id: '5', data: { cluster: 'A' } }, { id: '6', data: { cluster: 'B' } }, { id: '7', data: { cluster: 'B' } }, { id: '8', data: { cluster: 'B' } }, { id: '9', data: { cluster: 'B' } }, ], edges: [ { source: '0', target: '6' }, { source: '0', target: '7' }, { source: '0', target: '9' }, { source: '1', target: '6' }, { source: '1', target: '9' }, { source: '1', target: '7' }, { source: '2', target: '8' }, { source: '2', target: '9' }, { source: '2', target: '6' }, { source: '3', target: '8' }, { source: '4', target: '6' }, { source: '4', target: '7' }, { source: '5', target: '9' }, ], }; class BiLayout extends BaseLayout { id = 'bi-layout'; async execute(data, options) { const { sep = 100, nodeSep = 20, nodeSize = 32 } = { ...this.options, ...options }; const [A, B] = data.nodes.reduce( (acc, curr) => { acc[curr.data.cluster === 'A' ? 0 : 1].push(curr); return acc; }, [[], []], ); return { nodes: [ ...A.map((node, i) => ({ id: node.id, style: { x: i * (nodeSep + nodeSize), y: 0, }, })), ...B.map((node, i) => ({ id: node.id, style: { x: i * (nodeSep + nodeSize), y: sep, }, })), ], }; } } register(ExtensionCategory.LAYOUT, 'bi', BiLayout); const graph = new Graph({ container: 'container', data, autoFit: 'center', node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, palette: { type: 'group', field: 'cluster', color: ['#1783FF', '#D580FF'], }, }, layout: { type: 'bi', sep: 300, nodeSep: 20, nodeSize: 32, preLayout: true, }, behaviors: ['drag-canvas', 'drag-element', 'zoom-canvas'], }); graph.render(); ``` ### Dagre 流程图 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dagre/antv-dagre/ - Source path: examples/layout/dagre/demo/antv-dagre.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const data = { nodes: [ { id: '0' }, { id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }, { id: '6' }, { id: '7' }, { id: '8' }, { id: '9' }, ], edges: [ { source: '0', target: '1' }, { source: '0', target: '2' }, { source: '1', target: '4' }, { source: '0', target: '3' }, { source: '3', target: '4' }, { source: '4', target: '5' }, { source: '4', target: '6' }, { source: '5', target: '7' }, { source: '5', target: '8' }, { source: '8', target: '9' }, { source: '2', target: '9' }, { source: '3', target: '9' }, ], }; const graph = new Graph({ container: 'container', autoFit: 'view', data, layout: { type: 'antv-dagre', nodeSize: [60, 30], nodesep: 60, ranksep: 40, controlPoints: true, }, node: { type: 'rect', style: { size: [60, 30], radius: 8, labelText: (d) => d.id, labelBackground: true, }, }, edge: { type: 'polyline', }, behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas'], }); graph.render(); addPanel((gui) => { const config = { layout: 'default' }; const layouts = { default: { type: 'antv-dagre', nodesep: 100, ranksep: 70, controlPoints: true }, LR: { type: 'antv-dagre', rankdir: 'LR', align: 'DL', nodesep: 50, ranksep: 70, controlPoints: true }, 'LR&UL': { type: 'antv-dagre', rankdir: 'LR', align: 'UL', controlPoints: true, nodesep: 50, ranksep: 70 }, }; gui.add(config, 'layout', Object.keys(layouts)).onChange(async (layout) => { graph.setLayout(layouts[layout]); await graph.layout(); graph.fitCenter(); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 带有 Combo 的流程图 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dagre/antv-dagre-combo/ - Source path: examples/layout/dagre/demo/antv-dagre-combo.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/dagre-combo.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { type: 'rect', style: { size: [60, 30], radius: 8, labelText: (d) => d.id, labelBackground: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }, palette: { field: (d) => d.combo, }, }, edge: { type: 'cubic-vertical', style: { endArrow: true, }, }, combo: { type: 'rect', style: { radius: 8, labelText: (d) => d.id, }, }, layout: { type: 'antv-dagre', ranksep: 50, nodesep: 5, sortByCombo: true, }, behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### Dagre.js 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dagre/dagre/ - Source path: examples/layout/dagre/demo/dagre.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'kspacey', data: { label: 'Kevin Spacey', width: 144, height: 100 } }, { id: 'swilliams', data: { label: 'Saul Williams', width: 160, height: 100 } }, { id: 'bpitt', data: { label: 'Brad Pitt', width: 108, height: 100 } }, { id: 'hford', data: { label: 'Harrison Ford', width: 168, height: 100 } }, { id: 'lwilson', data: { label: 'Luke Wilson', width: 144, height: 100 } }, { id: 'kbacon', data: { label: 'Kevin Bacon', width: 121, height: 100 } }, ], edges: [ { id: 'kspacey->swilliams', source: 'kspacey', target: 'swilliams' }, { id: 'swilliams->kbacon', source: 'swilliams', target: 'kbacon' }, { id: 'bpitt->kbacon', source: 'bpitt', target: 'kbacon' }, { id: 'hford->lwilson', source: 'hford', target: 'lwilson' }, { id: 'lwilson->kbacon', source: 'lwilson', target: 'kbacon' }, ], }; const graph = new Graph({ autoFit: 'center', data, node: { type: 'rect', style: { size: (d) => [d.data.width, d.data.height], radius: 10, iconText: (d) => d.data.label, iconFontSize: 14, }, palette: { type: 'group', field: 'label', }, }, edge: { type: 'polyline', style: { router: { type: 'orth', }, }, }, layout: { type: 'dagre', }, }); graph.render(); ``` ### 生态树 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dendrogram/basic/ - Source path: examples/layout/dendrogram/demo/basic.js ```js import { Graph, treeToGraphData } from '@antv/g6'; /** * If the node is a leaf node * @param {*} d - node data * @returns {boolean} - whether the node is a leaf node */ function isLeafNode(d) { return !d.children || d.children.length === 0; } fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { style: { labelText: (d) => d.id, labelPlacement: (d) => (isLeafNode(d) ? 'right' : 'left'), labelBackground: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'dendrogram', direction: 'LR', // H / V / LR / RL / TB / BT nodeSep: 36, rankSep: 250, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 径向布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dendrogram/radial/ - Source path: examples/layout/dendrogram/demo/radial.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], node: { style: { labelText: (d) => d.id, labelBackground: true, }, animation: { enter: false, }, }, layout: { type: 'dendrogram', radial: true, nodeSep: 40, rankSep: 140, }, }); graph.render(); }); ``` ### 垂直布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/dendrogram/vertical/ - Source path: examples/layout/dendrogram/demo/vertical.js ```js import { Graph, treeToGraphData } from '@antv/g6'; /** * If the node is a leaf node * @param {*} d - node data * @returns {boolean} - whether the node is a leaf node */ function isLeafNode(d) { return !d.children || d.children.length === 0; } fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], node: { style: (d) => { const style = { labelText: d.id, labelPlacement: 'right', labelOffsetX: 2, labelBackground: true, ports: [{ placement: 'top' }, { placement: 'bottom' }], }; if (isLeafNode(d)) { Object.assign(style, { labelTransform: [ ['rotate', 90], ['translate', 18], ], labelBaseline: 'center', labelTextAlign: 'left', }); } return style; }, animation: { enter: false, }, }, edge: { type: 'cubic-vertical', animation: { enter: false, }, }, layout: { type: 'dendrogram', direction: 'TB', // H / V / LR / RL / TB / BT nodeSep: 50, rankSep: 120, }, }); graph.render(); }); ``` ### Fishbone 鱼骨布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/fishbone/basic/ - Source path: examples/layout/fishbone/demo/basic.js ```js import { Graph, treeToGraphData } from '@antv/g6'; const data = { id: 'Quality', children: [ { id: 'Machine', children: [{ id: 'Mill' }, { id: 'Mixer' }, { id: 'Metal Lathe', children: [{ id: 'Milling' }] }], }, { id: 'Method' }, { id: 'Material', children: [ { id: 'Masonite', children: [ { id: 'spearMint' }, { id: 'pepperMint', children: [{ id: 'test3' }] }, { id: 'test1', children: [{ id: 'test4' }] }, ], }, { id: 'Marscapone', children: [{ id: 'Malty' }, { id: 'Minty' }], }, { id: 'Meat', children: [{ id: 'Mutton' }] }, ], }, { id: 'Man Power', children: [ { id: 'Manager' }, { id: "Master's Student" }, { id: 'Magician' }, { id: 'Miner' }, { id: 'Magister', children: [{ id: 'Malpractice' }] }, { id: 'Massage Artist', children: [{ id: 'Masseur' }, { id: 'Masseuse' }], }, ], }, { id: 'Measurement', children: [{ id: 'Malleability' }], }, { id: 'Milieu', children: [{ id: 'Marine' }], }, ], }; export const layoutFishbone = async (context) => { const graph = new Graph({ ...context, container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { type: 'rect', style: { size: [32, 32], // fill: () => randomColor(), label: false, labelFill: '#262626', labelFontFamily: 'Gill Sans', labelMaxLines: 2, labelMaxWidth: '100%', labelPlacement: 'center', labelText: (d) => d.id, labelWordWrap: true, }, }, edge: { type: 'polyline', style: { lineWidth: 3, }, }, layout: { type: 'fishbone', vGap: 48, hGap: 48, direction: 'RL', }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], animation: false, }); await graph.render(); layoutFishbone.form = (panel) => { const config = { type: 'fishbone', direction: 'RL', }; return [ panel .add(config, 'direction', ['LR', 'RL']) .name('Direction') .onChange((value) => { graph.setLayout((prev) => ({ ...prev, direction: value })); graph.render(); }), ]; }; return graph; }; layoutFishbone(); ``` ### 3D 力导向布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/3d-force/ - Source path: examples/layout/force-directed/demo/3d-force.js ```js import { CameraSetting, ExtensionCategory, Graph, register } from '@antv/g6'; import { D3Force3DLayout, Light, Line3D, ObserveCanvas3D, Sphere, ZoomCanvas3D, renderer } from '@antv/g6-extension-3d'; register(ExtensionCategory.PLUGIN, '3d-light', Light); register(ExtensionCategory.NODE, 'sphere', Sphere); register(ExtensionCategory.EDGE, 'line3d', Line3D); register(ExtensionCategory.LAYOUT, 'd3-force-3d', D3Force3DLayout); register(ExtensionCategory.PLUGIN, 'camera-setting', CameraSetting); register(ExtensionCategory.BEHAVIOR, 'zoom-canvas-3d', ZoomCanvas3D); register(ExtensionCategory.BEHAVIOR, 'observe-canvas-3d', ObserveCanvas3D); fetch('https://assets.antv.antgroup.com/g6/d3-force-3d.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', renderer, data, layout: { type: 'd3-force-3d', }, node: { type: 'sphere', style: { materialType: 'phong', }, palette: { color: 'tableau', type: 'group', field: 'group', }, }, edge: { type: 'line3d', }, behaviors: ['observe-canvas-3d', 'zoom-canvas-3d'], plugins: [ { type: '3d-light', directional: { direction: [0, 0, 1], }, }, ], }); graph.render(); }); ``` ### Force Atlas 2 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/atlas2/ - Source path: examples/layout/force-directed/demo/atlas2.js ```js import { Graph } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'view', layout: { type: 'force-atlas2', preventOverlap: true, kr: 20, center: [250, 250], }, behaviors: ['zoom-canvas', 'drag-canvas'], autoResize: true, zoomRange: [0.1, 5], }); graph.render(); }); ``` ### 力导向气泡图 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/bubbles/ - Source path: examples/layout/force-directed/demo/bubbles.js ```js import { Graph, NodeEvent } from '@antv/g6'; const data = { nodes: [ { id: '0', label: '0', value: 10, cluster: 'a', description: 'this is node 0, \nand the value of it is 10', }, { id: '1', label: '1', value: 20, cluster: 'b', description: 'this is node 1, \nand the value of it is 20', }, { id: '2', label: '2', value: 5, cluster: 'a', description: 'this is node 2, \nand the value of it is 5', }, { id: '3', label: '3', value: 10, cluster: 'a', description: 'this is node 3, \nand the value of it is 10', }, { id: '4', label: '4', value: 12, cluster: 'c', subCluster: 'sb', description: 'this is node 4, \nand the value of it is 12', }, { id: '5', label: '5', value: 18, cluster: 'c', subCluster: 'sa', description: 'this is node 5, \nand the value of it is 18', }, { id: '6', label: '6', value: 3, cluster: 'c', subCluster: 'sa', description: 'this is node 6, \nand the value of it is 3', }, { id: '7', label: '7', value: 7, cluster: 'b', subCluster: 'sa', description: 'this is node 7, \nand the value of it is 7', }, { id: '8', label: '8', value: 21, cluster: 'd', subCluster: 'sb', description: 'this is node 8, \nand the value of it is 21', }, { id: '9', label: '9', value: 9, cluster: 'd', subCluster: 'sb', description: 'this is node 9, \nand the value of it is 9', }, ], edges: [], }; const oriSize = {}; const nodes = data.nodes; // randomize the node size nodes.forEach((node) => { node.size = Math.random() * 30 + 16; oriSize[node.id] = node.size; }); const graph = new Graph({ container: 'container', data, node: { style: { size: (d) => d.size, labelText: (d) => (d.size === 200 ? d.description : d.id), labelPlacement: 'middle', labelFill: '#fff', }, palette: { field: (d) => d.cluster, }, }, layout: { type: 'd3-force', collide: { radius: (d) => d.size / 2, strength: 0.7, }, manyBody: { strength: 30, }, }, behaviors: ['drag-element-force'], }); graph.on(NodeEvent.CLICK, async (e) => { const nodeId = e.target.id; const data = graph.getNodeData(nodeId); const size = data.size === oriSize[nodeId] ? 200 : oriSize[nodeId]; graph.updateNodeData([{ id: nodeId, size }]); await graph.layout(); }); graph.render(); ``` ### 弹性碰撞效果 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/collision/ - Source path: examples/layout/force-directed/demo/collision.js ```js import { BaseBehavior, ExtensionCategory, Graph, invokeLayoutMethod, register } from '@antv/g6'; function getData(width, size = 200) { const k = width / 200; const r = randomUniform(k * 2, k * 8); const n = 4; return { nodes: Array.from({ length: size }, (_, i) => ({ id: `${i}`, data: { r: r(), group: i && (i % n) + 1 } })), edges: [], }; } function randomUniform(min, max) { min = min == null ? 0 : +min; max = max == null ? 1 : +max; if (arguments.length === 1) (max = min), (min = 0); else max -= min; return function () { return Math.random() * max + min; }; } class CollisionElement extends BaseBehavior { constructor(context) { super(context, {}); this.onPointerMove = this.onPointerMove.bind(this); this.bindEvents(); } bindEvents() { this.context.graph.on('pointermove', this.onPointerMove); } onPointerMove(event) { const pos = this.context.graph.getCanvasByClient([event.client.x, event.client.y]); const layoutInstance = this.context.layout ?.getLayoutInstance() .find((layout) => ['d3-force', 'd3-force-3d'].includes(layout?.id)); if (layoutInstance) { invokeLayoutMethod(layoutInstance, 'setFixedPosition', '0', [...pos]); } } } register(ExtensionCategory.BEHAVIOR, 'collision-element', CollisionElement); const container = document.getElementById('container'); const width = container.scrollWidth; const graph = new Graph({ container, data: getData(width), layout: { type: 'd3-force', alphaTarget: 0.3, velocityDecay: 0.1, x: { strength: 0.01, }, y: { strength: 0.01, }, collide: { radius: (d) => d.data.r, iterations: 3, }, manyBody: { strength: (d, i) => (i ? 0 : (-width * 2) / 3), }, link: false, }, node: { style: { size: (d) => (d.id === '0' ? 0 : d.data.r * 2), }, palette: { color: 'tableau', type: 'group', field: (d) => d.data.group, }, }, behaviors: ['collision-element'], }); graph.render(); ``` ### D3 力导向布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/d3-force/ - Source path: examples/layout/force-directed/demo/d3-force.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.id, ports: [], }, palette: { type: 'group', field: 'cluster', }, }, layout: { type: 'd3-force', collide: { strength: 0.5, }, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 固定被做拽节点 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/drag-fixed/ - Source path: examples/layout/force-directed/demo/drag-fixed.js ```js import { Graph } from '@antv/g6'; const data = { nodes: new Array(10).fill(0).map((_, i) => ({ id: `${i}`, label: `${i}` })), edges: [ { source: '0', target: '1' }, { source: '0', target: '2' }, { source: '0', target: '3' }, { source: '0', target: '4' }, { source: '0', target: '5' }, { source: '0', target: '7' }, { source: '0', target: '8' }, { source: '0', target: '9' }, { source: '2', target: '3' }, { source: '4', target: '5' }, { source: '4', target: '6' }, { source: '5', target: '6' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.label, labelPlacement: 'middle', labelFill: '#fff', }, }, layout: { type: 'd3-force', link: { distance: 100, strength: 2, }, collide: { radius: 40, }, }, behaviors: [ { type: 'drag-element-force', fixed: true, }, ], }); graph.render(); ``` ### Force 聚类 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/force/ - Source path: examples/layout/force-directed/demo/force.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.id, ports: [], }, palette: { type: 'group', field: 'cluster', }, }, layout: { type: 'force', linkDistance: 50, clustering: true, nodeClusterBy: 'cluster', clusterNodeStrength: 70, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 定制不同节点的参数 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/functional-params/ - Source path: examples/layout/force-directed/demo/functional-params.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node0', size: 50 }, { id: 'node1', size: 30 }, { id: 'node2', size: 30 }, { id: 'node3', size: 30 }, { id: 'node4', size: 30, isLeaf: true }, { id: 'node5', size: 30, isLeaf: true }, { id: 'node6', size: 15, isLeaf: true }, { id: 'node7', size: 15, isLeaf: true }, { id: 'node8', size: 15, isLeaf: true }, { id: 'node9', size: 15, isLeaf: true }, { id: 'node10', size: 15, isLeaf: true }, { id: 'node11', size: 15, isLeaf: true }, { id: 'node12', size: 15, isLeaf: true }, { id: 'node13', size: 15, isLeaf: true }, { id: 'node14', size: 15, isLeaf: true }, { id: 'node15', size: 15, isLeaf: true }, { id: 'node16', size: 15, isLeaf: true }, ], edges: [ { source: 'node0', target: 'node1' }, { source: 'node0', target: 'node2' }, { source: 'node0', target: 'node3' }, { source: 'node0', target: 'node4' }, { source: 'node0', target: 'node5' }, { source: 'node1', target: 'node6' }, { source: 'node1', target: 'node7' }, { source: 'node2', target: 'node8' }, { source: 'node2', target: 'node9' }, { source: 'node2', target: 'node10' }, { source: 'node2', target: 'node11' }, { source: 'node2', target: 'node12' }, { source: 'node2', target: 'node13' }, { source: 'node3', target: 'node14' }, { source: 'node3', target: 'node15' }, { source: 'node3', target: 'node16' }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: (d) => d.size, }, }, layout: { type: 'd3-force', link: { distance: (d) => { if (d.source.id === 'node0') { return 100; } return 30; }, strength: (d) => { if (d.source.id === 'node1' || d.source.id === 'node2' || d.source.id === 'node3') { return 0.7; } return 0.1; }, }, manyBody: { strength: (d) => { if (d.isLeaf) { return -50; } return -10; }, }, }, behaviors: ['drag-element-force'], }); graph.render(); ``` ### 网格效果 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/mesh/ - Source path: examples/layout/force-directed/demo/mesh.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; function getData(size = 10) { const nodes = Array.from({ length: size * size }, (_, i) => ({ id: `${i}` })); const edges = []; for (let y = 0; y < size; ++y) { for (let x = 0; x < size; ++x) { if (y > 0) edges.push({ source: `${(y - 1) * size + x}`, target: `${y * size + x}` }); if (x > 0) edges.push({ source: `${y * size + (x - 1)}`, target: `${y * size + x}` }); } } return { nodes, edges }; } const graph = new Graph({ data: getData(), layout: { type: 'd3-force', manyBody: { strength: -30, }, link: { strength: 1, distance: 20, iterations: 10, }, }, node: { style: { size: 10, fill: '#000', }, }, edge: { style: { stroke: '#000', }, }, behaviors: [{ type: 'drag-element-force' }, 'zoom-canvas'], }); graph.render(); addPanel((gui) => { gui.add({ msg: 'Try to drag nodes' }, 'msg').name('Tips').disable(); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 力导向布局防止节点重叠 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/force-directed/prevent-overlap/ - Source path: examples/layout/force-directed/demo/prevent-overlap.js ```js import { Graph } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/relations.json') .then((res) => res.json()) .then((data) => { const nodes = data.nodes; // randomize the node size nodes.forEach((node) => { node.size = Math.random() * 30 + 5; }); const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { size: (d) => d.size, lineWidth: 1, }, }, layout: { type: 'd3-force', collide: { // Prevent nodes from overlapping by specifying a collision radius for each node. radius: (d) => d.size / 2, }, }, behaviors: ['drag-element-force'], }); graph.render(); }); ``` ### 基本 Fruchterman 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/fruchterman/basic/ - Source path: examples/layout/fruchterman/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, layout: { type: 'fruchterman', gravity: 5, speed: 5, animation: true, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### Fruchterman 聚类布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/fruchterman/cluster/ - Source path: examples/layout/fruchterman/demo/cluster.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, layout: { type: 'fruchterman', gravity: 5, speed: 5, clustering: true, nodeClusterBy: 'cluster', clusterGravity: 16, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, palette: { type: 'group', field: 'cluster', }, }, edge: { style: { endArrow: true, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 使用 GPU 加速 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/fruchterman/run-in-gpu/ - Source path: examples/layout/fruchterman/demo/run-in-gpu.js ```js import { Graph, register } from '@antv/g6'; import { FruchtermanLayout } from '@antv/layout-gpu'; register('layout', 'fruchterman-gpu', FruchtermanLayout); fetch('https://gw.alipayobjects.com/os/basement_prod/7bacd7d1-4119-4ac1-8be3-4c4b9bcbc25f.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, node: { style: { size: 5, }, }, edge: { style: { startArrow: true, }, }, layout: { type: 'fruchterman-gpu', speed: 20, gravity: 1, maxIteration: 10000, workerEnabled: true, }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 使用 Web-worker - zh page: https://g6.antv.antgroup.com/zh/examples/layout/fruchterman/run-in-web-worker/ - Source path: examples/layout/fruchterman/demo/run-in-web-worker.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph, GraphEvent } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, layout: { type: 'fruchterman', speed: 20, gravity: 10, maxIteration: 10000, workerEnabled: true, }, node: { style: { size: 20, labelText: (d) => d.id, labelPlacement: 'center', }, palette: { type: 'group', field: 'cluster', }, }, edge: { style: { stroke: '#ddd', }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); addPanel((gui) => { const msg = gui.add({ msg: 'Running...' }, 'msg').name('Tips').disable(); graph.on(GraphEvent.AFTER_LAYOUT, () => { msg.setValue('Layout Done!'); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### Grid 网格布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/grid/basic/ - Source path: examples/layout/grid/demo/basic.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, node: { style: { labelText: (d) => d.id, labelBackground: true, }, palette: { type: 'group', field: 'cluster', }, }, layout: { type: 'grid', sortBy: 'id', nodeSize: 32, }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], }); graph.render(); addPanel((gui) => { gui.add({ sortBy: 'id' }, 'sortBy', ['id', 'cluster']).onChange((type) => { graph.setLayout({ type: 'grid', sortBy: type, }); graph.layout(); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 子节点自动分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/indented/auto-side/ - Source path: examples/layout/indented/demo/auto-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; const getNodeSide = (graph, datum) => { const parentData = graph.getParentData(datum.id, 'tree'); if (!parentData) return 'center'; return datum.style.x > parentData.style.x ? 'right' : 'left'; }; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data: treeToGraphData(data), autoFit: 'view', node: { style: function (d) { const side = getNodeSide(this, d); return { labelText: d.id, labelPlacement: side === 'center' ? 'bottom' : side, labelBackground: true, ports: side === 'center' ? [{ placement: 'bottom' }] : side === 'right' ? [{ placement: 'bottom' }, { placement: 'left' }] : [{ placement: 'bottom' }, { placement: 'right' }], }; }, animation: { enter: false, }, }, edge: { type: 'polyline', style: { radius: 4, router: { type: 'orth', }, }, animation: { enter: false, }, }, layout: { type: 'indented', direction: 'H', indent: 80, preLayout: false, getHeight: () => 16, getWidth: () => 32, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 自定义子节点分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/indented/custom-side/ - Source path: examples/layout/indented/demo/custom-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; const getNodeSide = (graph, datum) => { const parentData = graph.getParentData(datum.id, 'tree'); if (!parentData) return 'center'; return datum.style.x > parentData.style.x ? 'right' : 'left'; }; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data: treeToGraphData(data), autoFit: 'view', node: { style: function (d) { const side = getNodeSide(this, d); return { labelText: d.id, labelPlacement: side === 'center' ? 'bottom' : side, labelBackground: true, ports: side === 'center' ? [{ placement: 'bottom' }] : side === 'right' ? [{ placement: 'bottom' }, { placement: 'left' }] : [{ placement: 'bottom' }, { placement: 'right' }], }; }, animation: { enter: false, }, }, edge: { type: 'polyline', style: { radius: 4, router: { type: 'orth', }, }, animation: { enter: false, }, }, layout: { type: 'indented', direction: 'H', indent: 80, preLayout: false, getHeight: () => 16, getWidth: () => 32, getSide: (d) => { if (d.id === 'Regression' || d.id === 'Classification') return 'left'; return 'right'; }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 子节点左侧分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/indented/left-side/ - Source path: examples/layout/indented/demo/left-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data: treeToGraphData(data), autoFit: 'view', node: { style: { labelText: (d) => d.id, labelPlacement: 'left', labelBackground: true, }, animation: { enter: false, }, }, edge: { type: 'polyline', style: { radius: 4, router: { type: 'orth', }, }, animation: { enter: false, }, }, layout: { type: 'indented', direction: 'RL', indent: 80, getHeight: () => 16, getWidth: () => 32, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 首子节点不换行 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/indented/no-drop-cap/ - Source path: examples/layout/indented/demo/no-drop-cap.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data: treeToGraphData(data), autoFit: 'view', node: { style: { labelText: (d) => d.id, labelPlacement: 'right', labelBackground: true, }, animation: { enter: false, }, }, edge: { type: 'polyline', style: { radius: 4, router: { type: 'orth', }, }, animation: { enter: false, }, }, layout: { type: 'indented', direction: 'LR', indent: 80, getHeight: () => 16, getWidth: () => 32, dropCap: false, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 子节点右侧分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/indented/right-side/ - Source path: examples/layout/indented/demo/right-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data: treeToGraphData(data), autoFit: 'view', node: { style: { labelText: (d) => d.id, labelPlacement: 'right', labelBackground: true, }, animation: { enter: false, }, }, edge: { type: 'polyline', style: { radius: 4, router: { type: 'orth', }, }, animation: { enter: false, }, }, layout: { type: 'indented', direction: 'LR', indent: 80, getHeight: () => 16, getWidth: () => 32, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element', 'collapse-expand'], }); graph.render(); }); ``` ### 基本 MDS 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mds/basic/ - Source path: examples/layout/mds/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/cluster.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', padding: 20, autoFit: 'view', data, node: { style: { labelFill: '#fff', labelText: (d) => d.id, labelPlacement: 'center', }, }, layout: { type: 'mds', nodeSize: 32, linkDistance: 100, }, behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### 数据动态切换 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mechanism/change-data/ - Source path: examples/layout/mechanism/demo/change-data.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const fetchData = async (type) => { if (type === 'large') { const data = await fetch('https://assets.antv.antgroup.com/g6/cluster.json').then((res) => res.json()); return data; } return { nodes: [{ id: 'b0' }, { id: 'b1' }, { id: 'b2' }, { id: 'b3' }, { id: 'b4' }, { id: 'b5' }], edges: [ { source: 'b0', target: 'b1' }, { source: 'b0', target: 'b2' }, { source: 'b0', target: 'b3' }, { source: 'b0', target: 'b4' }, { source: 'b0', target: 'b5' }, ], }; }; fetchData('small').then((data) => { const graph = new Graph({ container: 'container', behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], layout: { type: 'force', animated: true, linkDistance: 100, preventOverlap: true, }, data, }); graph.render(); addPanel((gui) => { gui.add({ type: 'small' }, 'type', ['small', 'large']).onChange((type) => { fetchData(type).then((data) => { graph.setData(data); graph.render(); }); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 布局切换 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mechanism/switch/ - Source path: examples/layout/mechanism/demo/switch.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', layout: { type: 'circular', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node'], data, }); graph.render(); addPanel((gui) => { gui .add({ layout: 'circular' }, 'layout', ['circular', 'grid', 'force', 'radial', 'concentric', 'mds']) .onChange((layout) => { const options = { circular: { type: 'circular' }, grid: { type: 'grid' }, force: { type: 'force', preventOverlap: true }, radial: { type: 'radial', preventOverlap: true }, concentric: { type: 'concentric' }, mds: { type: 'mds', linkDistance: 100 }, }; graph.stopLayout(); graph.layout(options[layout]); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 子节点自动分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mindmap/auto-side/ - Source path: examples/layout/mindmap/demo/auto-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; const getNodeSide = (graph, datum) => { const parentData = graph.getParentData(datum.id, 'tree'); if (!parentData) return 'center'; return datum.style.x > parentData.style.x ? 'right' : 'left'; }; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { style: { labelText: (d) => d.id, labelBackground: true, labelPlacement: function (d) { const side = getNodeSide(this, d); return side === 'center' ? 'right' : side; }, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'mindmap', direction: 'H', getHeight: () => 32, getWidth: () => 32, getVGap: () => 4, getHGap: () => 64, }, behaviors: ['collapse-expand', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### 自定义子节点分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mindmap/custom-side/ - Source path: examples/layout/mindmap/demo/custom-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; const getNodeSide = (graph, datum) => { const parentData = graph.getParentData(datum.id, 'tree'); if (!parentData) return 'center'; return datum.style.x > parentData.style.x ? 'right' : 'left'; }; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { style: { labelText: (d) => d.id, labelBackground: true, labelPlacement: function (d) { const side = getNodeSide(this, d); return side === 'center' ? 'right' : side; }, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'mindmap', direction: 'H', preLayout: false, getHeight: () => 32, getWidth: () => 32, getVGap: () => 4, getHGap: () => 64, getSide: (d) => { if (d.id === 'Classification') { return 'left'; } return 'right'; }, }, behaviors: ['collapse-expand', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### 子节点左侧分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mindmap/left-side/ - Source path: examples/layout/mindmap/demo/left-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { style: { labelText: (d) => d.id, labelPlacement: 'left', labelBackground: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'mindmap', direction: 'RL', getHeight: () => 32, getWidth: () => 32, getVGap: () => 4, getHGap: () => 100, }, behaviors: ['collapse-expand', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### 子节点右侧分布 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/mindmap/right-side/ - Source path: examples/layout/mindmap/demo/right-side.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data), node: { style: { labelText: (d) => d.id, labelPlacement: 'right', labelBackground: true, ports: [{ placement: 'right' }, { placement: 'left' }], }, animation: { enter: false, }, }, edge: { type: 'cubic-horizontal', animation: { enter: false, }, }, layout: { type: 'mindmap', direction: 'LR', getHeight: () => 32, getWidth: () => 32, getVGap: () => 4, getHGap: () => 100, }, behaviors: ['collapse-expand', 'drag-canvas', 'zoom-canvas'], }); graph.render(); }); ``` ### 基本 Radial 辐射布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/radial/basic/ - Source path: examples/layout/radial/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/radial.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'center', layout: { type: 'radial', nodeSize: 32, unitRadius: 100, linkDistance: 200, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 排序聚类 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/radial/cluster-sort/ - Source path: examples/layout/radial/demo/cluster-sort.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: '0', data: { type: 'a' } }, { id: '1', data: { type: 'a' } }, { id: '2', data: { type: 'a' } }, { id: '3', data: { type: 'a' } }, { id: '4', data: { type: 'c' } }, { id: '5', data: { type: 'a' } }, { id: '6', data: { type: 'b' } }, { id: '7', data: { type: 'b' } }, { id: '8', data: { type: 'c' } }, { id: '9', data: { type: 'd' } }, { id: '10', data: { type: 'd' } }, { id: '11', data: { type: 'b' } }, { id: '12', data: { type: 'c' } }, { id: '13', data: { type: 'b' } }, { id: '14', data: { type: 'd' } }, { id: '15', data: { type: 'd' } }, { id: '16', data: { type: 'b' } }, { id: '17', data: { type: 'c' } }, { id: '18', data: { type: 'c' } }, { id: '19', data: { type: 'b' } }, { id: '20', data: { type: 'b' } }, { id: '21', data: { type: 'd' } }, { id: '22', data: { type: 'd' } }, { id: '23', data: { type: 'd' } }, { id: '24', data: { type: 'a' } }, { id: '25', data: { type: 'a' } }, { id: '26', data: { type: 'b' } }, { id: '27', data: { type: 'b' } }, { id: '28', data: { type: 'd' } }, { id: '29', data: { type: 'c' } }, { id: '30', data: { type: 'c' } }, { id: '31', data: { type: 'b' } }, { id: '32', data: { type: 'b' } }, { id: '33', data: { type: 'a' } }, ], edges: [ { source: '0', target: '1' }, { source: '0', target: '2' }, { source: '0', target: '3' }, { source: '0', target: '4' }, { source: '0', target: '5' }, { source: '0', target: '7' }, { source: '0', target: '8' }, { source: '0', target: '9' }, { source: '0', target: '10' }, { source: '0', target: '11' }, { source: '0', target: '13' }, { source: '0', target: '14' }, { source: '0', target: '15' }, { source: '0', target: '16' }, { source: '2', target: '3' }, { source: '4', target: '5' }, { source: '4', target: '6' }, { source: '5', target: '6' }, { source: '7', target: '13' }, { source: '8', target: '14' }, { source: '9', target: '10' }, { source: '10', target: '22' }, { source: '10', target: '14' }, { source: '10', target: '12' }, { source: '10', target: '24' }, { source: '10', target: '21' }, { source: '10', target: '20' }, { source: '11', target: '24' }, { source: '11', target: '22' }, { source: '11', target: '14' }, { source: '12', target: '13' }, { source: '16', target: '17' }, { source: '16', target: '18' }, { source: '16', target: '21' }, { source: '16', target: '22' }, { source: '17', target: '18' }, { source: '17', target: '20' }, { source: '18', target: '19' }, { source: '19', target: '20' }, { source: '19', target: '33' }, { source: '19', target: '22' }, { source: '19', target: '23' }, { source: '20', target: '21' }, { source: '21', target: '22' }, { source: '22', target: '24' }, { source: '22', target: '25' }, { source: '22', target: '26' }, { source: '22', target: '23' }, { source: '22', target: '28' }, { source: '22', target: '30' }, { source: '22', target: '31' }, { source: '22', target: '32' }, { source: '22', target: '33' }, { source: '23', target: '28' }, { source: '23', target: '27' }, { source: '23', target: '29' }, { source: '23', target: '30' }, { source: '23', target: '31' }, { source: '23', target: '33' }, { source: '32', target: '33' }, ], }; const graph = new Graph({ container: 'container', autoFit: 'center', data, layout: { type: 'radial', nodeSize: 32, unitRadius: 90, linkDistance: 200, preventOverlap: true, sortBy: 'type', sortStrength: 50, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, palette: { type: 'group', field: 'type', }, }, edge: { style: { endArrow: true, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 防止节点重叠的非严格辐射布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/radial/non-strict-prevent-overlap/ - Source path: examples/layout/radial/demo/non-strict-prevent-overlap.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/radial.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'center', layout: { type: 'radial', nodeSize: 32, unitRadius: 90, linkDistance: 200, preventOverlap: true, maxPreventOverlapIteration: 100, strictRadial: false, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 防止节点重叠的严格辐射布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/radial/strict-prevent-overlap/ - Source path: examples/layout/radial/demo/strict-prevent-overlap.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/radial.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'center', layout: { type: 'radial', nodeSize: 32, unitRadius: 90, linkDistance: 200, preventOverlap: true, maxPreventOverlapIteration: 100, }, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); }); ``` ### 基本 Snake 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/snake/basic/ - Source path: examples/layout/snake/demo/basic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: new Array(16).fill(0).map((_, i) => ({ id: `${i}` })), edges: new Array(15).fill(0).map((_, i) => ({ source: `${i}`, target: `${i + 1}` })), }; const graph = new Graph({ container: 'container', data, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, layout: { type: 'snake', padding: 50, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 自定义间距的 Snake 布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/snake/gutter/ - Source path: examples/layout/snake/demo/gutter.js ```js import { Graph } from '@antv/g6'; const data = { nodes: new Array(16).fill(0).map((_, i) => ({ id: `${i}` })), edges: new Array(15).fill(0).map((_, i) => ({ source: `${i}`, target: `${i + 1}` })), }; const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.id, }, }, layout: { type: 'snake', cols: 3, rowGap: 80, colGap: 120, }, behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 子图布局 - zh page: https://g6.antv.antgroup.com/zh/examples/layout/sub-graph/basic/ - Source path: examples/layout/sub-graph/demo/basic.js ```js import { Graph } from '@antv/g6'; function generateArray(groups = 10, itemsPerGroup = 6) { const result = []; for (let i = 1; i <= groups; i++) { for (let j = 1; j <= itemsPerGroup; j++) { const id = `${i}-${j}`; result.push({ id, labelText: id, }); } } return result; } const data = generateArray(); const graph = new Graph({ container: 'container', data: { nodes: data, }, animation: false, autoFit: 'view', autoResize: true, node: { style: { labelFill: '#fff', labelPlacement: 'center', labelText: (d) => d.labelText, }, }, layout: Array.from({ length: 10 }, (_, i) => ({ type: 'circular', nodeFilter: (node) => node.id.startsWith(`${i + 1}-`), center: [ 1000 + (i % 5) * 850, // x坐标 i < 5 ? 100 : 1100, // y坐标 ], })), behaviors: ['drag-canvas', 'drag-element', 'zoom-canvas'], }); graph.render(); ``` ### 约 20000 元素 - zh page: https://g6.antv.antgroup.com/zh/examples/performance/massive-data/20000/ - Source path: examples/performance/massive-data/demo/20000.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/20000.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', animation: false, autoFit: 'view', data, node: { style: { size: 8, }, palette: { type: 'group', field: 'cluster', }, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 5000+ 元素 - zh page: https://g6.antv.antgroup.com/zh/examples/performance/massive-data/5000/ - Source path: examples/performance/massive-data/demo/5000.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/5000.json') .then((res) => res.json()) .then(async (data) => { const graph = new Graph({ container: 'container', animation: false, data, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], autoFit: 'view', }); await graph.render(); }); ``` ### 60000+ 元素 - zh page: https://g6.antv.antgroup.com/zh/examples/performance/massive-data/60000/ - Source path: examples/performance/massive-data/demo/60000.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/60000.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', animation: false, autoFit: 'view', data, node: { style: { size: 4, batchKey: 'node', }, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 背景图片 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/background/background/ - Source path: examples/plugin/background/demo/background.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', width: 800, height: 600, data, layout: { type: 'grid' }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'background', width: '800px', height: '600px', backgroundImage: 'url(https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*0Qq0ToQm1rEAAAAAAAAAAAAADmJ7AQ/original)', backgroundRepeat: 'no-repeat', backgroundSize: 'cover', opacity: 0.2, }, ], }); graph.render(); ``` ### 用气泡集包裹节点集 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/bubble-sets/basic/ - Source path: examples/plugin/bubble-sets/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/collection.json') .then((res) => res.json()) .then((data) => { const groupedNodesByCluster = data.nodes.reduce((acc, node) => { const cluster = node.data.cluster; acc[cluster] ||= []; acc[cluster].push(node.id); return acc; }, {}); const createStyle = (baseColor) => ({ fill: baseColor, stroke: baseColor, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: baseColor, labelBackgroundRadius: 5, }); const graph = new Graph({ container: 'container', data, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], node: { palette: { field: 'cluster' }, }, layout: { type: 'force', preventOverlap: true, linkDistance: (d) => { if (d.source === 'node0' || d.target === 'node0') { return 200; } return 80; }, }, plugins: [ { key: 'bubble-sets-a', type: 'bubble-sets', members: groupedNodesByCluster['a'], labelText: 'cluster-a', ...createStyle('#1783FF'), }, { key: 'bubble-sets-b', type: 'bubble-sets', members: groupedNodesByCluster['b'], labelText: 'cluster-b', ...createStyle('#00C9C9'), }, { key: 'bubble-sets-c', type: 'bubble-sets', members: groupedNodesByCluster['c'], labelText: 'cluster-c', ...createStyle('#F08F56'), }, { key: 'bubble-sets-d', type: 'bubble-sets', members: groupedNodesByCluster['d'], labelText: 'cluster-d', ...createStyle('#D580FF'), }, ], autoFit: 'center', }); graph.render(); }); ``` ### 上下文菜单 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/contextmenu/basic/ - Source path: examples/plugin/contextMenu/demo/basic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'contextmenu', trigger: 'contextmenu', // 'click' or 'contextmenu' onClick: (v) => { alert('You have clicked the「' + v + '」item'); }, getItems: () => { return [ { name: '展开一度关系', value: 'spread' }, { name: '查看详情', value: 'detail' }, ]; }, enable: (e) => e.targetType === 'node', }, ], }); graph.render(); ``` ### 边绑定 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/edge-bundling/basic/ - Source path: examples/plugin/edge-bundling/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/circular.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, layout: { type: 'circular', }, node: { style: { size: 20 } }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { key: 'edge-bundling', type: 'edge-bundling', bundleThreshold: 0.1, }, ], }); graph.render(); }); ``` ### 边过滤镜 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/edge-filter-lens/basic/ - Source path: examples/plugin/edge-filter-lens/demo/basic.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, autoFit: 'view', node: { style: { size: 16 }, palette: { field: (datum) => Math.floor(datum.style?.y / 60), }, }, edge: { style: { label: false, labelText: (d) => d.data.value?.toString(), stroke: '#ccc', }, }, plugins: [ { key: 'edge-filter-lens', type: 'edge-filter-lens', }, ], }); graph.render(); const config = { trigger: 'pointermove', scaleRBy: 'wheel', nodeType: 'both', }; addPanel((gui) => { gui .add(config, 'trigger', ['pointermove', 'click', 'drag']) .name('Trigger') .onChange((value) => { graph.updatePlugin({ key: 'edge-filter-lens', trigger: value, }); }); gui .add(config, 'scaleRBy', ['wheel', 'unset']) .name('Scale R by') .onChange((value) => { graph.updatePlugin({ key: 'edge-filter-lens', scaleRBy: value, }); }); gui .add(config, 'nodeType', ['source', 'target', 'both', 'either']) .name('Node Type') .onChange((value) => { graph.updatePlugin({ key: 'edge-filter-lens', nodeType: value, }); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 鱼眼放大镜 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/fisheye/basic/ - Source path: examples/plugin/fisheye/demo/basic.js ```js import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); fetch('https://assets.antv.antgroup.com/g6/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { size: (datum) => datum.id.length * 2 + 10, label: false, labelText: (datum) => datum.id, labelBackground: true, icon: false, iconFontFamily: 'iconfont', iconText: '\ue6f6', iconFill: '#fff', }, palette: { type: 'group', field: (datum) => datum.id, color: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }, }, edge: { style: { stroke: '#e2e2e2', }, }, plugins: [{ key: 'fisheye', type: 'fisheye', nodeStyle: { label: true, icon: true } }], }); graph.render(); }); ``` ### 自定义鱼眼放大镜 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/fisheye/custom/ - Source path: examples/plugin/fisheye/demo/custom.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph, iconfont } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); fetch('https://assets.antv.antgroup.com/g6/relations.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data, node: { style: { size: (datum) => datum.id.length * 2 + 10, label: false, labelText: (datum) => datum.id, labelBackground: true, icon: false, iconFontFamily: 'iconfont', iconText: '\ue6f6', iconFill: '#fff', }, palette: { type: 'group', field: (datum) => datum.id, color: ['#1783FF', '#00C9C9', '#F08F56', '#D580FF'], }, }, edge: { style: { stroke: '#e2e2e2', }, }, plugins: [ { key: 'fisheye', type: 'fisheye', trigger: 'click', scaleRBy: 'wheel', scaleDBy: 'drag', style: { fill: '#F08F56', stroke: '#666', lineDash: [5, 5] }, nodeStyle: { label: true, icon: true }, }, ], }); graph.render(); const config = { trigger: 'click', scaleRBy: 'wheel', scaleDBy: 'drag', showDPercent: true, borderless: true, }; addPanel((gui) => { gui .add(config, 'trigger', ['pointermove', 'click', 'drag']) .name('Trigger') .onChange((value) => { graph.updatePlugin({ key: 'fisheye', trigger: value, }); }); gui .add(config, 'scaleRBy', ['wheel', 'drag', 'unset']) .name('Scale R by') .onChange((value) => { graph.updatePlugin({ key: 'fisheye', scaleRBy: value, }); }); gui .add(config, 'scaleDBy', ['wheel', 'drag', 'unset']) .name('Scale D by') .onChange((value) => { graph.updatePlugin({ key: 'fisheye', scaleDBy: value, }); }); gui .add(config, 'showDPercent') .name('Show D Percent') .onChange((value) => { graph.updatePlugin({ key: 'fisheye', showDPercent: value, }); }); gui .add(config, 'borderless') .name('Borderless') .onChange((value) => { const style = value ? { fill: 'transparent', lineDash: 0, stroke: 'transparent' } : { fill: '#F08F56', lineDash: [5, 5], stroke: '#666' }; graph.updatePlugin({ key: 'fisheye', style, }); }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 全屏展示 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/fullscreen/basic/ - Source path: examples/plugin/fullscreen/demo/basic.js ```js import { Graph } from '@antv/g6'; const graph = new Graph({ data: { nodes: Array.from({ length: 20 }).map((_, i) => ({ id: `node${i}` })) }, autoFit: 'center', background: '#fff', plugins: [ { type: 'fullscreen', key: 'fullscreen', }, function () { const graph = this; return { type: 'toolbar', key: 'toolbar', position: 'top-left', onClick: (item) => { const fullscreenPlugin = graph.getPluginInstance('fullscreen'); if (item === 'request-fullscreen') { fullscreenPlugin.request(); } if (item === 'exit-fullscreen') { fullscreenPlugin.exit(); } }, getItems: () => { return [ { id: 'request-fullscreen', value: 'request-fullscreen' }, { id: 'exit-fullscreen', value: 'exit-fullscreen' }, ]; }, }; }, ], }); graph.render(); ``` ### 画布网格 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/grid-line/basic/ - Source path: examples/plugin/grid-line/demo/basic.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['drag-canvas'], plugins: [{ key: 'grid-line', type: 'grid-line', follow: false }], }); graph.render(); addPanel((gui) => { gui .add({ follow: false }, 'follow') .name('Follow') .onChange((value) => { graph.updatePlugin({ key: 'grid-line', follow: value, }); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 撤销重做 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/history/basic/ - Source path: examples/plugin/history/demo/basic.js ```js import { addPanel } from '/demo-runtime.ts'; import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [{ id: 'node-0', style: { x: 200, y: 150 } }], }, node: { style: { size: 60, labelText: 'Drag Me!', labelPlacement: 'middle', labelFill: '#fff', }, }, behaviors: ['drag-element'], plugins: [ { type: 'history', key: 'history', }, ], }); graph.render().then(() => { addPanel((gui) => { const history = graph.getPluginInstance('history'); const config = { undo: () => { if (history.canUndo()) history.undo(); }, redo: () => { if (history.canRedo()) history.redo(); }, }; gui.add(config, 'undo').name('⬅️ undo'); gui.add(config, 'redo').name('➡️ redo'); }); }); ``` ### src/demo-runtime.ts ```ts import { Graph } from '@antv/g6'; import GUI from 'lil-gui'; export function addPanel(renderPanel: (gui: GUI) => void) { const gui = new GUI({ container: document.body }); gui.title('Control'); Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' }); renderPanel(gui); addEventListener('pagehide', () => gui.destroy(), { once: true }); } export async function createGraph( options: ConstructorParameters[0], size: { width?: number; height?: number } = {}, renderPanel?: (gui: GUI, graph: Graph) => void, ) { const container = document.createElement('div'); Object.assign(container.style, { width: '100%', maxWidth: `${size.width || 600}px`, height: `${size.height || 400}px`, }); document.getElementById('container')!.append(container); const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true }); addEventListener('pagehide', () => graph.destroy(), { once: true }); await graph.render(); if (renderPanel) addPanel((gui) => renderPanel(gui, graph)); return container; } ``` ### 用轮廓包裹节点集合 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/hull/basic/ - Source path: examples/plugin/hull/demo/basic.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/collection.json') .then((res) => res.json()) .then((data) => { const groupedNodesByCluster = data.nodes.reduce((acc, node) => { const cluster = node.data.cluster; acc[cluster] ||= []; acc[cluster].push(node.id); return acc; }, {}); const createStyle = (baseColor) => ({ fill: baseColor, stroke: baseColor, labelFill: '#fff', labelPadding: 2, labelBackgroundFill: baseColor, labelBackgroundRadius: 5, }); const graph = new Graph({ container: 'container', data, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], node: { palette: { field: 'cluster' }, }, layout: { type: 'force', preventOverlap: true, linkDistance: (d) => { if (d.source === 'node0' || d.target === 'node0') { return 200; } return 80; }, }, plugins: [ { key: 'hull-a', type: 'hull', members: groupedNodesByCluster['a'], labelText: 'cluster-a', ...createStyle('#1783FF'), }, { key: 'hull-b', type: 'hull', members: groupedNodesByCluster['b'], labelText: 'cluster-b', ...createStyle('#00C9C9'), }, { key: 'hull-c', type: 'hull', members: groupedNodesByCluster['c'], labelText: 'cluster-c', ...createStyle('#F08F56'), }, { key: 'hull-d', type: 'hull', members: groupedNodesByCluster['d'], labelText: 'cluster-d', ...createStyle('#D580FF'), }, ], autoFit: 'center', }); graph.render(); }); ``` ### 默认图例 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/legend/basic/ - Source path: examples/plugin/legend/demo/basic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'node-1', type: 'circle', data: { cluster: 'node-type1' } }, { id: 'node-2', type: 'rect', data: { cluster: 'node-type2' } }, { id: 'node-3', type: 'triangle', data: { cluster: 'node-type3' } }, { id: 'node-4', type: 'diamond', data: { cluster: 'node-type4' } }, ], edges: [ { source: 'node-1', target: 'node-2', data: { cluster: 'edge-type1' } }, { source: 'node-1', target: 'node-4', data: { cluster: 'edge-type2' } }, { source: 'node-3', target: 'node-4' }, { source: 'node-2', target: 'node-4', data: { cluster: 'edge-type3' } }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: 32 }, palette: { field: 'cluster', }, }, layout: { type: 'force', }, plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', }, ], }); graph.render(); ``` ### 点击图例 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/legend/click/ - Source path: examples/plugin/legend/demo/click.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: '1', type: 'circle', data: { cluster: 'node-type1' } }, { id: '2', type: 'rect', data: { cluster: 'node-type2' } }, { id: '3', type: 'triangle', data: { cluster: 'node-type3' } }, { id: '4', type: 'diamond', data: { cluster: 'node-type4' } }, ], edges: [ { source: '1', target: '2', type: 'quadratic', data: { cluster: 'edge-type1' } }, { source: '1', target: '4', data: { cluster: 'edge-type2' } }, { source: '3', target: '4' }, { source: '2', target: '4', data: { cluster: 'edge-type3' } }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: 32 }, palette: { field: 'cluster' }, }, edge: { palette: { field: 'cluster' }, }, layout: { type: 'force', }, plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', trigger: 'click', gridRow: 1, gridCol: 4, itemLabelFontSize: 12, }, ], }); graph.render(); ``` ### 图例项样式 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/legend/style/ - Source path: examples/plugin/legend/demo/style.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: '1', type: 'circle', data: { cluster: 'node-type1' }, }, { id: '2', type: 'rect', data: { cluster: 'node-type2' }, }, { id: '3', type: 'triangle', data: { cluster: 'node-type3' }, }, { id: '4', type: 'diamond', data: { cluster: 'node-type4' }, }, ], edges: [ { id: '1-2', source: '1', target: '2', type: 'quadratic', data: { cluster: 'edge-type1' }, }, { id: '1-4', source: '1', target: '4', data: { cluster: 'edge-type2' }, }, { id: '3-4', source: '3', target: '4', }, { id: '2-4', source: '2', target: '4', data: { cluster: 'edge-type3' }, }, ], }; const graph = new Graph({ container: 'container', data, node: { style: { size: 32 }, palette: { field: 'cluster' }, }, edge: { palette: { field: 'cluster' }, }, layout: { type: 'force', }, plugins: [ { type: 'legend', nodeField: 'cluster', edgeField: 'cluster', titleText: 'Legend Title', trigger: 'click', position: 'top', gridCol: 3, itemLabelFontSize: 12, }, ], }); graph.render(); ``` ### 小地图 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/minimap/basic/ - Source path: examples/plugin/minimap/demo/basic.js ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: Array.from({ length: 20 }).map((_, i) => ({ id: `node${i}` })) }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], plugins: [ { type: 'minimap', size: [240, 160], }, ], node: { palette: 'spectral', }, layout: { type: 'circular', }, autoFit: 'view', }); graph.render(); ``` ### 支持自动吸附 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/snapline/autosnap/ - Source path: examples/plugin/snapline/demo/autoSnap.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { type: 'snapline', key: 'snapline', verticalLineStyle: { stroke: '#F08F56', lineWidth: 2 }, horizontalLineStyle: { stroke: '#17C76F', lineWidth: 2 }, offset: Infinity, autoSnap: true, }, ], }); graph.render(); ``` ### 对齐线 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/snapline/basic/ - Source path: examples/plugin/snapline/demo/basic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['drag-canvas', 'drag-element'], plugins: [ { type: 'snapline', key: 'snapline', verticalLineStyle: { stroke: '#F08F56', lineWidth: 2 }, horizontalLineStyle: { stroke: '#17C76F', lineWidth: 2 }, autoSnap: false, }, ], }); graph.render(); ``` ### 图表模式 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/timebar/chart/ - Source path: examples/plugin/timebar/demo/chart.js ```js import { Graph } from '@antv/g6'; const startTime = new Date('2023-08-01').getTime(); const diff = 3600 * 24 * 1000; const timebarData = [10, 2, 3, 4, 15, 10, 5, 0, 3, 1].map((value, index) => ({ time: new Date(startTime + index * diff), value, label: new Date(startTime + index * diff).toLocaleString(), })); const graphData = { nodes: new Array(49).fill(0).map((_, index) => ({ id: `node-${index}`, data: { timestamp: startTime + (index % 10) * diff, value: index % 20, label: new Date(startTime + (index % 10) * diff).toLocaleString(), }, })), edges: new Array(49).fill(0).map((_, i) => ({ id: `edge-${i}`, source: `node-${i % 30}`, target: `node-${(i % 20) + 29}`, data: { edgeType: 'e1', }, })), }; const graph = new Graph({ container: 'container', data: graphData, behaviors: ['drag-canvas', 'drag-element', 'zoom-canvas'], layout: { type: 'grid', cols: 7, }, plugins: [ { type: 'timebar', key: 'timebar', data: timebarData, width: 450, height: 100, loop: true, timebarType: 'chart', }, ], autoFit: 'view', padding: [10, 0, 160, 0], }); graph.render(); ``` ### 时间模式 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/timebar/time/ - Source path: examples/plugin/timebar/demo/time.js ```js import { Graph } from '@antv/g6'; const startTime = new Date('2023-08-01').getTime(); const diff = 3600 * 24 * 1000; const timebarData = [10, 2, 3, 4, 15, 10, 5, 0, 3, 1].map((value, index) => ({ time: new Date(startTime + index * diff), value, label: new Date(startTime + index * diff).toLocaleString(), })); const graphData = { nodes: new Array(49).fill(0).map((_, index) => ({ id: `node-${index}`, data: { timestamp: startTime + (index % 10) * diff, value: index % 20, label: new Date(startTime + (index % 10) * diff).toLocaleString(), }, })), edges: new Array(49).fill(0).map((_, i) => ({ id: `edge-${i}`, source: `node-${i % 30}`, target: `node-${(i % 20) + 29}`, data: { edgeType: 'e1', }, })), }; const graph = new Graph({ container: 'container', data: graphData, behaviors: ['drag-canvas', 'drag-element', 'zoom-canvas'], layout: { type: 'grid', cols: 7, }, plugins: [ { type: 'timebar', key: 'timebar', data: timebarData, width: 450, loop: true, }, ], autoFit: 'view', padding: [10, 0, 65, 0], }); graph.render(); ``` ### 工具栏 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/toolbar/basic/ - Source path: examples/plugin/toolbar/demo/basic.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'toolbar', position: 'top-left', onClick: (item) => { alert('item clicked:' + item); }, getItems: () => { // G6 内置了 9 个 icon,分别是 zoom-in、zoom-out、redo、undo、edit、delete、auto-fit、export、reset return [ { id: 'zoom-in', value: 'zoom-in' }, { id: 'zoom-out', value: 'zoom-out' }, { id: 'redo', value: 'redo' }, { id: 'undo', value: 'undo' }, { id: 'edit', value: 'edit' }, { id: 'delete', value: 'delete' }, { id: 'auto-fit', value: 'auto-fit' }, { id: 'export', value: 'export' }, { id: 'reset', value: 'reset' }, ]; }, }, ], }); graph.render(); ``` ### 自定义工具栏 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/toolbar/custom/ - Source path: examples/plugin/toolbar/demo/custom.js ```js import { Graph } from '@antv/g6'; // Use your own iconfont. const iconFont = document.createElement('script'); iconFont.src = '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js'; document.head.appendChild(iconFont); const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'toolbar', position: 'right-top', onClick: (item) => { alert('item clicked:' + item); }, getItems: () => { return [ { id: 'icon-xinjian', value: 'new' }, { id: 'icon-fenxiang', value: 'share' }, { id: 'icon-chexiao', value: 'undo' }, ]; }, }, ], }); graph.render(); ``` ### 提示框 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/tooltip/basic/ - Source path: examples/plugin/tooltip/demo/basic.js ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: '0', data: { label: 'node-0', description: 'This is node-0.' } }, { id: '1', data: { label: 'node-1', description: 'This is node-1.' } }, { id: '2', data: { label: 'node-2', description: 'This is node-2.' } }, { id: '3', data: { label: 'node-3', description: 'This is node-3.' } }, { id: '4', data: { label: 'node-4', description: 'This is node-4.' } }, { id: '5', data: { label: 'node-5', description: 'This is node-5.' } }, ], edges: [ { source: '0', target: '1', data: { description: 'This is edge from node 0 to node 1.' } }, { source: '0', target: '2', data: { description: 'This is edge from node 0 to node 2.' } }, { source: '0', target: '3', data: { description: 'This is edge from node 0 to node 3.' } }, { source: '0', target: '4', data: { description: 'This is edge from node 0 to node 4.' } }, { source: '0', target: '5', data: { description: 'This is edge from node 0 to node 5.' } }, ], }, layout: { type: 'grid', }, plugins: [ { type: 'tooltip', getContent: (e, items) => { let result = `

Custom Content

`; items.forEach((item) => { result += `

Type: ${item.data.description}

`; }); return result; }, }, ], behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 点击触发 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/tooltip/click/ - Source path: examples/plugin/tooltip/demo/click.js ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: '0', data: { label: 'node-0', description: 'This is node-0.' } }, { id: '1', data: { label: 'node-1', description: 'This is node-1.' } }, { id: '2', data: { label: 'node-2', description: 'This is node-2.' } }, { id: '3', data: { label: 'node-3', description: 'This is node-3.' } }, { id: '4', data: { label: 'node-4', description: 'This is node-4.' } }, { id: '5', data: { label: 'node-5', description: 'This is node-5.' } }, ], edges: [ { source: '0', target: '1', data: { description: 'This is edge from node 0 to node 1.' } }, { source: '0', target: '2', data: { description: 'This is edge from node 0 to node 2.' } }, { source: '0', target: '3', data: { description: 'This is edge from node 0 to node 3.' } }, { source: '0', target: '4', data: { description: 'This is edge from node 0 to node 4.' } }, { source: '0', target: '5', data: { description: 'This is edge from node 0 to node 5.' } }, ], }, layout: { type: 'grid', }, plugins: [ { type: 'tooltip', trigger: 'click', getContent: (e, items) => { let result = `

Custom Content

`; items.forEach((item) => { result += `

Type: ${item.data.description}

`; }); return result; }, }, ], behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 鼠标移入和点击同一元素时显示不同的提示框 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/tooltip/dual/ - Source path: examples/plugin/tooltip/demo/dual.js ```js import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', data: { nodes: [ { id: '0', data: { label: 'node-0', description: 'This is node-0.' } }, { id: '1', data: { label: 'node-1', description: 'This is node-1.' } }, { id: '2', data: { label: 'node-2', description: 'This is node-2.' } }, { id: '3', data: { label: 'node-3', description: 'This is node-3.' } }, { id: '4', data: { label: 'node-4', description: 'This is node-4.' } }, { id: '5', data: { label: 'node-5', description: 'This is node-5.' } }, ], edges: [ { source: '0', target: '1', data: { description: 'This is edge from node 0 to node 1.' } }, { source: '0', target: '2', data: { description: 'This is edge from node 0 to node 2.' } }, { source: '0', target: '3', data: { description: 'This is edge from node 0 to node 3.' } }, { source: '0', target: '4', data: { description: 'This is edge from node 0 to node 4.' } }, { source: '0', target: '5', data: { description: 'This is edge from node 0 to node 5.' } }, ], }, layout: { type: 'grid', }, plugins: [ function () { return { key: 'tooltip-click', type: 'tooltip', trigger: 'click', getContent: (evt, items) => { return `
click ${items[0].id}
`; }, onOpenChange: (open) => { const tooltip = this.getPluginInstance('tooltip-hover'); if (tooltip && open) tooltip.hide(); }, }; }, function () { return { key: 'tooltip-hover', type: 'tooltip', trigger: 'hover', enable: (e) => { const tooltip = this.getPluginInstance('tooltip-click'); return e.target.id !== tooltip.currentTarget; }, getContent: (evt, items) => { return `
hover ${items[0].id}
`; }, onOpenChange: (open) => { const tooltip = this.getPluginInstance('tooltip-click'); if (tooltip && open) { tooltip.hide(); } }, }; }, ], behaviors: ['drag-canvas', 'drag-element'], }); graph.render(); ``` ### 重复图片 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/watermark/repeat/ - Source path: examples/plugin/watermark/demo/repeat.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid', }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'watermark', width: 200, height: 100, rotate: Math.PI / 12, imageURL: 'https://gw.alipayobjects.com/os/s/prod/antv/assets/image/logo-with-text-73b8a.svg', }, ], }); graph.render(); ``` ### 文本水印 - zh page: https://g6.antv.antgroup.com/zh/examples/plugin/watermark/text/ - Source path: examples/plugin/watermark/demo/text.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [{ id: 'node-0' }, { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }], edges: [ { source: 'node-0', target: 'node-1' }, { source: 'node-0', target: 'node-2' }, { source: 'node-0', target: 'node-3' }, { source: 'node-0', target: 'node-4' }, { source: 'node-1', target: 'node-0' }, { source: 'node-2', target: 'node-0' }, { source: 'node-3', target: 'node-0' }, { source: 'node-4', target: 'node-0' }, { source: 'node-5', target: 'node-0' }, ], }; const graph = new Graph({ container: 'container', data, layout: { type: 'grid' }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], plugins: [ { type: 'watermark', text: 'G6: Graph Visualization', textFontSize: 14, textFontFamily: 'Microsoft YaHei', fill: 'rgba(0, 0, 0, 0.1)', rotate: Math.PI / 12, }, ], }); graph.render(); ``` ### 英格兰阵容 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/battle-array/ - Source path: examples/scene-case/default/demo/battle-array.jsx ```jsx import { ExtensionCategory, Graph, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; import styled from 'styled-components'; const Player = styled.div` width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; `; const Shirt = styled.div` width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; position: relative; img { width: 40px; position: absolute; left: 0; top: 0; } `; const Number = styled.div` color: #fff; font-family: 'DingTalk-JinBuTi'; font-size: 10px; top: 20px; left: 15px; z-index: 1; margin-top: 16px; margin-left: -2px; `; const Label = styled.div` max-width: 120px; padding: 0 8px; color: #fff; font-size: 10px; background-image: url('https://mdn.alipayobjects.com/huamei_92awrc/afts/img/A*s2csQ48M0AkAAAAAAAAAAAAADsvfAQ/original'); background-repeat: no-repeat; background-size: cover; display: flex; justify-content: center; overflow: hidden; text-overflow: ellipsis; `; const PlayerNode = ({ playerInfo }) => { const { isTeamA, player_shirtnumber, player_name } = playerInfo; return ( {player_shirtnumber} ); }; register(ExtensionCategory.NODE, 'react', ReactNode); const data = { nodes: [ { id: '50251337', x: 50, y: 68, isTeamA: '1', player_id: '50251337', player_shirtnumber: '19', player_enName: 'Justin Kluivert', player_name: '尤斯廷-克鲁伊维特', }, { id: '50436685', x: 25, y: 68, isTeamA: '1', player_id: '50436685', player_shirtnumber: '24', player_enName: 'Antoine Semenyo', player_name: '塞门约', }, { id: '50204813', x: 50, y: 89, isTeamA: '1', player_id: '50204813', player_shirtnumber: '9', player_enName: 'Dominic Solanke', player_name: '索兰克', }, { id: '50250175', x: 75, y: 68, isTeamA: '1', player_id: '50250175', player_shirtnumber: '16', player_enName: 'Marcus Tavernier', player_name: '塔韦尼耶', }, { id: '50213675', x: 65, y: 48, isTeamA: '1', player_id: '50213675', player_shirtnumber: '4', player_enName: 'Lewis Cook', player_name: '刘易斯-库克', }, { id: '50186648', x: 35, y: 48, isTeamA: '1', player_id: '50186648', player_shirtnumber: '10', player_enName: 'Ryan Christie', player_name: '克里斯蒂', }, { id: '50279448', x: 38, y: 28, isTeamA: '1', player_id: '50279448', player_shirtnumber: '6', player_enName: 'Chris Mepham', player_name: '迈帕姆', }, { id: '50061646', x: 15, y: 28, isTeamA: '1', player_id: '50061646', player_shirtnumber: '15', player_enName: 'Adam Smith', player_name: '亚当-史密斯', }, { id: '50472140', x: 62, y: 28, isTeamA: '1', player_id: '50472140', player_shirtnumber: '27', player_enName: 'Ilya Zabarnyi', player_name: '扎巴尔尼', }, { id: '50544346', x: 85, y: 28, isTeamA: '1', player_id: '50544346', player_shirtnumber: '3', player_enName: 'Milos Kerkez', player_name: '科尔克兹', }, { id: '50062598', x: 50, y: 7, isTeamA: '1', player_id: '50062598', player_shirtnumber: '1', player_enName: 'Neto', player_name: '内托', }, ], }; const graph = new Graph({ container: 'container', data, animation: false, x: 10, y: 50, width: 480, height: 720, node: { type: 'react', style: { size: [120, 60], ports: [{ placement: 'center' }], x: (d) => d.x * 3.5, y: (d) => d.y * 3.5, fill: 'transparent', component: (data) => , }, }, plugins: [ { type: 'background', width: '480px', height: '720px', backgroundImage: 'url(https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*EmPXQLrX2xIAAAAAAAAAAAAADmJ7AQ/original)', backgroundRepeat: 'no-repeat', backgroundSize: 'contain', opacity: 1, }, ], }); graph.render(); ``` ### 资金流向图 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/fund-flow/ - Source path: examples/scene-case/default/demo/fund-flow.js ```js import { Rect as GRect, Text as GText } from '@antv/g'; import { Badge, CommonEvent, ExtensionCategory, Graph, GraphEvent, iconfont, Label, Rect, register, treeToGraphData, } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const COLORS = { B: '#1783FF', R: '#F46649', Y: '#DB9D0D', G: '#60C42D', DI: '#A7A7A7', }; const GREY_COLOR = '#CED4D9'; class TreeNode extends Rect { get data() { return this.context.model.getNodeLikeDatum(this.id); } get childrenData() { return this.context.model.getChildrenData(this.id); } getLabelStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: -width / 2 + 8, y: -height / 2 + 16, text: this.data.name, fontSize: 12, opacity: 0.85, fill: '#000', cursor: 'pointer', }; } getPriceStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: -width / 2 + 8, y: height / 2 - 8, text: this.data.label, fontSize: 16, fill: '#000', opacity: 0.85, }; } drawPriceShape(attributes, container) { const priceStyle = this.getPriceStyle(attributes); this.upsert('price', GText, priceStyle, container); } getCurrencyStyle(attributes) { const [, height] = this.getSize(attributes); return { x: this.shapeMap['price'].getLocalBounds().max[0] + 4, y: height / 2 - 8, text: this.data.currency, fontSize: 12, fill: '#000', opacity: 0.75, }; } drawCurrencyShape(attributes, container) { const currencyStyle = this.getCurrencyStyle(attributes); this.upsert('currency', GText, currencyStyle, container); } getPercentStyle(attributes) { const [width, height] = this.getSize(attributes); return { x: width / 2 - 4, y: height / 2 - 8, text: `${((Number(this.data.variableValue) || 0) * 100).toFixed(2)}%`, fontSize: 12, textAlign: 'right', fill: COLORS[this.data.status], }; } drawPercentShape(attributes, container) { const percentStyle = this.getPercentStyle(attributes); this.upsert('percent', GText, percentStyle, container); } getTriangleStyle(attributes) { const percentMinX = this.shapeMap['percent'].getLocalBounds().min[0]; const [, height] = this.getSize(attributes); return { fill: COLORS[this.data.status], x: this.data.variableUp ? percentMinX - 18 : percentMinX, y: height / 2 - 16, fontFamily: 'iconfont', fontSize: 16, text: '\ue62d', transform: this.data.variableUp ? [] : [['rotate', 180]], }; } drawTriangleShape(attributes, container) { const triangleStyle = this.getTriangleStyle(attributes); this.upsert('triangle', Label, triangleStyle, container); } getVariableStyle(attributes) { const [, height] = this.getSize(attributes); return { fill: '#000', fontSize: 12, opacity: 0.45, text: this.data.variableName, textAlign: 'right', x: this.shapeMap['triangle'].getLocalBounds().min[0] - 4, y: height / 2 - 8, }; } drawVariableShape(attributes, container) { const variableStyle = this.getVariableStyle(attributes); this.upsert('variable', GText, variableStyle, container); } getCollapseStyle(attributes) { if (this.childrenData.length === 0) return false; const { collapsed } = attributes; const [width, height] = this.getSize(attributes); return { backgroundFill: '#fff', backgroundHeight: 16, backgroundLineWidth: 1, backgroundRadius: 0, backgroundStroke: GREY_COLOR, backgroundWidth: 16, cursor: 'pointer', fill: GREY_COLOR, fontSize: 16, text: collapsed ? '+' : '-', textAlign: 'center', textBaseline: 'middle', x: width / 2, y: 0, }; } drawCollapseShape(attributes, container) { const collapseStyle = this.getCollapseStyle(attributes); const btn = this.upsert('collapse', Badge, collapseStyle, container); if (btn && !Reflect.has(btn, '__bind__')) { Reflect.set(btn, '__bind__', true); btn.addEventListener(CommonEvent.CLICK, () => { const { collapsed } = this.attributes; const graph = this.context.graph; if (collapsed) graph.expandElement(this.id); else graph.collapseElement(this.id); }); } } getProcessBarStyle(attributes) { const { rate, status } = this.data; const { radius } = attributes; const color = COLORS[status]; const percent = `${Number(rate) * 100}%`; const [width, height] = this.getSize(attributes); return { x: -width / 2, y: height / 2 - 4, width: width, height: 4, radius: [0, 0, radius, radius], fill: `linear-gradient(to right, ${color} ${percent}, ${GREY_COLOR} ${percent})`, }; } drawProcessBarShape(attributes, container) { const processBarStyle = this.getProcessBarStyle(attributes); this.upsert('process-bar', GRect, processBarStyle, container); } getKeyStyle(attributes) { const keyStyle = super.getKeyStyle(attributes); return { ...keyStyle, fill: '#fff', lineWidth: 1, stroke: GREY_COLOR, }; } render(attributes = this.parsedAttributes, container) { super.render(attributes, container); this.drawPriceShape(attributes, container); this.drawCurrencyShape(attributes, container); this.drawPercentShape(attributes, container); this.drawTriangleShape(attributes, container); this.drawVariableShape(attributes, container); this.drawProcessBarShape(attributes, container); this.drawCollapseShape(attributes, container); } } register(ExtensionCategory.NODE, 'tree-node', TreeNode); fetch('https://assets.antv.antgroup.com/g6/decision-tree.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', data: treeToGraphData(data, { getNodeData: (datum, depth) => { if (!datum.style) datum.style = {}; datum.style.collapsed = depth >= 2; if (!datum.children) return datum; const { children, ...restDatum } = datum; return { ...restDatum, children: children.map((child) => child.id) }; }, }), node: { type: 'tree-node', style: { size: [202, 60], ports: [{ placement: 'left' }, { placement: 'right' }], radius: 4, }, }, edge: { type: 'cubic-horizontal', style: { stroke: GREY_COLOR, }, }, layout: { type: 'indented', direction: 'LR', dropCap: false, indent: 300, getHeight: () => 60, preLayout: false, }, behaviors: ['zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 音乐节 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/music-festival/ - Source path: examples/scene-case/default/demo/music-festival.js ```js import { Graph } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/music-festival.json') .then((res) => res.json()) .then((data) => { const map = new Map(); data.forEach((datum) => { const { actors, venuecity } = datum; actors.forEach((actor) => { if (!map.has(actor)) map.set(actor, new Set([venuecity])); else map.get(actor).add(venuecity); }); }); const nodes = Array.from(map) .filter(([, city]) => city.size >= 2) .sort((a, b) => -a[1].size + b[1].size) .map(([name, city]) => ({ id: name, data: { city: Array.from(city), value: city.size, }, })); return { nodes }; }) .then((data) => { const graph = new Graph({ container: 'container', data, node: { type: 'rect', style: { size: [100, 20], radius: 5, iconText: (d) => d.id, iconFill: '#000', iconWordWrap: true, iconWordWrapWidth: 80, iconFontSize: 15, iconTextOverflow: '...', iconMaxLines: 1, labelText: (d) => d.data.city.join('\n'), labelFontSize: 12, labelDy: 2, labelFill: '#fff', }, palette: { type: 'group', field: 'value', color: [ '#FCE75A', '#F5DB75', '#EFCF90', '#E8C3AB', '#E1B7C6', '#DBABE0', '#D49FFB', '#CD93FF', '#B981F2', '#7E45E8', ], }, }, layout: { type: 'grid', nodeSize: [100, 120], sortBy: 'order', cols: 5, }, behaviors: [{ type: 'scroll-canvas', direction: 'y' }], plugins: [ { type: 'background', background: '#000', }, ], }); graph.render(); }); ``` ### 组织架构 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/organization-chart/ - Source path: examples/scene-case/default/demo/organization-chart.js ```js import { Badge, BaseBehavior, ExtensionCategory, Graph, GraphEvent, Label, Rect, register } from '@antv/g6'; const statusColors = { online: '#17BEBB', busy: '#E36397', offline: '#B7AD99', }; const DEFAULT_LEVEL = 'detailed'; /** * Draw a chart node with different ui based on the zoom level. */ class ChartNode extends Rect { get data() { return this.context.model.getElementDataById(this.id).data; } get level() { return this.data.level || DEFAULT_LEVEL; } getLabelStyle() { const text = this.data.name; const labelStyle = this.level === 'overview' ? { fill: '#fff', fontSize: 20, fontWeight: 600, textAlign: 'center', transform: [['translate', 0, 0]], } : { fill: '#2078B4', fontSize: 14, fontWeight: 400, textAlign: 'left', transform: [['translate', -65, -15]], }; return { text, ...labelStyle }; } getKeyStyle(attributes) { return { ...super.getKeyStyle(attributes), fill: this.level === 'overview' ? statusColors[this.data.status] : '#fff', }; } getPositionStyle(attributes) { if (this.level === 'overview') return false; return { text: this.data.position, fontSize: 8, fontWeight: 400, textTransform: 'uppercase', fill: '#343f4a', textAlign: 'left', transform: [['translate', -65, 0]], }; } drawPositionShape(attributes, container) { const positionStyle = this.getPositionStyle(attributes); this.upsert('position', Label, positionStyle, container); } getStatusStyle(attributes) { if (this.level === 'overview') return false; return { text: this.data.status, fontSize: 8, textAlign: 'left', transform: [['translate', 40, -16]], padding: [0, 4], fill: '#fff', backgroundFill: statusColors[this.data.status], }; } drawStatusShape(attributes, container) { const statusStyle = this.getStatusStyle(attributes); this.upsert('status', Badge, statusStyle, container); } getPhoneStyle(attributes) { if (this.level === 'overview') return false; return { text: this.data.phone, fontSize: 8, fontWeight: 300, textAlign: 'left', transform: [['translate', -65, 20]], }; } drawPhoneShape(attributes, container) { const style = this.getPhoneStyle(attributes); this.upsert('phone', Label, style, container); } render(attributes = this.parsedAttributes, container = this) { super.render(attributes, container); this.drawPositionShape(attributes, container); this.drawStatusShape(attributes, container); this.drawPhoneShape(attributes, container); } } /** * Implement a level of detail rendering, which will show different details based on the zoom level. */ class LevelOfDetail extends BaseBehavior { prevLevel = DEFAULT_LEVEL; levels = { ['overview']: [0, 0.6], ['detailed']: [0.6, Infinity], }; constructor(context, options) { super(context, options); this.bindEvents(); } update(options) { this.unbindEvents(); super.update(options); this.bindEvents(); } updateZoomLevel = async (e) => { if ('scale' in e.data) { const scale = e.data.scale; const level = Object.entries(this.levels).find(([key, [min, max]]) => scale > min && scale <= max)?.[0]; if (level && this.prevLevel !== level) { const { graph } = this.context; graph.updateNodeData((prev) => prev.map((node) => ({ ...node, data: { ...node.data, level } }))); await graph.draw(); this.prevLevel = level; } } }; bindEvents() { const { graph } = this.context; graph.on(GraphEvent.AFTER_TRANSFORM, this.updateZoomLevel); } unbindEvents() { const { graph } = this.context; graph.off(GraphEvent.AFTER_TRANSFORM, this.updateZoomLevel); } destroy() { this.unbindEvents(); super.destroy(); } } register(ExtensionCategory.NODE, 'chart-node', ChartNode); register(ExtensionCategory.BEHAVIOR, 'level-of-detail', LevelOfDetail); fetch('https://assets.antv.antgroup.com/g6/organization-chart.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', data, node: { type: 'chart-node', style: { labelPlacement: 'center', lineWidth: 1, ports: [{ placement: 'top' }, { placement: 'bottom' }], radius: 2, shadowBlur: 10, shadowColor: '#e0e0e0', shadowOffsetX: 3, size: [150, 60], stroke: '#C0C0C0', }, }, edge: { type: 'polyline', style: { router: { type: 'orth', }, stroke: '#C0C0C0', }, }, layout: { type: 'dagre', }, autoFit: 'view', behaviors: ['level-of-detail', 'zoom-canvas', 'drag-canvas'], }); graph.render(); }); ``` ### 系统性能诊断流程图 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/performance-diagnosis-flowchart/ - Source path: examples/scene-case/default/demo/performance-diagnosis-flowchart.js ```js import { BugOutlined } from '@ant-design/icons'; import { ExtensionCategory, Graph, HoverActivate, idOf, register } from '@antv/g6'; import { ReactNode } from '@antv/g6-extension-react'; import { Flex, Typography } from 'antd'; import { useEffect, useRef } from 'react'; import { createRoot } from 'react-dom/client'; const { Text } = Typography; const ACTIVE_COLOR = '#f6c523'; const COLOR_MAP = { 'pre-inspection': '#3fc1c9', problem: '#8983f3', inspection: '#f48db4', solution: '#ffaa64', }; class HoverElement extends HoverActivate { getActiveIds(event) { const { model, graph } = this.context; const { targetType, target } = event; const targetId = target.id; const ids = [targetId]; if (targetType === 'edge') { const edge = model.getEdgeDatum(targetId); ids.push(edge.source, edge.target); } else if (targetType === 'node') { ids.push(...model.getRelatedEdgesData(targetId).map(idOf)); } graph.frontElement(ids); return ids; } } register(ExtensionCategory.NODE, 'react', ReactNode); register(ExtensionCategory.BEHAVIOR, 'hover-element', HoverElement); const Node = ({ data }) => { const { text, type } = data.data; const isHovered = data.states?.includes('active'); const isSelected = data.states?.includes('selected'); const color = isHovered ? ACTIVE_COLOR : COLOR_MAP[type]; const containerStyle = { width: '100%', height: '100%', background: color, border: `3px solid ${color}`, borderRadius: 16, cursor: 'pointer', }; if (isSelected) { Object.assign(containerStyle, { border: `3px solid #000` }); } return ( {type === 'problem' && } {text} ); }; export const PerformanceDiagnosisFlowchart = () => { const containerRef = useRef(); useEffect(() => { fetch('https://assets.antv.antgroup.com/g6/performance-diagnosis.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: containerRef.current, data, autoFit: 'view', node: { type: 'react', style: (d) => { const style = { component: , ports: [{ placement: 'top' }, { placement: 'bottom' }], }; const size = { 'pre-inspection': [240, 120], problem: [200, 120], inspection: [330, 100], solution: [200, 120], }[d.data.type] || [200, 80]; Object.assign(style, { size, dx: -size[0] / 2, dy: -size[1] / 2, }); return style; }, state: { active: { halo: false, }, selected: { halo: false, }, }, }, edge: { type: 'polyline', style: { lineWidth: 3, radius: 20, stroke: '#8b9baf', endArrow: true, labelText: (d) => d.data.text, labelFill: '#8b9baf', labelFontWeight: 600, labelBackground: true, labelBackgroundFill: '#f8f8f8', labelBackgroundOpacity: 1, labelBackgroundLineWidth: 3, labelBackgroundStroke: '#8b9baf', labelPadding: [1, 10], labelBackgroundRadius: 4, router: { type: 'orth', }, }, state: { active: { stroke: ACTIVE_COLOR, labelBackgroundStroke: ACTIVE_COLOR, halo: false, }, }, }, layout: { type: 'antv-dagre', }, behaviors: ['zoom-canvas', 'drag-canvas', 'hover-element', 'click-select'], }); graph.render(); }); }, []); return
; }; const root = createRoot(document.getElementById('container')); root.render(); ``` ### S 型流程图 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/snake-flow-diagram/ - Source path: examples/scene-case/default/demo/snake-flow-diagram.js ```js import { ExtensionCategory, Graph, Polyline, positionOf, register } from '@antv/g6'; const data = { nodes: [ { id: '0', data: { label: '开始流程', time: '17:00:00' } }, { id: '1', data: { label: '流程1', time: '17:00:05' } }, { id: '2', data: { label: '流程2', time: '17:00:12' } }, { id: '3', data: { label: '流程3', time: '17:00:30' } }, { id: '4', data: { label: '流程4', time: '17:02:00' } }, { id: '5', data: { label: '流程5', time: '17:02:40' } }, { id: '6', data: { label: '流程6', time: '17:05:50' } }, { id: '7', data: { label: '流程7', time: '17:10:00' } }, { id: '8', data: { label: '流程8', time: '17:11:20' } }, { id: '9', data: { label: '流程9', time: '17:15:00' } }, { id: '10', data: { label: '流程10', time: '17:30:00' } }, { id: '11', data: { label: '流程11' } }, { id: '12', data: { label: '流程12' } }, { id: '13', data: { label: '流程13' } }, { id: '14', data: { label: '流程14' } }, { id: '15', data: { label: '流程结束' } }, ], edges: [ { source: '0', target: '1', data: { done: true } }, { source: '1', target: '2', data: { done: true } }, { source: '2', target: '3', data: { done: true } }, { source: '3', target: '4', data: { done: true } }, { source: '4', target: '5', data: { done: true } }, { source: '5', target: '6', data: { done: true } }, { source: '6', target: '7', data: { done: true } }, { source: '7', target: '8', data: { done: true } }, { source: '8', target: '9', data: { done: true } }, { source: '9', target: '10', data: { done: true } }, { source: '10', target: '11', data: { done: false } }, { source: '11', target: '12', data: { done: false } }, { source: '12', target: '13', data: { done: false } }, { source: '13', target: '14', data: { done: false } }, { source: '14', target: '15', data: { done: false } }, ], }; class SnakePolyline extends Polyline { getPoints(attributes) { const [sourcePoint, targetPoint] = this.getEndpoints(attributes, false); if (sourcePoint[1] === targetPoint[1]) return [sourcePoint, targetPoint]; const prevPointId = this.context.model .getRelatedEdgesData(this.sourceNode.id) .filter((edge) => edge.target === this.sourceNode.id)[0]?.source; if (!prevPointId) return [sourcePoint, targetPoint]; const prevPoint = positionOf(this.context.model.getNodeLikeDatum(prevPointId)); const offset = -(prevPoint[0] - sourcePoint[0]) / 4; return [ sourcePoint, [sourcePoint[0] + offset, sourcePoint[1]], [targetPoint[0] + offset, targetPoint[1]], targetPoint, ]; } } register(ExtensionCategory.EDGE, 's-polyline', SnakePolyline); const graph = new Graph({ container: 'container', data, background: '#fafafa', autoFit: 'center', node: { style: { fill: (d) => (d.data.time ? '#1783ff' : '#d9d9d9'), lineWidth: 2, size: 8, stroke: (d) => (d.data.time ? 'lightblue' : ''), labelFontWeight: 500, labelOffsetY: 8, labelText: (d) => d.data.label, badge: true, badges: (d) => [ { background: false, fill: '#858ca6', fontSize: 10, offsetY: 39, placement: 'bottom', text: d.data.time || '--', }, ], }, }, edge: { type: 's-polyline', style: { lineWidth: 2, stroke: (d) => (d.data.done ? '#1783ff' : '#d9d9d9'), }, }, layout: { type: 'snake', cols: 6, rowGap: 200, padding: [20, 140, 80], }, behaviors: ['drag-canvas', 'zoom-canvas'], }); graph.render(); ``` ### 子图 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/sub-graph/ - Source path: examples/scene-case/default/demo/sub-graph.js ```js import { BaseCombo, ExtensionCategory, Graph, HTML, isCollapsed, register } from '@antv/g6'; import { isEqual } from '@antv/util'; class SubGraphNode extends HTML { connectedCallback() { super.connectedCallback(); this.drawSubGraph(); } render(attributes, container) { super.render(attributes, container); this.drawSubGraph(); } get data() { return this.context.graph.getElementData(this.id).data; } drawSubGraph() { if (!this.isConnected) return; if (isEqual(this.previousData, this.data)) return; this.previousData = this.data; const data = this.data; this.drawGraphNode(data.data); } drawGraphNode(data) { const [width, height] = this.getSize(); const container = this.getDomElement(); container.innerHTML = ''; const subGraph = new Graph({ container, width, height, animation: false, data: data, node: { style: { labelText: (d) => d.id, iconFontFamily: 'iconfont', iconText: '\ue6e5', }, }, layout: { type: 'force', linkDistance: 50, }, behaviors: ['zoom-canvas', { type: 'drag-canvas', enable: (event) => event.shiftKey === true }], autoFit: 'view', }); subGraph.render(); this.graph = subGraph; } destroy() { this.graph?.destroy(); super.destroy(); } } class CardCombo extends BaseCombo { getKeyStyle(attributes) { const keyStyle = super.getKeyStyle(attributes); const [width, height] = this.getKeySize(attributes); return { ...keyStyle, width, height, x: -width / 2, y: -height / 2, }; } drawKeyShape(attributes, container) { const { collapsed } = attributes; const outer = this.upsert('key', 'rect', this.getKeyStyle(attributes), container); if (!outer || !collapsed) { this.removeCardShape(); return outer; } this.drawCardShape(attributes, container); return outer; } drawCardShape(attributes, container) { const [width, height] = this.getCollapsedKeySize(attributes); const data = this.context.graph.getComboData(this.id).data; const baseX = -width / 2; const baseY = -height / 2; this.upsert( 'card-title', 'text', { x: baseX, y: baseY, text: 'Group: ' + this.id, textAlign: 'left', textBaseline: 'top', fontSize: 16, fontWeight: 'bold', fill: '#4083f7', }, container, ); const gap = 10; const sep = (width + gap) / data.data.length; data.data.forEach(({ name, value }, index) => { this.upsert( `card-item-name-${index}`, 'text', { x: baseX + index * sep, y: baseY + 40, text: name, textAlign: 'left', textBaseline: 'top', fontSize: 12, fill: 'gray', }, container, ); this.upsert( `card-item-value-${index}`, 'text', { x: baseX + index * sep, y: baseY + 60, text: value + '%', textAlign: 'left', textBaseline: 'top', fontSize: 24, }, container, ); }); } removeCardShape() { Object.entries(this.shapeMap).forEach(([key, shape]) => { if (key.startsWith('card-')) { delete this.shapeMap[key]; shape.destroy(); } }); } } register(ExtensionCategory.NODE, 'sub-graph', SubGraphNode); register(ExtensionCategory.COMBO, 'card', CardCombo); const getSize = (d) => { const data = d.data; if (data.type === 'card') return data.status === 'expanded' ? [200, 100 * data.children.length] : [200, 100]; else return [200, 200]; }; const graph = new Graph({ container: 'container', animation: false, zoom: 0.8, data: { nodes: [ { id: '1', combo: 'A', style: { x: 120, y: 70 }, data: { data: { nodes: [ { id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }, { id: 'node-5' }, { id: 'node-6' }, { id: 'node-7' }, { id: 'node-8' }, ], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-1', target: 'node-4' }, { source: 'node-1', target: 'node-5' }, { source: 'node-1', target: 'node-6' }, { source: 'node-1', target: 'node-7' }, { source: 'node-1', target: 'node-8' }, ], }, }, }, { id: '2', combo: 'C', style: { x: 370, y: 70 }, data: { data: { nodes: [{ id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-1', target: 'node-4' }, ], }, }, }, { id: 'node-4', combo: 'D', style: { x: 370, y: 200 }, data: { data: { nodes: [{ id: 'node-1' }, { id: 'node-2' }, { id: 'node-3' }, { id: 'node-4' }], edges: [ { source: 'node-1', target: 'node-2' }, { source: 'node-1', target: 'node-3' }, { source: 'node-1', target: 'node-4' }, ], }, }, }, ], edges: [], combos: [ { id: 'root', data: { data: [ { name: 'percent', value: 50 }, { name: 'percent', value: 45 }, { name: 'percent', value: 70 }, ], }, }, { id: 'A', combo: 'root', data: { data: [ { name: 'percent', value: 30 }, { name: 'percent', value: 90 }, ], }, }, { id: 'B', combo: 'root', style: { collapsed: true }, data: { data: [ { name: 'percent', value: 60 }, { name: 'percent', value: 80 }, ], }, }, { id: 'C', combo: 'B', style: { collapsed: true }, data: { data: [{ name: 'percent', value: 60 }], }, }, { id: 'D', combo: 'B', style: { collapsed: true }, data: { data: [{ name: 'percent', value: 80 }], }, }, ], }, node: { type: 'sub-graph', style: { dx: -100, dy: -50, size: getSize, }, }, combo: { type: 'card', style: { collapsedSize: [200, 100], collapsedMarker: false, radius: 10, }, }, behaviors: [ { type: 'drag-element', enable: (event) => event.shiftKey !== true }, 'collapse-expand', 'zoom-canvas', 'drag-canvas', ], plugins: [ { type: 'contextmenu', getItems: (event) => { const { targetType, target } = event; if (!['node', 'combo'].includes(targetType)) return []; const id = target.id; if (targetType === 'combo') { const data = graph.getComboData(id); if (isCollapsed(data)) { return [{ name: '展开', value: 'expanded' }]; } else return [{ name: '收起', value: 'collapsed' }]; } return [{ name: '收起', value: 'collapsed' }]; }, onClick: (value, target, current) => { const id = current.id; const elementType = graph.getElementType(id); if (elementType === 'node') { const parent = graph.getParentData(id, 'combo'); if (parent) return graph.collapseElement(parent.id, false); } if (value === 'expanded') graph.expandElement(id, false); else graph.collapseElement(id, false); }, }, ], }); graph.render(); ``` ### 猫咪喜好 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/default/why-do-cats/ - Source path: examples/scene-case/default/demo/why-do-cats.js ```js // ref: https://whydocatsanddogs.com/cats import { Renderer as CanvasRenderer } from '@antv/g-canvas'; import { Plugin as PluginRoughCanvasRenderer } from '@antv/g-plugin-rough-canvas-renderer'; import { BaseLayout, ExtensionCategory, Graph, register } from '@antv/g6'; import { hierarchy, pack } from '@antv/vendor/d3-hierarchy'; const style = document.createElement('style'); style.innerHTML = ` @font-face { font-family: 'handwriting'; src: url('https://mass-office.alipay.com/huamei_koqzbu/afts/file/sgUeRbI3d-IAAAAAAAAAABAADnV5AQBr/font.woff2') format('woff2'); }`; document.head.appendChild(style); function getColor(id) { const colors = [ '#8dd3c7', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f', ]; const index = parseInt(id); return colors[index % colors.length]; } const topics = [ 'cat.like', 'cat.hate', 'cat.love', 'cat.not.like', 'cat.afraid_of', 'cat.want.to', 'cat.scared.of', 'cat.not.want_to', ]; class BubbleLayout extends BaseLayout { id = 'bubble-layout'; async execute(model, options) { const { nodes = [] } = model; const { width = 0, height = 0 } = { ...this.options, ...options }; const root = hierarchy({ id: 'root' }, (datum) => { const { id } = datum; if (id === 'root') return nodes.filter((node) => node.depth === 1); else if (datum.depth === 2) return []; else return nodes.filter((node) => node.actualParentId === id); }); root.sum((d) => (+d.index_value || 0.01) ** 0.5 * 100); pack() .size([width, height]) .padding((node) => { return node.depth === 0 ? 20 : 2; })(root); const result = { nodes: [] }; root.descendants().forEach((node) => { const { data: { id }, x, y, // @ts-expect-error r is exist r, } = node; if (node.depth >= 1) result.nodes.push({ id, style: { x, y, size: r * 2 } }); }); return result; } } register(ExtensionCategory.LAYOUT, 'bubble-layout', BubbleLayout); fetch('https://assets.antv.antgroup.com/g6/cat-hierarchy.json') .then((res) => res.json()) .then((rawData) => { const graphData = rawData.reduce( (acc, row) => { const { id } = row; topics.forEach((topic) => { if (id.startsWith(topic)) { if (id === topic) { acc.nodes.push({ ...row, depth: 1 }); } else { acc.nodes.push({ ...row, depth: 2, actualParentId: topic }); } } }); return acc; }, { nodes: [] }, ); const graph = new Graph({ container: 'container', data: graphData, renderer: (layer) => { const renderer = new CanvasRenderer(); if (layer === 'main') { renderer.registerPlugin(new PluginRoughCanvasRenderer()); } return renderer; }, node: { style: (d) => { const { id, depth, id_num } = d; const color = getColor(id_num); if (depth === 1) { return { fill: 'none', stroke: color, labelFontFamily: 'handwriting', labelFontSize: 20, labelText: id.replace('cat.', '').replace(/\.|_/g, ' '), labelTextTransform: 'capitalize', lineWidth: 1, zIndex: -1, }; } const { text, style: { size: diameter }, } = d; return { fill: color, fillOpacity: 0.7, stroke: color, fillStyle: 'cross-hatch', hachureGap: 1.5, iconFontFamily: 'handwriting', iconFontSize: (diameter / text.length) * 2, iconText: diameter > 20 ? text : '', iconFontWeight: 'bold', iconStroke: color, iconLineWidth: 2, lineWidth: (diameter || 20) ** 0.5 / 5, }; }, }, layout: { type: 'bubble-layout', preLayout: true, }, plugins: [ { type: 'tooltip', getContent: (event, items) => { return `${items[0].id.replace(/\.|_/g, ' ')}`; }, }, ], behaviors: [{ type: 'drag-canvas', enable: true }, 'zoom-canvas'], }); graph.render(); }); ``` ### 克服拖延症(决策型鱼骨图) - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/anti-procrastination-fishbone/ - Source path: examples/scene-case/tree-graph/demo/anti-procrastination-fishbone.js ```js import { Text } from '@antv/g'; import { BaseTransform, ExtensionCategory, Graph, register, treeToGraphData } from '@antv/g6'; const data = { id: 'Overcome \n procrastination', children: [ { id: 'Perfectionism', children: [ { id: 'Correctly assess the difficulty of things' }, { id: 'Complete first, then improve' }, { id: 'Just do it' }, ], }, { id: 'Improve concentration', children: [ { id: 'Pomodoro Technique' }, { id: 'Limited time, limited quantity, only do one thing at a time' }, { id: 'Improve anti-interference ability, reduce interruptions' }, ], }, { id: 'Set a clear task management process', children: [ { id: 'Set priorities for completed tasks' }, { id: 'Break down specific executable goals' }, { id: 'Collect-sort-sort-execute feedback-summary' }, ], }, { id: 'Establish positive feedback', children: [{ id: 'Do what you like' }, { id: 'Spiritual motivation' }, { id: 'Material motivation' }], }, { id: 'Relax and enjoy', children: [ { id: 'Focus on process rather than results' }, { id: 'Driven by needs rather than anxiety' }, { id: 'Accept and understand' }, ], }, ], }; let textShape; const measureText = (style) => { if (!textShape) textShape = new Text({ style }); textShape.attr(style); return textShape.getBBox().width; }; class AssignColorByBranch extends BaseTransform { static defaultOptions = { colors: [ '#1783FF', '#F08F56', '#D580FF', '#00C9C9', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }; constructor(context, options) { super(context, Object.assign({}, AssignColorByBranch.defaultOptions, options)); } beforeDraw(input) { const nodes = this.context.model.getNodeData(); if (nodes.length === 0) return input; let colorIndex = 0; const dfs = (nodeId, color) => { const node = nodes.find((datum) => datum.id == nodeId); if (!node) return; node.style ||= {}; node.style.color = color || this.options.colors[colorIndex++ % this.options.colors.length]; node.children?.forEach((childId) => dfs(childId, node.style?.color)); }; nodes.filter((node) => node.depth === 1).forEach((rootNode) => dfs(rootNode.id)); return input; } } class ArrangeEdgeZIndex extends BaseTransform { beforeDraw(input) { const { model } = this.context; const { nodes, edges } = model.getData(); const oneLevelNodes = nodes.filter((node) => node.depth === 1); const oneLevelNodeIds = oneLevelNodes.map((node) => node.id); edges.forEach((edge) => { if (oneLevelNodeIds.includes(edge.target)) { edge.style ||= {}; edge.style.zIndex = oneLevelNodes.length - oneLevelNodes.findIndex((node) => node.id === edge.target); } }); return input; } } register(ExtensionCategory.TRANSFORM, 'assign-color-by-branch', AssignColorByBranch); register(ExtensionCategory.TRANSFORM, 'arrange-edge-z-index', ArrangeEdgeZIndex); const getNodeSize = (id, depth) => { const FONT_FAMILY = 'system-ui, sans-serif'; return depth === 0 ? [measureText({ text: id, fontSize: 24, fontWeight: 'bold', fontFamily: FONT_FAMILY }) + 80, 70] : depth === 1 ? [measureText({ text: id, fontSize: 18, fontFamily: FONT_FAMILY }) + 50, 42] : [2, 30]; }; const graph = new Graph({ autoFit: 'view', padding: 10, data: treeToGraphData(data), node: { type: 'rect', style: (d) => { const style = { radius: 8, size: getNodeSize(d.id, d.depth), labelText: d.id, labelPlacement: 'right', labelFontFamily: 'Gill Sans', }; if (d.depth === 0) { Object.assign(style, { fill: '#EFF0F0', labelFill: '#262626', labelFontWeight: 'bold', labelFontSize: 24, labelOffsetY: 4, labelPlacement: 'center', labelLineHeight: 24, }); } else if (d.depth === 1) { Object.assign(style, { labelFontSize: 18, labelFill: '#fff', labelFillOpacity: 0.9, labelOffsetY: 5, labelPlacement: 'center', fill: d.style?.color, }); } else { Object.assign(style, { fill: 'transparent', labelFontSize: 16, labeFill: '#262626', }); } return style; }, }, edge: { type: 'polyline', style: { lineWidth: 3, stroke: function (data) { return this.getNodeData(data.target).style.color || '#99ADD1'; }, }, }, layout: { type: 'fishbone', direction: 'LR', hGap: 40, vGap: 60, }, behaviors: ['zoom-canvas', 'drag-canvas'], transforms: ['assign-color-by-branch', 'arrange-edge-z-index'], }); graph.render(); ``` ### 缩进树 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/indented-tree/ - Source path: examples/scene-case/tree-graph/demo/indented-tree.js ```js import { Text as GText, Rect } from '@antv/g'; import { Badge, BaseBehavior, BaseNode, CommonEvent, ExtensionCategory, Graph, NodeEvent, Polyline, iconfont, idOf, register, subStyleProps, treeToGraphData, } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const rootId = 'Modeling Methods'; const COLORS = [ '#5B8FF9', '#F6BD16', '#5AD8A6', '#945FB9', '#E86452', '#6DC8EC', '#FF99C3', '#1E9493', '#FF9845', '#5D7092', ]; const TreeEvent = { COLLAPSE_EXPAND: 'collapse-expand', ADD_CHILD: 'add-child', }; let textShape; const measureText = (text) => { if (!textShape) textShape = new GText({ style: text }); textShape.attr(text); return textShape.getBBox().width; }; class IndentedNode extends BaseNode { static defaultStyleProps = { ports: [ { key: 'in', placement: 'right-bottom', }, { key: 'out', placement: 'left-bottom', }, ], }; constructor(options) { Object.assign(options.style, IndentedNode.defaultStyleProps); super(options); } get childrenData() { return this.context.model.getChildrenData(this.id); } getKeyStyle(attributes) { const [width, height] = this.getSize(attributes); const keyStyle = super.getKeyStyle(attributes); return { width, height, ...keyStyle, fill: 'transparent', }; } drawKeyShape(attributes, container) { const keyStyle = this.getKeyStyle(attributes); return this.upsert('key', 'rect', keyStyle, container); } getLabelStyle(attributes) { if (attributes.label === false || !attributes.labelText) return false; return subStyleProps(this.getGraphicStyle(attributes), 'label'); } drawIconArea(attributes, container) { const [, h] = this.getSize(attributes); const iconAreaStyle = { fill: 'transparent', height: 30, width: 12, x: -6, y: h, zIndex: -1, }; this.upsert('icon-area', Rect, iconAreaStyle, container); } forwardEvent(target, type, listener) { if (target && !Reflect.has(target, '__bind__')) { Reflect.set(target, '__bind__', true); target.addEventListener(type, listener); } } getCountStyle(attributes) { const { collapsed, color } = attributes; if (collapsed) { const [, height] = this.getSize(attributes); return { backgroundFill: color, cursor: 'pointer', fill: '#fff', fontSize: 8, padding: [0, 10], text: `${this.childrenData.length}`, textAlign: 'center', y: height + 8, }; } return false; } drawCountShape(attributes, container) { const countStyle = this.getCountStyle(attributes); const btn = this.upsert('count', Badge, countStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.COLLAPSE_EXPAND, { id: this.id, collapsed: false, }); }); } isShowCollapse(attributes) { return !attributes.collapsed && this.childrenData.length > 0; } getCollapseStyle(attributes) { const { showIcon, color } = attributes; if (!this.isShowCollapse(attributes)) return false; const [, height] = this.getSize(attributes); return { visibility: showIcon ? 'visible' : 'hidden', backgroundFill: color, backgroundHeight: 12, backgroundWidth: 12, cursor: 'pointer', fill: '#fff', fontFamily: 'iconfont', fontSize: 8, text: '\ue6e4', textAlign: 'center', x: -1, // half of edge line width y: height + 8, }; } drawCollapseShape(attributes, container) { const iconStyle = this.getCollapseStyle(attributes); const btn = this.upsert('collapse-expand', Badge, iconStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.COLLAPSE_EXPAND, { id: this.id, collapsed: !attributes.collapsed, }); }); } getAddStyle(attributes) { const { collapsed, showIcon } = attributes; if (collapsed) return false; const [, height] = this.getSize(attributes); const color = '#ddd'; const lineWidth = 1; return { visibility: showIcon ? 'visible' : 'hidden', backgroundFill: '#fff', backgroundHeight: 12, backgroundLineWidth: lineWidth, backgroundStroke: color, backgroundWidth: 12, cursor: 'pointer', fill: color, fontFamily: 'iconfont', text: '\ue664', textAlign: 'center', x: -1, y: height + (this.isShowCollapse(attributes) ? 22 : 8), }; } drawAddShape(attributes, container) { const addStyle = this.getAddStyle(attributes); const btn = this.upsert('add', Badge, addStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.ADD_CHILD, { id: this.id }); }); } render(attributes = this.parsedAttributes, container = this) { super.render(attributes, container); this.drawCountShape(attributes, container); this.drawIconArea(attributes, container); this.drawCollapseShape(attributes, container); this.drawAddShape(attributes, container); } } class IndentedEdge extends Polyline { getControlPoints(attributes) { const [sourcePoint, targetPoint] = this.getEndpoints(attributes, false); const [sx] = sourcePoint; const [, ty] = targetPoint; return [[sx, ty]]; } } class CollapseExpandTree extends BaseBehavior { constructor(context, options) { super(context, options); this.bindEvents(); } update(options) { this.unbindEvents(); super.update(options); this.bindEvents(); } bindEvents() { const { graph } = this.context; graph.on(NodeEvent.POINTER_ENTER, this.showIcon); graph.on(NodeEvent.POINTER_LEAVE, this.hideIcon); graph.on(TreeEvent.COLLAPSE_EXPAND, this.onCollapseExpand); graph.on(TreeEvent.ADD_CHILD, this.addChild); } unbindEvents() { const { graph } = this.context; graph.off(NodeEvent.POINTER_ENTER, this.showIcon); graph.off(NodeEvent.POINTER_LEAVE, this.hideIcon); graph.off(TreeEvent.COLLAPSE_EXPAND, this.onCollapseExpand); graph.off(TreeEvent.ADD_CHILD, this.addChild); } status = 'idle'; showIcon = (event) => { this.setIcon(event, true); }; hideIcon = (event) => { this.setIcon(event, false); }; setIcon = (event, show) => { if (this.status !== 'idle') return; const { target } = event; const id = target.id; const { graph, element } = this.context; graph.updateNodeData([{ id, style: { showIcon: show } }]); element.draw({ animation: false, silence: true }); }; onCollapseExpand = async (event) => { this.status = 'busy'; const { id, collapsed } = event; const { graph } = this.context; if (collapsed) await graph.collapseElement(id); else await graph.expandElement(id); this.status = 'idle'; }; addChild(event) { const { onCreateChild = () => ({ id: `${Date.now()}`, style: { labelText: 'new node' } }) } = this.options; const { graph } = this.context; const datum = onCreateChild(event.id); graph.addNodeData([datum]); graph.addEdgeData([{ source: event.id, target: datum.id }]); const parent = graph.getNodeData(event.id); graph.updateNodeData([ { id: event.id, children: [...(parent.children || []), datum.id], style: { collapsed: false } }, ]); graph.render(); } } /** * 支持拖拽节点到其他节点下作为子节点 * * Support dragging nodes to other nodes as child nodes */ class DragBranch extends BaseBehavior { constructor(context, options) { super(context, options); this.bindEvents(); } update(options) { this.unbindEvents(); super.update(options); this.bindEvents(); } bindEvents() { const { graph } = this.context; graph.on(NodeEvent.DRAG_START, this.onDragStart); graph.on(NodeEvent.DRAG, this.onDrag); graph.on(NodeEvent.DRAG_END, this.onDragEnd); graph.on(NodeEvent.DRAG_ENTER, this.onDragEnter); graph.on(NodeEvent.DRAG_LEAVE, this.onDragLeave); } unbindEvents() { const { graph } = this.context; graph.off(NodeEvent.DRAG_START, this.onDragStart); graph.off(NodeEvent.DRAG, this.onDrag); graph.off(NodeEvent.DRAG_END, this.onDragEnd); graph.off(NodeEvent.DRAG_ENTER, this.onDragEnter); graph.off(NodeEvent.DRAG_LEAVE, this.onDragLeave); } enable = true; validate(event) { if (this.destroyed) return false; const { enable = (evt) => evt.target.id !== rootId } = this.options; if (typeof enable === 'function') return enable(event); return !!enable; } createShadow(target) { const shadowStyle = subStyleProps(this.options, 'shadow'); const positionStyle = target.getShape('label').getBBox(); this.shadow = new Rect({ style: { pointerEvents: 'none', fill: '#F3F9FF', fillOpacity: 0.5, stroke: '#1890FF', strokeOpacity: 0.9, lineDash: [5, 5], ...shadowStyle, ...positionStyle, }, }); this.context.canvas.appendChild(this.shadow); } moveShadow(offset) { if (!this.shadow) return; const [dx, dy] = offset; this.shadow.translate(dx, dy); } destroyShadow() { this.shadow?.remove(); this.shadow = undefined; } onDragStart = (event) => { this.enable = this.validate(event); if (!this.enable) return; const { target } = event; this.child = target; this.createShadow(target); }; getDelta(event) { const zoom = this.context.graph.getZoom(); return [event.dx / zoom, event.dy / zoom]; } onDrag = (event) => { if (!this.enable) return; const delta = this.getDelta(event); this.moveShadow(delta); }; onDragEnd = () => { this.destroyShadow(); if (this.child === undefined || this.parent === undefined) return; const { graph } = this.context; const childId = this.child.id; const parentId = this.parent.id; const originalParent = graph.getParentData(childId, 'tree'); // 前后父节点不应该相同 // The previous and current parent nodes should not be the same if (idOf(originalParent) === parentId) return; // 新的父节点不应该是当前节点的子节点 // The new parent node should not be a child node of the current node const ancestors = graph.getAncestorsData(parentId, 'tree'); if (ancestors.some((ancestor) => ancestor.id === childId)) return; const edges = graph .getEdgeData() .filter((edge) => edge.target === childId) .map(idOf); graph.removeEdgeData(edges); graph.updateNodeData([ { id: idOf(originalParent), children: originalParent?.children?.filter((child) => child !== childId) }, ]); const modifiedParent = graph.getNodeData(parentId); graph.updateNodeData([{ id: parentId, children: [...(modifiedParent.children || []), childId] }]); graph.addEdgeData([{ source: parentId, target: childId }]); graph.render(); }; onDragEnter = (event) => { const { graph, element } = this.context; const targetId = event.target.id; if (targetId === this.child?.id || targetId === rootId) { if (targetId === rootId) this.parent = event.target; return; } this.parent = event.target; graph.updateNodeData([{ id: targetId, states: ['selected'] }]); element.draw({ animation: false, silence: true }); }; onDragLeave = (event) => { const { graph, element } = this.context; const targetId = event.target.id; this.parent = undefined; graph.updateNodeData([{ id: targetId, states: [] }]); element.draw({ animation: false, silence: true }); }; } register(ExtensionCategory.NODE, 'indented', IndentedNode); register(ExtensionCategory.EDGE, 'indented', IndentedEdge); register(ExtensionCategory.BEHAVIOR, 'collapse-expand-tree', CollapseExpandTree); register(ExtensionCategory.BEHAVIOR, 'drag-branch', DragBranch); fetch('https://assets.antv.antgroup.com/g6/algorithm-category.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', x: 60, data: treeToGraphData(data), node: { type: 'indented', style: { size: (d) => [measureText({ text: d.id, fontSize: 12 }) + 6, 20], labelBackground: (datum) => datum.id === rootId, labelBackgroundRadius: 0, labelBackgroundFill: '#576286', labelFill: (datum) => (datum.id === rootId ? '#fff' : '#666'), labelText: (d) => d.style?.labelText || d.id, labelTextAlign: (datum) => (datum.id === rootId ? 'center' : 'left'), labelTextBaseline: 'top', color: (datum) => { const depth = graph.getAncestorsData(datum.id, 'tree').length - 1; return COLORS[depth % COLORS.length] || '#576286'; }, }, state: { selected: { lineWidth: 0, labelFill: '#40A8FF', labelBackground: true, labelFontWeight: 'normal', labelBackgroundFill: '#e8f7ff', labelBackgroundRadius: 10, }, }, }, edge: { type: 'indented', style: { radius: 16, lineWidth: 2, sourcePort: 'out', targetPort: 'in', stroke: (datum) => { const depth = graph.getAncestorsData(datum.source, 'tree').length; return COLORS[depth % COLORS.length]; }, }, }, layout: { type: 'indented', direction: 'LR', isHorizontal: true, indent: 40, getHeight: () => 20, getVGap: () => 10, }, behaviors: [ 'scroll-canvas', 'drag-branch', 'collapse-expand-tree', { type: 'click-select', enable: (event) => event.targetType === 'node' && event.target.id !== rootId }, ], }); graph.render(); }); ``` ### 思维导图 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/mindmap/ - Source path: examples/scene-case/tree-graph/demo/mindmap.js ```js import { Rect, Text } from '@antv/g'; import { Badge, BaseBehavior, BaseNode, BaseTransform, CommonEvent, CubicHorizontal, ExtensionCategory, Graph, GraphEvent, iconfont, idOf, NodeEvent, positionOf, register, treeToGraphData, } from '@antv/g6'; const style = document.createElement('style'); style.innerHTML = `@import url('${iconfont.css}');`; document.head.appendChild(style); const RootNodeStyle = { fill: '#EFF0F0', labelFill: '#262626', labelFontSize: 24, labelFontWeight: 600, labelOffsetY: 8, labelPlacement: 'center', ports: [{ placement: 'right' }, { placement: 'left' }], radius: 8, }; const NodeStyle = { fill: 'transparent', labelPlacement: 'center', labelFontSize: 16, ports: [{ placement: 'right-bottom' }, { placement: 'left-bottom' }], }; const TreeEvent = { COLLAPSE_EXPAND: 'collapse-expand', ADD_CHILD: 'add-child', }; let textShape; const measureText = (text) => { if (!textShape) textShape = new Text({ style: text }); textShape.attr(text); return textShape.getBBox().width; }; const getNodeWidth = (nodeId, isRoot) => { const padding = isRoot ? 40 : 30; const nodeStyle = isRoot ? RootNodeStyle : NodeStyle; return measureText({ text: nodeId, fontSize: nodeStyle.labelFontSize, fontFamily: 'Gill Sans' }) + padding; }; const getNodeSize = (nodeId, isRoot) => { const width = getNodeWidth(nodeId, isRoot); const height = isRoot ? 48 : 32; return [width, height]; }; class MindmapNode extends BaseNode { static defaultStyleProps = { showIcon: false, }; constructor(options) { Object.assign(options.style, MindmapNode.defaultStyleProps); super(options); } get childrenData() { return this.context.model.getChildrenData(this.id); } get rootId() { return idOf(this.context.model.getRootsData()[0]); } isShowCollapse(attributes) { const { collapsed, showIcon } = attributes; return !collapsed && showIcon && this.childrenData.length > 0; } getCollapseStyle(attributes) { const { showIcon, color, direction } = attributes; if (!this.isShowCollapse(attributes)) return false; const [width, height] = this.getSize(attributes); return { backgroundFill: color, backgroundHeight: 12, backgroundWidth: 12, cursor: 'pointer', fill: '#fff', fontFamily: 'iconfont', fontSize: 8, text: '\ue6e4', textAlign: 'center', transform: direction === 'left' ? [['rotate', 90]] : [['rotate', -90]], visibility: showIcon ? 'visible' : 'hidden', x: direction === 'left' ? -6 : width + 6, y: height, }; } drawCollapseShape(attributes, container) { const iconStyle = this.getCollapseStyle(attributes); const btn = this.upsert('collapse-expand', Badge, iconStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.COLLAPSE_EXPAND, { id: this.id, collapsed: !attributes.collapsed, }); }); } getCountStyle(attributes) { const { collapsed, color, direction } = attributes; const count = this.context.model.getDescendantsData(this.id).length; if (!collapsed || count === 0) return false; const [width, height] = this.getSize(attributes); return { backgroundFill: color, backgroundHeight: 12, backgroundWidth: 12, cursor: 'pointer', fill: '#fff', fontSize: 8, text: count.toString(), textAlign: 'center', x: direction === 'left' ? -6 : width + 6, y: height, }; } drawCountShape(attributes, container) { const countStyle = this.getCountStyle(attributes); const btn = this.upsert('count', Badge, countStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.COLLAPSE_EXPAND, { id: this.id, collapsed: false, }); }); } getAddStyle(attributes) { const { collapsed, showIcon, direction } = attributes; if (collapsed || !showIcon) return false; const [width, height] = this.getSize(attributes); const color = '#ddd'; const offsetX = this.isShowCollapse(attributes) ? 24 : 12; const isRoot = this.id === this.rootId; return { backgroundFill: '#fff', backgroundHeight: 12, backgroundLineWidth: 1, backgroundStroke: color, backgroundWidth: 12, cursor: 'pointer', fill: color, fontFamily: 'iconfont', fontSize: 8, text: '\ue664', textAlign: 'center', x: isRoot ? width + 12 : direction === 'left' ? -offsetX : width + offsetX, y: isRoot ? height / 2 : height, }; } getAddBarStyle(attributes) { const { collapsed, showIcon, direction, color = '#1783FF' } = attributes; if (collapsed || !showIcon) return false; const [width, height] = this.getSize(attributes); const offsetX = this.isShowCollapse(attributes) ? 12 : 0; const isRoot = this.id === this.rootId; const HEIGHT = 2; const WIDTH = 6; return { cursor: 'pointer', fill: direction === 'left' ? `linear-gradient(180deg, #fff 20%, ${color})` : `linear-gradient(0deg, #fff 20%, ${color})`, height: HEIGHT, width: WIDTH, x: isRoot ? width : direction === 'left' ? -offsetX - WIDTH : width + offsetX, y: isRoot ? height / 2 - HEIGHT / 2 : height - HEIGHT / 2, zIndex: -1, }; } drawAddShape(attributes, container) { const addStyle = this.getAddStyle(attributes); const addBarStyle = this.getAddBarStyle(attributes); this.upsert('add-bar', Rect, addBarStyle, container); const btn = this.upsert('add', Badge, addStyle, container); this.forwardEvent(btn, CommonEvent.CLICK, (event) => { event.stopPropagation(); this.context.graph.emit(TreeEvent.ADD_CHILD, { id: this.id, direction: attributes.direction }); }); } forwardEvent(target, type, listener) { if (target && !Reflect.has(target, '__bind__')) { Reflect.set(target, '__bind__', true); target.addEventListener(type, listener); } } getKeyStyle(attributes) { const [width, height] = this.getSize(attributes); const keyShape = super.getKeyStyle(attributes); return { width, height, ...keyShape }; } drawKeyShape(attributes, container) { const keyStyle = this.getKeyStyle(attributes); return this.upsert('key', Rect, keyStyle, container); } render(attributes = this.parsedAttributes, container = this) { super.render(attributes, container); this.drawCollapseShape(attributes, container); this.drawAddShape(attributes, container); this.drawCountShape(attributes, container); } } class MindmapEdge extends CubicHorizontal { get rootId() { return idOf(this.context.model.getRootsData()[0]); } getKeyPath(attributes) { const path = super.getKeyPath(attributes); const isRoot = this.targetNode.id === this.rootId; const labelWidth = getNodeWidth(this.targetNode.id, isRoot); const [, tp] = this.getEndpoints(attributes); const sign = this.sourceNode.getCenter()[0] < this.targetNode.getCenter()[0] ? 1 : -1; return [...path, ['L', tp[0] + labelWidth * sign, tp[1]]]; } } class CollapseExpandTree extends BaseBehavior { constructor(context, options) { super(context, options); this.bindEvents(); } update(options) { this.unbindEvents(); super.update(options); this.bindEvents(); } bindEvents() { const { graph } = this.context; graph.on(NodeEvent.POINTER_ENTER, this.showIcon); graph.on(NodeEvent.POINTER_LEAVE, this.hideIcon); graph.on(TreeEvent.COLLAPSE_EXPAND, this.onCollapseExpand); graph.on(TreeEvent.ADD_CHILD, this.addChild); } unbindEvents() { const { graph } = this.context; graph.off(NodeEvent.POINTER_ENTER, this.showIcon); graph.off(NodeEvent.POINTER_LEAVE, this.hideIcon); graph.off(TreeEvent.COLLAPSE_EXPAND, this.onCollapseExpand); graph.off(TreeEvent.ADD_CHILD, this.addChild); } status = 'idle'; showIcon = (event) => { this.setIcon(event, true); }; hideIcon = (event) => { this.setIcon(event, false); }; setIcon = (event, show) => { if (this.status !== 'idle') return; const { target } = event; const id = target.id; const { graph, element } = this.context; graph.updateNodeData([{ id, style: { showIcon: show } }]); element.draw({ animation: false, silence: true }); }; onCollapseExpand = async (event) => { this.status = 'busy'; const { id, collapsed } = event; const { graph } = this.context; await graph.frontElement(id); if (collapsed) await graph.collapseElement(id); else await graph.expandElement(id); this.status = 'idle'; }; addChild = async (event) => { this.status = 'busy'; const { onCreateChild = () => { const currentTime = new Date(Date.now()).toLocaleString(); return { id: `New Node in ${currentTime}` }; }, } = this.options; const { graph } = this.context; const datum = onCreateChild(event.id); const parent = graph.getNodeData(event.id); graph.addNodeData([datum]); graph.addEdgeData([{ source: event.id, target: datum.id }]); graph.updateNodeData([ { id: event.id, children: [...(parent.children || []), datum.id], style: { collapsed: false, showIcon: false }, }, ]); await graph.render(); await graph.focusElement(datum.id); this.status = 'idle'; }; } class AssignColorByBranch extends BaseTransform { static defaultOptions = { colors: [ '#1783FF', '#F08F56', '#D580FF', '#00C9C9', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }; constructor(context, options) { super(context, Object.assign({}, AssignColorByBranch.defaultOptions, options)); } beforeDraw(input) { const nodes = this.context.model.getNodeData(); if (nodes.length === 0) return input; let colorIndex = 0; const dfs = (nodeId, color) => { const node = nodes.find((datum) => datum.id == nodeId); if (!node) return; node.style ||= {}; node.style.color = color || this.options.colors[colorIndex++ % this.options.colors.length]; node.children?.forEach((childId) => dfs(childId, node.style?.color)); }; nodes.filter((node) => node.depth === 1).forEach((rootNode) => dfs(rootNode.id)); return input; } } register(ExtensionCategory.NODE, 'mindmap', MindmapNode); register(ExtensionCategory.EDGE, 'mindmap', MindmapEdge); register(ExtensionCategory.BEHAVIOR, 'collapse-expand-tree', CollapseExpandTree); register(ExtensionCategory.TRANSFORM, 'assign-color-by-branch', AssignColorByBranch); const getNodeSide = (nodeData, parentData) => { if (!parentData) return 'center'; const nodePositionX = positionOf(nodeData)[0]; const parentPositionX = positionOf(parentData)[0]; return parentPositionX > nodePositionX ? 'left' : 'right'; }; fetch('https://assets.antv.antgroup.com/g6/algorithm-category.json') .then((res) => res.json()) .then((data) => { const rootId = data.id; const graph = new Graph({ autoFit: 'view', data: treeToGraphData(data), node: { type: 'mindmap', style: function (d) { const direction = getNodeSide(d, this.getParentData(idOf(d), 'tree')); const isRoot = idOf(d) === rootId; return { direction, labelText: idOf(d), size: getNodeSize(idOf(d), isRoot), labelFontFamily: 'Gill Sans', // 通过设置节点标签背景来扩大交互区域 | Expand the interaction area by setting the node label background labelBackground: true, labelBackgroundFill: 'transparent', labelPadding: direction === 'left' ? [2, 0, 10, 40] : [2, 40, 10, 0], ...(isRoot ? RootNodeStyle : NodeStyle), }; }, }, edge: { type: 'mindmap', style: { lineWidth: 3, stroke: function (data) { return this.getNodeData(data.target).style.color || '#99ADD1'; }, }, }, layout: { type: 'mindmap', direction: 'H', getHeight: () => 30, getWidth: (node) => getNodeWidth(node.id, node.id === rootId), getVGap: () => 6, getHGap: () => 60, animation: false, }, behaviors: ['drag-canvas', 'zoom-canvas', 'collapse-expand-tree'], transforms: ['assign-color-by-branch'], animation: false, }); graph.render(); }); ``` ### 分析产品收益(原因型鱼骨图) - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/product-fishbone/ - Source path: examples/scene-case/tree-graph/demo/product-fishbone.js ```js import { Text } from '@antv/g'; import { BaseTransform, ExtensionCategory, Graph, register, treeToGraphData } from '@antv/g6'; const data = { id: 'Product Profitability\nBelow Expectations', children: [ { id: 'Problem Description', children: [ { id: 'Brand Sales Volume' }, { id: 'Market Capacity' }, { id: 'Brand Market Share' }, { id: 'Total Contribution Margin' }, ], }, { id: 'Brand Positioning', children: [{ id: 'Packaging' }, { id: 'Brand Name' }, { id: 'Selling Price' }, { id: 'Product Specifications' }], }, { id: 'Distribution Channels', children: [{ id: 'Region' }, { id: 'Channel' }, { id: 'Customer Type' }, { id: 'Sales Personnel Coverage' }], }, { id: 'Market Awareness', children: [ { id: 'Regional Weighting' }, { id: 'Media Mix' }, { id: 'Advertising Investment' }, { id: 'Quality Perception' }, ], }, { id: 'Trial Purchase', children: [ { id: 'In-store Display' }, { id: 'Promotion Type' }, { id: 'Timing of Promotion' }, { id: 'Supply Assurance' }, ], }, { id: 'Repeat Purchase', children: [ { id: 'Consumer Profile' }, { id: 'Usage Occasion' }, { id: 'Frequency of Use' }, { id: 'Returns Due to Product Issues' }, ], }, ], }; let textShape; const measureText = (style) => { if (!textShape) textShape = new Text({ style }); textShape.attr(style); return textShape.getBBox().width; }; class AssignColorByBranch extends BaseTransform { static defaultOptions = { colors: [ '#1783FF', '#F08F56', '#D580FF', '#00C9C9', '#7863FF', '#DB9D0D', '#60C42D', '#FF80CA', '#2491B3', '#17C76F', ], }; constructor(context, options) { super(context, Object.assign({}, AssignColorByBranch.defaultOptions, options)); } beforeDraw(input) { const nodes = this.context.model.getNodeData(); if (nodes.length === 0) return input; let colorIndex = 0; const dfs = (nodeId, color) => { const node = nodes.find((datum) => datum.id == nodeId); if (!node) return; node.style ||= {}; node.style.color = color || this.options.colors[colorIndex++ % this.options.colors.length]; node.children?.forEach((childId) => dfs(childId, node.style?.color)); }; nodes.filter((node) => node.depth === 1).forEach((rootNode) => dfs(rootNode.id)); return input; } } class ArrangeEdgeZIndex extends BaseTransform { beforeDraw(input) { const { model } = this.context; const { nodes, edges } = model.getData(); const oneLevelNodes = nodes.filter((node) => node.depth === 1); const oneLevelNodeIds = oneLevelNodes.map((node) => node.id); edges.forEach((edge) => { if (oneLevelNodeIds.includes(edge.target)) { edge.style ||= {}; edge.style.zIndex = oneLevelNodes.length - oneLevelNodes.findIndex((node) => node.id === edge.target); } }); return input; } } register(ExtensionCategory.TRANSFORM, 'assign-color-by-branch', AssignColorByBranch); register(ExtensionCategory.TRANSFORM, 'arrange-edge-z-index', ArrangeEdgeZIndex); const getNodeSize = (id, depth) => { const FONT_FAMILY = 'system-ui, sans-serif'; return depth === 0 ? [measureText({ text: id, fontSize: 24, fontWeight: 'bold', fontFamily: FONT_FAMILY }) + 80, 90] : depth === 1 ? [measureText({ text: id, fontSize: 18, fontFamily: FONT_FAMILY }) + 50, 42] : [2, 30]; }; const graph = new Graph({ autoFit: 'view', padding: 30, data: treeToGraphData(data), node: { type: 'rect', style: (d) => { const style = { radius: 8, size: getNodeSize(d.id, d.depth), labelText: d.id, labelPlacement: 'left', labelFontFamily: 'Gill Sans', }; if (d.depth === 0) { Object.assign(style, { fill: '#EFF0F0', labelFill: '#262626', labelFontWeight: 'bold', labelFontSize: 24, labelOffsetY: 3, labelPlacement: 'center', labelLineHeight: 32, }); } else if (d.depth === 1) { Object.assign(style, { labelFontSize: 18, labelFill: '#252525', labelFillOpacity: 0.9, labelOffsetY: 5, labelPlacement: 'center', labelFontWeight: 600, fill: d.style?.color, fillOpacity: 0.6, lineWidth: 2, stroke: '#252525', }); } else { Object.assign(style, { fill: 'transparent', labelFontSize: 16, labeFill: '#262626', }); } return style; }, }, edge: { type: 'polyline', style: { lineWidth: 3, stroke: '#252525', }, }, layout: { type: 'fishbone', direction: 'RL', hGap: 40, vGap: 60, getRibSep: (node) => { console.log(node); return node.depth === 0 ? 0 : -50; }, }, behaviors: ['zoom-canvas', 'drag-canvas'], transforms: ['assign-color-by-branch', 'arrange-edge-z-index'], }); graph.render(); ``` ### 径向紧凑树 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/radial-compact-tree/ - Source path: examples/scene-case/tree-graph/demo/radial-compact-tree.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/flare.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', padding: 50, data: treeToGraphData(data), node: { style: { size: 12, labelText: (d) => d.id, labelBackground: true, labelFontSize: 14, labelFontFamily: 'Gill Sans', }, }, edge: { type: 'cubic-radial', style: { lineWidth: 3, }, }, layout: { type: 'compact-box', radial: true, direction: 'RL', getVGap: () => 40, getHGap: () => 80, preLayout: false, }, behaviors: [ 'drag-canvas', 'zoom-canvas', 'drag-element', { key: 'hover-activate', type: 'hover-activate', degree: 5, direction: 'in', inactiveState: 'inactive', }, ], transforms: ['place-radial-labels'], animation: false, }); graph.render(); }); ``` ### 径向生态树 - zh page: https://g6.antv.antgroup.com/zh/examples/scene-case/tree-graph/radial-dendrogram/ - Source path: examples/scene-case/tree-graph/demo/radial-dendrogram.js ```js import { Graph, treeToGraphData } from '@antv/g6'; fetch('https://assets.antv.antgroup.com/g6/flare.json') .then((res) => res.json()) .then((data) => { const graph = new Graph({ container: 'container', autoFit: 'view', padding: 50, data: treeToGraphData(data), node: { style: { size: 12, labelText: (d) => d.id, labelBackground: true, labelFontSize: 14, labelFontFamily: 'Gill Sans', }, }, edge: { type: 'cubic-radial', style: { lineWidth: 3, }, }, layout: { type: 'dendrogram', radial: true, preLayout: false, }, behaviors: [ 'drag-canvas', 'zoom-canvas', 'drag-element', { key: 'hover-activate', type: 'hover-activate', degree: 5, direction: 'in', inactiveState: 'inactive', }, ], transforms: ['place-radial-labels'], animation: false, }); graph.render(); }); ``` ### 捆绑模式 - zh page: https://g6.antv.antgroup.com/zh/examples/transform/process-parallel-edges/bundle/ - Source path: examples/transform/process-parallel-edges/demo/bundle.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'A', style: { x: 50, y: 350 } }, { id: 'B', style: { x: 250, y: 150 } }, { id: 'C', style: { x: 450, y: 350 } }, ], edges: [ { source: 'A', target: 'C' }, { source: 'C', target: 'A' }, ...Array.from({ length: 10 }).map((_, i) => ({ id: `edge:A-B${i}`, source: 'A', target: 'B', data: { label: `A->B:${i}`, }, })), ...Array.from({ length: 5 }).map((_, i) => ({ id: `edge:B-C${i}`, source: 'B', target: 'C', data: { label: `B->C:${i}`, }, })), ], }; const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { ports: [{ placement: 'center' }], labelText: (d) => d.id, }, }, edge: { style: { labelText: (d) => d?.data?.label || `${d.source}->${d.target}`, }, }, behaviors: ['drag-element'], transforms: ['process-parallel-edges'], }); graph.render(); ``` ### 合并模式 - zh page: https://g6.antv.antgroup.com/zh/examples/transform/process-parallel-edges/merge/ - Source path: examples/transform/process-parallel-edges/demo/merge.js ```js import { Graph } from '@antv/g6'; const data = { nodes: [ { id: 'A', style: { x: 50, y: 350 } }, { id: 'B', style: { x: 250, y: 150 } }, { id: 'C', style: { x: 450, y: 350 } }, ], edges: [ { source: 'A', target: 'B' }, { source: 'B', target: 'A' }, { id: 'B-C:1', source: 'B', target: 'C' }, { id: 'B-C:2', source: 'B', target: 'C' }, { source: 'A', target: 'C' }, ], }; const graph = new Graph({ container: 'container', autoFit: 'center', data, node: { style: { labelText: (d) => d.id, }, }, edge: { style: { labelText: (d) => d?.data?.label || `${d.source}->${d.target}`, startArrow: false, }, }, transforms: [ { type: 'process-parallel-edges', mode: 'merge', style: { halo: true, haloOpacity: 0.2, haloStroke: 'red', startArrow: true, }, }, ], }); graph.render(); ```