### Initialize Graph with Watermark Plugin Source: https://g6.antv.antgroup.com/en/manual/plugin/watermark Basic example of initializing the G6 Graph with the watermark plugin, setting text, opacity, and rotation. ```javascript const graph = new Graph({ plugins: [ { type: 'watermark', text: 'G6 Graph', opacity: 0.2, rotate: Math.PI / 12, }, ], }); ``` -------------------------------- ### Initialize Graph with Built-in Behaviors Source: https://g6.antv.antgroup.com/en/manual/behavior/overview Configure required behaviors directly in the `behaviors` array during graph instance initialization. This is the simplest method for basic setup. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ behaviors: ['drag-canvas', 'zoom-canvas', 'click-select'], }); ``` ```javascript const graph = new Graph({ // Other configurations... behaviors: ['drag-canvas', 'zoom-canvas', 'click-select'], }); ``` -------------------------------- ### Basic Scrolling Functionality Example Source: https://g6.antv.antgroup.com/en/manual/behavior/scroll-canvas This snippet demonstrates the basic setup for enabling the scroll-canvas behavior in a G6 graph. ```javascript const graph = new Graph({ container: 'container', width: 800, height: 600, behaviors: ['scroll-canvas'], }); ``` -------------------------------- ### Registering and Using High-Performance Layouts Source: https://g6.antv.antgroup.com/en/manual/whats-new/feature Integrate high-performance layouts, such as FruchtermanLayout implemented in Rust, into G6 5.0. This requires installing `@antv/layout-wasm` and registering the layout extension. ```javascript import { FruchtermanLayout } from '@antv/layout-gpu'; import { Graph, register, ExtensionCategory } from '@antv/g6'; register(ExtensionCategory.LAYOUT, 'fruchterman-gpu', FruchtermanLayout); const graph = new Graph({ // ... other configurations layout: { type: 'fruchterman-gpu', // ... Other Layout Configurations }, }); ``` -------------------------------- ### Remote Data Loading Plugin with Registration Source: https://g6.antv.antgroup.com/en/manual/plugin/custom-plugin This example demonstrates a RemoteDataSource plugin that automatically loads data and is then registered with G6. It includes graph instantiation with the plugin enabled. ```javascript import { BasePlugin, Graph, register, ExtensionCategory } from '@antv/g6'; class RemoteDataSource extends BasePlugin { constructor(context, options) { super(context, options); this.loadData(); } async loadData() { // mock remote data const data = { nodes: [ { id: 'node-1', style: { x: 25, y: 50 } }, { id: 'node-2', style: { x: 175, y: 50 } }, ], edges: [{ source: 'node-1', target: 'node-2' }], }; const { graph } = this.context; graph.setData(data); await graph.render(); } } register(ExtensionCategory.PLUGIN, 'remote-data-source', RemoteDataSource); const graph = new Graph({ container: 'container', width: 200, height: 100, plugins: ['remote-data-source'], }); graph.render(); ``` -------------------------------- ### Image Watermark Configuration Source: https://g6.antv.antgroup.com/en/manual/plugin/watermark Example of using an image URL to set an image as the watermark, with specified dimensions and opacity. ```javascript const graph = new Graph({ plugins: [ { type: 'watermark', imageURL: 'https://example.com/logo.png', width: 100, height: 50, opacity: 0.1, }, ], }); ``` -------------------------------- ### Quick Configuration: Basic ScrollCanvas Source: https://g6.antv.antgroup.com/en/manual/behavior/scroll-canvas Declare the scroll-canvas behavior directly using a string. This is a simple method that only supports default configuration and cannot be dynamically modified after setup. ```javascript const graph = new Graph({ // Other configurations... behaviors: ['scroll-canvas'], }); ``` -------------------------------- ### Listen for Node Clicks and Edge Hover Events in G6 Source: https://g6.antv.antgroup.com/en/manual/behavior/overview Use event constants for reliable event handling. This example demonstrates listening for node clicks to select nodes and for edge hover events to highlight edges. ```javascript // Use event constants (recommended) import { NodeEvent, EdgeEvent } from '@antv/g6'; // Listen for node clicks graph.on(NodeEvent.CLICK, (evt) => { const { target } = evt; graph.setElementState(target.id, 'selected'); }); // Listen for edge hover graph.on(EdgeEvent.POINTER_OVER, (evt) => { const { target } = evt; graph.setElementState(target.id, 'highlight'); }); ``` -------------------------------- ### Initialize Graph with Cubic-Horizontal Edges Source: https://g6.antv.antgroup.com/en/manual/element/edge/cubic-horizontal This snippet shows the basic setup for a G6 graph using the 'cubic-horizontal' edge type. It includes node and edge data, along with layout configuration for a hierarchical structure. ```javascript 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(); ``` -------------------------------- ### Configure Title Plugin Alignment and Update Graph Source: https://g6.antv.antgroup.com/en/manual/plugin/title Shows how to dynamically update the 'align' property of the Title plugin and re-render the graph. This example uses a GUI to control alignment options. ```javascript createGraph( { data: { nodes: Array.from({ length: 12 }).map((_, i) => ({ id: `node${i}` })) }, node: { palette: 'spectral', style: { labelText: 'Ciallo' }, }, behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'], plugins: [ { key: 'title', type: 'title', title: 'This is a title This is a title', subtitle: 'This is a sub-', }, ], layout: { type: 'circular' }, autoFit: 'view', }, { width: 600, height: 300 }, (gui, graph) => { const options = { align: 'left' }; const optionFolder = gui.addFolder('Align Options'); optionFolder.add(options, 'align', ['left', 'center', 'right']); optionFolder.onChange(({ property, value }) => { graph.updatePlugin({ key: 'title', [property]: value, }); graph.render(); }); }, ); ``` -------------------------------- ### Create Graph with Cubic Horizontal Edge Source: https://g6.antv.antgroup.com/en/manual/element/edge/cubic-horizontal Initializes a G6 graph with cubic-horizontal edges. Configure node and edge styles, layout, and behaviors. This example sets up a basic graph suitable for horizontal layouts. ```javascript 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 Data Structure Example Source: https://g6.antv.antgroup.com/en/manual/element/edge/overview Defines the structure for an edge in the graph's data object, including source, target, type, custom data, style, and states. ```json { "source": "alice", "target": "bob", "type": "line", "data": { "relationship": "friend", "strength": 5 }, "style": { "stroke": "green", "lineWidth": 2 }, "states": ["hover"] } ``` -------------------------------- ### Insert a Fixed-Position Purple Circle using upsert Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo Example of using the `upsert` method to add a circle graphic with specific styling and position to a container. Ensure the container is correctly passed. ```typescript this.upsert( 'element-key', // Unique identifier of the element 'circle', // Graphic type, such as 'rect', 'circle', etc. { x: 100, y: 100, fill: '#a975f3' }, // Style configuration object container, // Parent container ); ``` -------------------------------- ### Update Default Element Styles Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade Default element styles are now configured under '[element].style' in G6 5.x. For example, 'defaultNode' is changed to 'node.style'. ```javascript // 4.x { defaultNode: { size: 20, fill: 'red', } } // 5.x { node: { style: { size: 20, fill: 'red', } } } ``` -------------------------------- ### Initialize G6 Title Plugin Source: https://g6.antv.antgroup.com/en/manual/plugin/title Demonstrates the basic initialization of the Title plugin within a G6 Graph configuration. Ensure the 'title' plugin is included in the 'plugins' array. ```javascript const graph = new Graph({ plugins: [ { key: 'title', type: 'title', title: 'This is a title', subTitle: 'This is a subtitle', }, ], }); ``` -------------------------------- ### Initialize Graph with Edge Configuration Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Initializes a G6 graph with basic edge configurations, including type, style, state, palette, and animation. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ edge: { type: 'line', // Edge type style: {}, // Edge style state: {}, // State styles palette: {}, // Palette configuration animation: {}, }, }); ``` -------------------------------- ### Instantiate and Draw Tree Graphs with G6 5.0 Source: https://g6.antv.antgroup.com/en/manual/whats-new/feature Demonstrates how to use the `Graph` class directly to render tree graphs in G6 5.0 by specifying a tree graph layout and utilizing the `treeToGraphData` utility for data conversion. ```javascript 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(); ``` ```javascript 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(); ``` -------------------------------- ### Basic Text Watermark Configuration Source: https://g6.antv.antgroup.com/en/manual/plugin/watermark Demonstrates the simplest configuration for a text watermark in G6. ```javascript const graph = new Graph({ plugins: [ { type: 'watermark', text: 'G6 Graph', }, ], }); ``` -------------------------------- ### G6 4.0 Options vs. G6 5.0 Options Source: https://g6.antv.antgroup.com/en/manual/whats-new/feature Compare the configuration structure between G6 4.0 and G6 5.0. The 5.0 version offers a more intuitive and streamlined approach to defining graph properties. ```javascript { 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'], }, } ``` ```javascript { node: { style: { size: 30, fill: 'steelblue', stroke: '#666', lineWidth: 1 labelFill: '#fff', }, state: { hover: { fill: 'lightsteelblue' } } }, behaviors: ['zoom-canvas', 'drag-canvas', 'drag-element'], } ``` -------------------------------- ### Configure Auto-Switch Animation Plugin Source: https://g6.antv.antgroup.com/en/manual/plugin/custom-plugin Pass a configuration object to the 'plugins' array to enable and configure the 'auto-switch-animation' plugin. Specify the 'type' and any relevant parameters like 'maxLength'. ```javascript const graph = new Graph({ // Other configurations plugins: [ { type: 'auto-switch-animation', maxLength: 500, }, ], }); ``` -------------------------------- ### Dynamic Edge Style Configuration Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Shows how to dynamically configure edge style properties like 'stroke', 'lineWidth', 'lineDash', and 'labelText' based on edge data using arrow or regular functions. This allows for styles that adapt to data. ```javascript const graph = new Graph({ edge: { style: { // Static configuration stroke: '#1783FF', // Dynamic configuration - arrow function form lineWidth: (datum) => (datum.data.isImportant ? 3 : 1), // Dynamic configuration - regular function form (can access graph instance) lineDash: function (datum) { console.log(this); // graph instance return datum.data.type === 'dashed' ? [5, 5] : []; }, // Nested properties also support dynamic configuration labelText: (datum) => `Edge: ${datum.id}`, endArrow: (datum) => datum.data.hasArrow, }, }, }); ``` -------------------------------- ### render(attributes, container) Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo The main entry point for rendering custom combos. This method defines the structure and appearance of the combo using atomic graphics. ```APIDOC ## render(style, container) ### Description Implements the rendering logic for a custom combo. This method is responsible for drawing the combo using various atomic graphics and styles. ### Method `render(style: Record, container: Group): void` ### Parameters #### Parameters - **style** (Record) - Required - The style configuration for the combo. - **container** (Group) - Required - The container group where the combo will be rendered. ### Response This method does not return a value directly; it renders the combo into the provided container. ``` -------------------------------- ### Configure AutoFit Options Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade The 'fitView' and 'fitCenter' options are merged into 'autoFit' in G6 5.x. Configure 'autoFit' with 'view' or 'center' values, or provide an object for detailed configuration. ```javascript autoFit: { type: 'view', options: { // ... } } ``` -------------------------------- ### Configure multiple Hull plugins Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade To use multiple Hull instances, configure them as separate plugins in the `plugins` array. Operations like retrieving, updating, or removing Hulls are then managed via `setPlugins` and `updatePlugin`. ```javascript { plugins: ['hull', 'hull'], } ``` -------------------------------- ### Using WebGL Renderer in G6 5.0 Source: https://g6.antv.antgroup.com/en/manual/whats-new/feature Configure G6 5.0 to use the WebGL renderer by providing a factory function for the renderer during graph instantiation. This enables hardware acceleration for rendering. ```javascript import { Renderer } from '@antv/g-webgl'; import { Graph } from '@antv/g6'; const graph = new Graph({ // ... other configurations // Use the WebGL renderer renderer: () => new Renderer(), }); ``` -------------------------------- ### ComboCombined: Unified Layout Configuration (5.1) Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade-to-5-1 In G6 5.1, configure inner and outer layouts for ComboCombined using a single `layout` entry that accepts a function to determine configuration based on `comboId`. ```javascript import { ConcentricLayout, ForceLayout } from '@antv/layout'; { layout: { type: 'combo-combined', layout: (comboId) => comboId ? { type: 'concentric', sortBy: 'id' } : { type: 'force', gravity: 1 }, }, } ``` -------------------------------- ### Dynamic Edge Type Configuration Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Demonstrates dynamic configuration of the edge 'type' property using arrow functions or regular functions based on edge data. This allows for conditional edge shapes. ```javascript const graph = new Graph({ edge: { // Static configuration type: 'line', // Dynamic configuration - arrow function form type: (datum) => datum.data.edgeType || 'line', // Dynamic configuration - regular function form (can access graph instance) type: function (datum) { console.log(this); // graph instance return datum.data.importance > 5 ? 'polyline' : 'line'; }, }, }); ``` -------------------------------- ### Basic Edge Style Configuration Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Configures the basic appearance of the edge, such as stroke color and line width. ```javascript const graph = new Graph({ edge: { style: {}, }, }); ``` -------------------------------- ### Configure Renderer in G6 5.x Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade G6 5.x supports multi-layer canvases and defaults to the 'canvas' renderer. The 'renderer' option now expects a callback function instead of a string type. ```javascript // 4.x var options = { renderer: 'svg', }; // 5.x import { Renderer } from '@antv/g-svg'; { renderer: () => new Renderer(), } ``` -------------------------------- ### Configure Behavior Parameters Source: https://g6.antv.antgroup.com/en/manual/behavior/overview For behaviors requiring custom parameters, use the object form within the `behaviors` array. This allows setting specific options like `sensitivity` or assigning a unique `key` for later updates. ```javascript const graph = new Graph({ // Other configurations... behaviors: [ 'drag-canvas', { type: 'zoom-canvas', sensitivity: 1.5, // Configure sensitivity key: 'zoom-behavior', // Specify a key for the behavior for subsequent updates }, ], }); ``` -------------------------------- ### Download Graph as Image Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade Use this function to download the graph as a PNG image. It converts the graph to a DataURL and then creates a downloadable blob. ```javascript 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(); } ``` -------------------------------- ### Remote Data Loading Plugin Implementation Source: https://g6.antv.antgroup.com/en/manual/plugin/custom-plugin This plugin simulates loading data from a remote source during graph instantiation. It inherits from BasePlugin and automatically sets graph data and renders it. No data needs to be passed during Graph instantiation. ```typescript import { BasePlugin } from '@antv/g6'; import type { BasePluginOptions, RuntimeContext } from '@antv/g6'; interface RemoteDataSourceOptions extends BasePluginOptions {} class RemoteDataSource extends BasePlugin { constructor(context: RuntimeContext, options: RemoteDataSourceOptions) { super(context, options); this.loadData(); } private async loadData() { // mock remote data const data = { nodes: [ { id: 'node-1', x: 100, y: 100 }, { id: 'node-2', x: 200, y: 200 }, ], edges: [{ source: 'node-1', target: 'node-2' }], }; const { graph } = this.context; graph.setData(data); await graph.render(); } } ``` -------------------------------- ### Render Graph with Basic Edge Styling Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Renders a G6 graph with nodes and edges, applying basic static styles to the edges, such as stroke color and line width. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', 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', // Blue edge lineWidth: 2, // Edge width }, }, }); graph.render(); ``` -------------------------------- ### Dynamically Set Edge Style with graph.setEdge() Source: https://g6.antv.antgroup.com/en/manual/element/edge/overview Use `graph.setEdge()` to dynamically configure edge styles after graph instantiation. This method has the highest priority and must be called before `graph.render()`. ```javascript graph.setEdge({ style: { type: 'line', style: { stroke: '#5CACEE', lineWidth: 2 }, }, }); graph.render(); ``` -------------------------------- ### Accessing History Plugin Instance Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade To use undo/redo functionality, first obtain the history plugin instance using `getPluginInstance('history')`. Then, call methods like `redo()` on the instance. ```javascript // 'history' is the key configured for use with the plugin const history = graph.getPluginInstance('history'); history.redo(); ``` -------------------------------- ### Global Edge Configuration on Graph Instantiation Source: https://g6.antv.antgroup.com/en/manual/element/edge/overview Configure edge styles globally when creating a new Graph instance. This applies the specified style to all edges by default. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ edge: { type: 'line', style: { stroke: '#5CACEE', lineWidth: 2 }, }, }); ``` -------------------------------- ### Register Custom Plugin Source: https://g6.antv.antgroup.com/en/manual/plugin/custom-plugin This snippet shows how to register a custom plugin named 'my-custom-plugin' with G6 using the register function and ExtensionCategory.PLUGIN. ```javascript import { register, ExtensionCategory } from '@antv/g6'; import { MyCustomPlugin } from './my-custom-plugin'; register(ExtensionCategory.PLUGIN, 'my-custom-plugin', MyCustomPlugin); ``` -------------------------------- ### Define Edge State Styles Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Configure styles for specific edge states like 'focus'. This allows visual feedback for interactive behaviors. ```javascript const graph = new Graph({ edge: { state: { focus: { halo: true, haloLineWidth: 6, haloStroke: 'orange', haloStrokeOpacity: 0.6, }, }, }, }); ``` -------------------------------- ### Basic Text Label for Edges Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Configure a simple text label for an edge. Ensure the 'labelText' property is set. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, autoFit: 'center', data: { nodes: [ { id: 'node1', style: { x: 60, y: 60 } }, { id: 'node2', style: { x: 180, y: 60 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: 'Edge Label', labelFill: '#262626', labelFontSize: 12, labelPlacement: 'center', }, }, }); graph.render(); ``` -------------------------------- ### Update Element State Styles Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade Element state styles are now configured under '[element].state' in G6 5.x. For instance, 'nodeStateStyles' is now 'node.stateStyles'. ```javascript // 4.x { nodeStateStyles: { selected: { fill: 'red', } } } // 5.x { node: { state: { selected: { fill: 'red', } } } } ``` -------------------------------- ### Configure Multi-line Label Text Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Enable automatic line wrapping for edge labels and set maximum width and lines. Text exceeding 'labelMaxWidth' will wrap, and 'labelMaxLines' limits the number of lines displayed. ```javascript { "labelWordWrap": true, "labelMaxWidth": 200, "labelMaxLines": 3 } ``` -------------------------------- ### Define Custom Combo Class: HexagonCombo Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo Extends BaseCombo to create a custom hexagon-shaped combo. Implements methods for generating key path, style, and drawing the main shape and collapse button. Handles collapse/expand logic via event listeners. ```typescript import { BaseCombo, Group, } from '@antv/g6'; import type { BaseComboStyleProps } from '@antv/g6'; // Define button path generation functions 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 { // Get the path of the hexagon protected getKeyPath(attributes: Required) { const [width, height] = this.getKeySize(attributes); const padding = 10; const size = Math.min(width, height) + padding; // Calculate the vertices of the hexagon 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]); } // Construct the SVG path 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; } // Get the style of the main graphic, directly using path data 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, }; } // Draw the main graphic, using path type to directly pass in style objects protected drawKeyShape(attributes: Required, container: Group) { return this.upsert('key', 'path', this.getKeyStyle(attributes), container); } // Draw the collapse/expand button, using SVG paths for finer control 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); // Create the clickable area and button graphic 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); } // Use lifecycle hook methods to bind events 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); }); } } ``` -------------------------------- ### Configure Edge Stage Animations Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Define specific animation effects for different edge stages like 'enter', 'update', and 'exit'. You can specify fields to animate, duration, and easing. ```json { "edge": { "animation": { "update": [ { "fields": ["stroke"], "duration": 1000, "easing": "linear" } ] } } } ``` -------------------------------- ### Update Zoom Range Configuration Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade In G6 5.x, 'minZoom' and 'maxZoom' are combined into a single 'zoomRange' array, specifying the minimum and maximum zoom values. ```javascript // 4.x { minZoom: 0.5, maxZoom: 2, } // 5.x { zoomRange: [0.5, 2], } ``` -------------------------------- ### Define Combo States Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo Configure styles for different combo states directly in the combo configuration. These styles are applied automatically when the state is active. ```javascript 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', }, }, } ``` -------------------------------- ### Update Behavior Configuration Source: https://g6.antv.antgroup.com/en/manual/behavior/overview Modify the configuration of an existing behavior using the `updateBehavior` method. This requires the behavior to have a unique `key` assigned during initialization. You can change parameters like `sensitivity` or `enable` status. ```javascript // Update a single behavior graph.updateBehavior({ key: 'zoom-behavior', sensitivity: 2, enable: false, // Disable the behavior }); ``` -------------------------------- ### ComboCombined: Separate Inner/Outer Layouts (5.0) Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade-to-5-1 In G6 5.0, inner and outer layouts for ComboCombined were configured separately using `innerLayout` and `outerLayout` properties. ```javascript import { ConcentricLayout, ForceLayout } from '@antv/layout'; { layout: { type: 'combo-combined', innerLayout: new ConcentricLayout({ sortBy: 'id', }), outerLayout: new ForceLayout({ gravity: 1, }), }, } ``` -------------------------------- ### Use Built-in Edge Animations Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Apply built-in animation effects such as 'fade' or 'path-in' for specific edge stages. ```json { "edge": { "animation": { "enter": "fade", "update": "path-in", "exit": "fade" } } } ``` -------------------------------- ### Converting Graph to Data URL Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade Use the `toDataURL` method to convert the graph to a data URL. Specify `mode: 'overall'` to capture the entire graph. ```javascript graph.toDataURL({ mode: 'overall' }); ``` -------------------------------- ### Dynamic Edge Configuration in Data Source: https://g6.antv.antgroup.com/en/manual/element/edge/overview Define specific styles for individual edges directly within the edge data. This allows for varied configurations across different edges. ```javascript const data = { edges: [ { source: 'node-1', target: 'node-2', type: 'line', style: { stroke: 'orange' }, }, ], }; ``` -------------------------------- ### D3Force: Center Force Shortcut Fields (5.1) Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade-to-5-1 Use shortcut fields like `centerX`, `centerY`, and `centerStrength` for center force configuration in D3Force layout in G6 5.1. ```javascript { layout: { type: 'd3-force', centerX: 250, centerY: 150, centerStrength: 0.8, }, } ``` -------------------------------- ### Define Render Method Signature for Custom Combos Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo This is the signature for the `render` method, which is mandatory for all custom combo classes. It defines how the combo is visually rendered using its constituent graphics. ```typescript render(style: Record, container: Group): void; ``` -------------------------------- ### Use Default Edge Palette Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Apply a predefined default palette, such as 'tableau', for edge coloring. Colors are assigned by ID by default. ```json { "edge": { "palette": "tableau" } } ``` -------------------------------- ### Custom Watermark Styles Source: https://g6.antv.antgroup.com/en/manual/plugin/watermark Shows how to customize various style properties of a text watermark, including font, color, size, rotation, and positioning. ```javascript const graph = new Graph({ plugins: [ { type: 'watermark', text: 'G6 Graph', textFontSize: 20, textFontFamily: 'Arial', textFontWeight: 'bold', textFill: '#1890ff', rotate: Math.PI / 6, opacity: 0.15, width: 180, height: 100, backgroundRepeat: 'space', backgroundPosition: 'center', textAlign: 'center', textBaseline: 'middle', }, ], }); ``` -------------------------------- ### Adjusting Edge Configuration Priority Source: https://g6.antv.antgroup.com/en/manual/element/edge/overview Configure edge styles to prioritize settings defined in the data over global configurations. This is achieved by using a callback function in the global style to reference data attributes. ```javascript 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, }, }, }); ``` -------------------------------- ### Edge Label with Background Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Add a background to edge labels for improved visibility. Configure background appearance with 'labelBackgroundFill' and 'labelBackgroundRadius', and spacing with 'labelPadding'. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 120, autoFit: 'center', data: { nodes: [ { id: 'node1', style: { x: 60, y: 60 } }, { id: 'node2', style: { x: 180, y: 60 } }, ], edges: [{ source: 'node1', target: 'node2' }], }, edge: { style: { labelText: 'Important Connection', labelBackground: true, labelBackgroundFill: 'rgba(250, 140, 22, 0.1)', labelBackgroundRadius: 6, labelPadding: [4, 8], labelFill: '#D4380D', labelFontWeight: 'bold', labelPlacement: 'center', }, }, }); graph.render(); ``` -------------------------------- ### Customize Rendering Based on State Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo Override the `getKeyStyle` method in a custom combo to adjust rendering logic based on the element's current states. This allows for dynamic style adjustments. ```typescript protected getKeyStyle(attributes: Required) { const style = super.getKeyStyle(attributes); // Adjust style based on state if (attributes.states?.includes('selected')) { return { ...style, stroke: '#1890ff', lineWidth: 2, shadowColor: 'rgba(24,144,255,0.2)', shadowBlur: 15, }; } return style; } ``` -------------------------------- ### Update Animation Configuration Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade The 'animate' option is renamed to 'animation' in G6 5.x. Both 'animate' and 'animateCfg' are merged into the 'animation' configuration. ```javascript // 4.x { animate: true, } // 5.x { animation: true, } { animation: { duration: 500, easing: 'easeLinear', } } ``` -------------------------------- ### Configure Edge Pointer Events Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Control how edges respond to pointer events using the `pointerEvents` property. Set to 'stroke' to only respond in the stroke area, or 'none' for complete non-responsiveness. ```javascript // Example 1: Only stroke area responds to events const graph = new Graph({ edge: { style: { stroke: '#000', lineWidth: 2, pointerEvents: 'stroke', // Only stroke responds to events }, }, }); // Example 2: Completely non-responsive to events const graph = new Graph({ edge: { style: { pointerEvents: 'none', // Edge does not respond to any events }, }, }); ``` -------------------------------- ### Create Edges with Dashed Line Style Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Apply a dashed line style to edges by setting the `lineDash` property in the edge style configuration. ```javascript import { Graph } from '@antv/g6'; const graph = new Graph({ container: 'container', width: 240, height: 100, autoFit: 'center', 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], // Dashed line style lineDashOffset: 0, }, }, }); graph.render(); ``` -------------------------------- ### Dynamically Add Behavior Source: https://g6.antv.antgroup.com/en/manual/behavior/overview Add new behaviors to the graph instance at runtime using the `setBehaviors` method. Pass a function that receives the current behaviors and returns an updated array including the new behavior. ```javascript // Add new behavior graph.setBehaviors((behaviors) => [...behaviors, 'lasso-select']); ``` -------------------------------- ### Object Configuration: ScrollCanvas with Custom Parameters Source: https://g6.antv.antgroup.com/en/manual/behavior/scroll-canvas Configure the scroll-canvas behavior using an object for custom parameters. This method supports dynamic updates at runtime and allows for specific settings like sensitivity and direction. ```javascript const graph = new Graph({ // Other configurations... behaviors: [ { type: 'scroll-canvas', key: 'scroll-canvas-1', // Specify an identifier for the behavior for dynamic updates sensitivity: 1.5, // Set sensitivity direction: 'y', // Allow only vertical scrolling }, ], }); ``` -------------------------------- ### Configure ScrollCanvas with Arrow Keys Source: https://g6.antv.antgroup.com/en/manual/behavior/scroll-canvas Use the 'scroll-canvas' behavior to enable panning of the canvas using keyboard arrow keys. Specify the keys for each direction in the 'trigger' configuration. ```javascript const graph = new Graph({ // Other configurations... behaviors: [ { type: 'scroll-canvas', trigger: { up: ['ArrowUp'], down: ['ArrowDown'], left: ['ArrowLeft'], right: ['ArrowRight'], }, }, ], }); ``` -------------------------------- ### D3Force: Center Force (5.0) Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade-to-5-1 In G6 5.0, the center force was configured within the `center` object. ```javascript { layout: { type: 'd3-force', center: { x: 250, y: 150, strength: 0.8, }, }, } ``` -------------------------------- ### Update Interaction Modes to Behaviors Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade In G6 5.x, interaction modes are replaced by 'behaviors'. Use 'behaviors' to define active interactions and 'graph.setBehaviors()' to switch them. ```javascript // 4.x { modes: { default: ['drag-canvas', 'zoom-canvas'], preview: ['drag-canvas'], }, } graph.setMode('preview'); ``` ```javascript // 5.x { behaviors: ['drag-canvas', 'zoom-canvas'], } graph.setBehaviors(['drag-canvas']); ``` -------------------------------- ### Update Data Structure for Nodes and Edges Source: https://g6.antv.antgroup.com/en/manual/whats-new/upgrade In G6 5.x, style attributes must be placed within the 'style' object, while data attributes should be in the 'data' object. This applies to nodes, edges, and combos. ```javascript // 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: [ // The label is a non-stylistic attribute, placed in the data, and can be accessed in the style mapping function // The `size` is a stylistic attribute, placed within the `style` { id: 'node1', data: { label: 'node1' }, style: { size: 20 } }, { id: 'node2', data: { label: 'node2' }, style: { size: 20 } }, ], edges: [{ source: 'node1', target: 'node2' }], }; ``` -------------------------------- ### Configure Edge Palette by Field Source: https://g6.antv.antgroup.com/en/manual/element/edge/base-edge Define a group-based color palette for edges, mapping colors to the 'stroke' property based on a specified data field like 'direction'. ```json { "edge": { "palette": { "type": "group", "field": "direction", "color": ["#F08F56", "#00C9C9", "#D580FF"] } } } ``` -------------------------------- ### Switch Combo State Programmatically Source: https://g6.antv.antgroup.com/en/manual/element/combo/custom-combo Use the `setElementState` method on the graph instance to change the state of a specific combo. Pass the combo's ID and an array of desired states. ```javascript graph.setElementState(comboId, ['selected']); ```