Skip to content
大纲

视图元素

G2 中包含 ViewChartGeometry 三层容器

  • View 拥有独立的数据源、坐标系、几何标记、图形组件,View 可以包含多个子 View
  • Chart 继承自 View 并提供绘制的能力
  • Geometry 根据视觉通道 colorsizeshape 对数据进行分组然后绘制

创建视图

由于 View 缺少绘制能力,一般通过 Chart 进行创建
chart 在实例化时默认生成一层 View
通过 chart.createView 可以创建多层 View
创建的 View 区域同 chart 或通过 region 进行配置
View 通常用于进行 chart 区域划分或层级叠加

js
import { Chart } from "@antv/g2";
const chart = new Chart({
  container: "contaienr",
  witdh: 1e3,
  height: 6e2,
});
const view = chart.createView({
  region: {
    start: { x: 0.1, y: 0.1 }, // [0-1] 范围
    end: { x: 0.9, y: 0.9 },
  },
  padding: [20, 30],
});
view.data(data);
view.line().position("x*y");
chart.render(); // view 不负责绘制, 由 chart 统一处理

图形元素

Geometry 针对给定的数据进行绘制,其中每一条/一组数据绘制对应的元素为 Element
单条数据对应的 Element 包括: pointintervalpolygonschemaedge
集合数据对应的 Element 包括: linepatharea
Element 提供了绘制、更新、销毁 shape 及对 shape 状态管理的操作方式
图形状态包括: activeselectedinactive

相关操作

ts
// 获取元素
class Geometry extends Base {
  elements: Element[];
}
ts
// 管理状态
class Element extends Base {
  // 设置 Element 的状态,这三种状态相互独立,可以进行叠加。
  setState(state: "active" | "selected" | "inactive",, status: boolean): void;
  clearStates(): void;
  hasState(stateName: string): boolean;
}

注意:

  • 操作 Elements 需要在图表渲染之后
  • 不同类型的 GeometryElements 个数不同(如 line 为单个,interval 为多个)

操作示例

js
import { Chart } from "@antv/g2";
const data = new Array(50)
  .fill(undefined)
  .map((v, i) => ({ x: i * 10, y: parseInt("" + Math.random() * 100) }));
const chart = new Chart({
  container: "chart",
  width: 800,
  height: 500,
});
const geom = chart
  .interval()
  .position("x*y")
  .shape("smooth")
  .state({ active: { style: { fill: "red" } } });
chart.data(data);
chart.render();
geom.elements.forEach(
  ele => ele.getData().y > 50 && ele.setState("active", true)
);