Loading...
G6 provides a series of drawing and rendering-related APIs to control the display process of graphical elements. In G6, drawing and rendering are two different concepts:
Understanding the differences between these APIs is crucial for optimizing performance and achieving specific effects.
Draw elements without performing layout calculations.
draw(): Promise<void>;
Note
The draw
method only executes the drawing process of elements and does not recalculate the layout.
⚠️ Attention: draw
is an asynchronous method, requiring the use of await
or Promise chaining to ensure subsequent operations are executed after drawing is complete.
Example 1: Basic Usage
// Basic usageawait graph.draw();
Example 2: Redraw after modifying node styles
// Redraw after modifying node stylesgraph.updateNodeData([{id: 'node1',style: {fill: 'red',stroke: 'blue',lineWidth: 2,},},]);// Only draw the updated styles without re-layoutawait graph.draw();
Example 3: Batch update multiple elements and draw once
// Update multiple nodesgraph.updateNodeData([{ id: 'node1', style: { fill: 'red' } }]);graph.updateNodeData([{ id: 'node2', style: { fill: 'blue' } }]);// Update edgesgraph.updateEdgeData([{ id: 'edge1', style: { stroke: 'green' } }]);// Draw after batch operationsawait graph.draw();
Example 4: Use event listener to detect drawing completion
import { GraphEvent } from '@antv/g6';graph.on(GraphEvent.AFTER_DRAW, () => {console.log('Drawing complete');});await graph.draw();
Execute the complete rendering process, including data processing, layout calculations, and drawing.
render(): Promise<void>;
Note
The render
method executes the complete rendering process:
Example 1: Basic Usage
// Basic usageawait graph.render();
Example 2: Render after adding new data
graph.addData({nodes: [{ id: 'node3' }, { id: 'node4' }],edges: [{ id: 'edge2', source: 'node1', target: 'node3' }],});await graph.render();
Example 3: Listen to rendering events
import { GraphEvent } from '@antv/g6';// Before rendering startsgraph.on(GraphEvent.BEFORE_RENDER, () => {console.log('Rendering starts...');// Show loading indicatorshowLoadingIndicator();});// After rendering completesgraph.on(GraphEvent.AFTER_RENDER, () => {console.log('Rendering complete');// Hide loading indicatorhideLoadingIndicator();});graph.render();
Clear all elements on the canvas, including nodes, edges, and other graphical elements.
clear(): Promise<void>;
Note
This method deletes all elements in the graph but retains the canvas configuration and styles. It is an asynchronous method that returns a Promise.
Example
// Basic usageawait graph.clear();
draw()
when:
render()
when: