logo

G2

  • Chart Gallery
  • Docs
  • Examples
  • Theme
  • Ecosystem
  • Productsantv logo arrow
  • 5.4.6
  • Get Started
  • Introduction
    • What is G2
    • Using in Frontend Frameworks
    • Experimental Spec API
  • Chart API
  • Core Concepts
    • G2's complete configuration system
    • Chart
      • Components of G2 Charts
      • Chart Lifecycle
    • Mark
      • Overview
      • area
      • box
      • boxplot
      • cell
      • chord
      • density
      • gauge
      • heatmap
      • image
      • interval
      • line
      • lineX
      • lineY
      • link
      • liquid
      • sunburst
      • beeswarm
      • point
      • polygon
      • range
      • rangeX
      • rangeY
      • rect
      • shape
      • text
      • vector
      • connector
      • wordCloud
    • View
    • Data
      • Overview
      • custom
      • ema
      • fetch
      • filter
      • fold
      • inline
      • join
      • kde
      • log
      • map
      • pick
      • rename
      • slice
      • sort
      • sortBy
    • Encode
    • Scale
      • Overview
      • band
      • linear
      • log
      • ordinal
      • point
      • quantile
      • quantize
      • sqrt
      • threshold
      • time
      • pow
    • Transform
      • Overview
      • bin
      • binX
      • diffY
      • dodgeX
      • flexX
      • group
      • groupColor
      • groupX
      • groupY
      • jitter
      • jitterX
      • jitterY
      • normalizeY
      • pack
      • sample
      • select
      • selectX
      • selectY
      • sortColor
      • sortX
      • sortY
      • stackEnter
      • stackY
      • symmetryY
    • Coordinate
      • Overview
      • fisheye
      • parallel
      • polar
      • theta
      • transpose
      • radial
      • cartesian3D
      • helix
    • Style
    • Animate
      • Overview
      • fadeIn
      • fadeOut
      • growInX
      • growInY
      • morphing
      • pathIn
      • scaleInX
      • scaleInY
      • scaleOutX
      • scaleOutY
      • waveIn
      • zoomIn
      • zoomOut
    • State
    • Interaction
      • Overview
      • brushAxisHighlight
      • brushHighlight
      • brushXHighlight
      • brushYHighlight
      • brushFilter
      • brushXFilter
      • brushYFilter
      • chartIndex
      • elementHighlight
      • elementHighlightByColor
      • elementHoverScale
      • elementHighlightByX
      • elementSelect
      • elementSelectByColor
      • elementSelectByX
      • legendFilter
      • legendHighlight
      • poptip
      • scrollbarFilter
      • sliderFilter
      • sliderWheel
      • fisheye
    • Composition
      • Overview
      • facetCircle
      • facetRect
      • repeatMatrix
      • spaceFlex
      • spaceLayer
      • timingKeyframe
    • Theme
      • Overview
      • academy
      • classic
      • classicDark
    • Events
    • Color Mapping
  • Chart Component
    • Title
    • Axis
    • Legend
    • Scrollbar
    • Slider
    • Tooltip
    • Data Label
  • Extra Topics
    • Graph
      • forceGraph
      • pack
      • sankey
      • tree
      • treemap
    • Geo
      • geoPath
      • geoView
    • 3D
      • Draw 3D Chart
      • point3D
      • line3D
      • interval3D
      • surface3D
    • Plugin
      • renderer
      • rough
      • lottie
      • a11y
    • Package on demand
    • Set pattern
    • Server-Side Rendering (SSR)
    • Spec Function Expression Support (Available in 5.3.0)
  • Whats New
    • New Version Features
    • Migration from v4 to v5
  • Frequently Asked Questions (FAQ)

Events

Previous
classicDark
Next
Color Mapping

Resource

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library
WeaveFox-AI Coding Assistant

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference
weavefoxWeaveFox-AI Developer Community

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-Interactive solution
weavefoxWeaveFox-AI Coding Assistant
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

G2 exposes various events to capture chart lifecycle and interaction information. G2 exports a ChartEvent type that defines the event types.

click event
import { Chart, ChartEvent } from '@antv/g2';
const chart = new Chart({
container,
canvas,
});
chart.data([
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
]);
chart
.interval()
.encode('x', 'genre')
.encode('y', 'sold')
.encode('color', 'genre')
.axis({ x: { animate: false }, y: { animate: false } });
chart.on('interval:click', (e) => {
console.log(e.data.data); // Display clicked data
});
chart.on('element:click', (e) => {
console.log(e.data.data); // Display clicked data
});
chart.render();

Lifecycle Events

To capture chart lifecycle information, you can use the following approach:

chart.on(ChartEvent.AFTER_RENDER, (ev) => {
console.log(ev);
});

G2 currently provides the following lifecycle events:

Event NameDescription
ChartEvent.BEFORE_RENDERBefore rendering
ChartEvent.BEFORE_PAINTBefore painting
ChartEvent.AFTER_PAINTAfter painting
ChartEvent.AFTER_RENDERAfter rendering
ChartEvent.BEFORE_CHANGE_DATABefore data change
ChartEvent.AFTER_CHANGE_DATAAfter data change
ChartEvent.BEFORE_CLEARBefore clearing canvas
ChartEvent.AFTER_CLEARAfter clearing canvas
ChartEvent.BEFORE_DESTROYBefore destroying canvas
ChartEvent.AFTER_DESTROYAfter destroying canvas
ChartEvent.BEFORE_CHANGE_SIZEBefore changing canvas size
ChartEvent.AFTER_CHANGE_SIZEAfter changing canvas size
  • Before rendering: When G2 starts processing data, performing layout, and drawing graphics.
  • Before painting: When data processing, layout, and graphics operations are complete but painting hasn't started.
  • After painting: When G2 completes all painting operations, but animations may still be running. The chart is fully rendered when animations finish.
  • After rendering: When G2 completes all painting operations, including animations.
  • After clearing canvas: The chart in the container has been cleared, but the G2 instance still exists and can be reused.
  • After destroying canvas: The G2 instance has been destroyed and cannot be used anymore.

Interaction Events

To capture chart interaction information, you can use the following approaches:

  • Listen to global element events
chart.on(`element:${ChartEvent.EventType}`, (ev) => {
console.log(ev);
});
  • Listen to specific element events
chart.on(`${markType}:${ChartEvent.EventType}`, (ev) => {
console.log(ev);
});
// For example, listen to click events on bars in a bar chart
chart.on(`interval:${ChartEvent.CLICK}`, (ev) => {
console.log(ev);
});
  • Listen to plot area events
chart.on('plot:click', (event) => console.log(event));
  • Listen to global component events
chart.on('component:click', (event) => console.log(event));
  • Listen to global label events
chart.on('label:click', (event) => console.log(event));

Click Events

Event NameDescriptionCallback Parameters
ChartEvent.CLICKClickEvent
ChartEvent.DBLCLICKDouble clickEvent

Pointer Events

Event NameDescriptionCallback Parameters
ChartEvent.POINTER_TAPEvent
ChartEvent.POINTER_DOWNWhen pointer is pressed downEvent
ChartEvent.POINTER_UPWhen pointer is releasedEvent
ChartEvent.POINTER_OVERWhen pointer enters the target elementEvent
ChartEvent.POINTER_OUTWhen pointer leaves the target elementEvent
ChartEvent.POINTER_MOVEWhen pointer coordinates changeEvent
ChartEvent.POINTER_ENTERWhen pointer enters the target element or its descendantsEvent
ChartEvent.POINTER_LEAVEWhen pointer leaves the target element or its descendantsEvent
ChartEvent.POINTER_UPOUTSIDEEvent

Drag Events

To listen to drag events, you need to set the draggable and droppable properties:

chart.interval().style('draggable', true).style('droppable', true);
Event NameDescriptionCallback Parameters
ChartEvent.DRAG_STARTWhen dragging startsEvent
ChartEvent.DRAGDuring draggingEvent
ChartEvent.DRAG_ENDWhen dragging endsEvent
ChartEvent.DRAG_ENTERWhen element is dragged into the target elementEvent
ChartEvent.DRAG_LEAVEWhen element is dragged away from the target elementEvent
ChartEvent.DRAG_OVERWhen element is dragged and hovering over target elementEvent
ChartEvent.DROPWhen element is dropped into the target elementEvent

Fine-grained Control with className

G2 provides standardized className for various component elements in charts, enabling more precise event handling and style control.

Listening to Specific Component Element Events

Using className allows you to precisely identify the type of element clicked by users. For example, listening to legend item click events:

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart.data([
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
]);
chart
.interval()
.encode('x', 'genre')
.encode('y', 'sold')
.encode('color', 'genre');
chart.render().then(() => {
const { canvas } = chart.getContext();
const { document } = canvas;
const legendItems = document.getElementsByClassName('g2-legend-item');
const legendMarkers = document.getElementsByClassName('g2-legend-marker');
const legendLabels = document.getElementsByClassName('g2-legend-label');
const legendData = Array.from(legendItems).map((item) => item.__data__);
legendLabels.forEach((label, index) => {
const labelText = label.getAttribute('text') || label.textContent;
label.addEventListener('click', (event) => {
const clickedText = label.getAttribute('text') || label.textContent;
const itemData = legendData[index];
console.log('\n 🖱️ Legend label clicked:');
console.log(' - Label text:', clickedText);
console.log(' - Index:', index);
console.log(' - Data:', itemData);
console.log(' - className:', label.className);
// Simulate business logic: perform actions based on clicked legend
alert(`You clicked legend: ${clickedText}
You can trigger custom business logic here, such as:
- Navigate to detail page
- Show more information
- Link with other charts`);
});
});
});

Filtering Specific Component Events

Using className makes it easy to filter out events from certain components to avoid interference:

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart.data([
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
]);
chart
.interval()
.encode('x', 'genre')
.encode('y', 'sold')
.encode('color', 'genre');
chart.render();
// Listen to plot clicks, but exclude legend clicks
chart.on('plot:click', (event) => {
const className = event.target?.className || '';
// Check if legend was clicked
const isLegendClick = className.includes('legend');
if (isLegendClick) {
console.log('Legend clicked, ignoring plot:click event');
return;
}
// Handle plot area click logic
console.log('Plot area clicked', event);
});

Controlling Element Styles with className

You can retrieve specific elements by className and dynamically modify their styles:

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart.data([
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
]);
chart
.interval()
.encode('x', 'genre')
.encode('y', 'sold')
.encode('color', 'genre');
chart.render().then(() => {
const { canvas } = chart.getContext();
const { document } = canvas;
const legendItems = document.getElementsByClassName('g2-legend-item');
// Modify the style of the first legend item
if (legendItems.length > 0) {
const firstItem = legendItems[0];
const firstMarker = firstItem.getElementsByClassName('g2-legend-marker')[0];
const firstLabel = firstItem.getElementsByClassName('g2-legend-label')[0];
// Add highlight styles
if (firstLabel) {
firstLabel.style.fontWeight = 'bold';
firstLabel.style.fill = 'orange';
firstLabel.style.shadowColor = '#d3d3d3';
firstLabel.style.shadowBlur = 10;
firstLabel.style.shadowOffsetX = 5;
firstLabel.style.shadowOffsetY = 5;
}
}
});

Finding Specific Elements by Content

Combining className with element attributes allows precise location of specific chart elements:

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart.data([
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
]);
chart
.interval()
.encode('x', 'genre')
.encode('y', 'sold')
.encode('color', 'genre');
chart.render().then(() => {
const { canvas } = chart.getContext();
const { document } = canvas;
const legendItems = document.getElementsByClassName('g2-legend-item');
const targetText = 'Action';
let targetItem = null;
// Iterate through all legend labels to find target text
for (let i = 0; i < legendItems.length; i++) {
const labels = legendItems[i].getElementsByClassName('g2-legend-label');
if (labels.length > 0) {
const labelText = labels[0].getAttribute('text') || labels[0].textContent;
if (labelText === targetText) {
targetItem = legendItems[i];
break;
}
}
}
if (targetItem) {
console.log(`✅ Found target legend: "${targetText}"`);
console.log(' className:', targetItem.className);
console.log(' Business logic can be executed: e.g., auto-focus, highlight, etc.');
// Add background color and special styles to target legend item
console.log(`🎨 Adding special styles to legend "${targetText}"...`);
// Get the background element of legend item
const background = targetItem.getElementsByClassName(
'g2-legend-background',
)[0];
const label = targetItem.getElementsByClassName('g2-legend-label')[0];
const marker = targetItem.getElementsByClassName('g2-legend-marker')[0];
// Modify background color
if (background) {
background.style.fill = '#FFF3E0'; // Light orange background
background.style.fillOpacity = 0.8;
}
// Also modify label style
if (label) {
label.style.fill = '#FF6B00'; // Orange text
label.style.fontWeight = 'bold';
}
}
});

Complete List of G2 Component className

Legend Component

classNameDescription
g2-legend-titleLegend title
g2-legend-itemContainer for category legend item
g2-legend-backgroundBackground of category legend item
g2-legend-markerMarker icon of category legend item
g2-legend-labelLabel text of category legend item
g2-legend-valueValue of category legend item
g2-legend-focus-iconFocus icon of category legend item
g2-legend-ribbonColor ribbon of continuous legend
g2-legend-trackTrack of continuous legend
g2-legend-selectionSelection area of continuous legend
g2-legend-handleSlider handle of continuous legend
g2-legend-handle-markerSlider handle icon of continuous legend
g2-legend-handle-labelLabel/tick value of continuous legend

Axis Component

classNameDescription
g2-axis-lineMain axis line
g2-axis-tickAxis tick line
g2-axis-tick-itemSingle tick item
g2-axis-labelAxis tick label
g2-axis-label-itemSingle label item
g2-axis-titleAxis title
g2-axis-gridAxis grid line

Typical Use Cases

For detailed examples, see Interaction - Events Examples