AntV G 入门教程

下面是 AntV G(以下简称 G)的中文入门与核心 API 教程,涵盖从画布创建、图形绘制到事件与动画等常用方法,每个 API 均附带完整示例代码。示例引用自官方"Getting Started"指南 ([g.antv.antgroup.com][1])。


一、安装与引入

bash 复制代码
# 使用 npm(或 yarn / pnpm 同理)
npm install @antv/g --save
js 复制代码
// 在项目中引入 G 的核心模块
import { Canvas, Group, Rect, Circle, Line, Polygon, Path, Text, Image, Matrix } from '@antv/g';

二、创建 Canvas

2.1 构造函数

ts 复制代码
new Canvas({
  container: 'containerId', // 容器的 DOM id 或 HTMLElement
  width:  800,              // 画布宽度,默认为容器宽度
  height: 600,              // 画布高度
  pixelRatio: window.devicePixelRatio, // 设备像素比
  background: '#fff',       // 背景色
});

2.2 示例

html 复制代码
<!-- HTML -->
<div id="container" style="width:800px; height:600px;"></div>
js 复制代码
// JavaScript
const canvas = new Canvas({
  container: 'container',
  width: 800,
  height: 600,
  background: '#f5f5f5',
});

三、绘制基础图形

G 提供了一系列 Shape 类,你可以直接 appendChild 到 Canvas 或者 Group 上。

3.1 矩形 Rect

js 复制代码
const rect = new Rect({
  style: {
    x: 50,
    y: 50,
    width: 200,
    height: 100,
    fill: '#5B8FF9',
    stroke: '#3B76FF',
    lineWidth: 2,
    radius: 8,            // 圆角
    opacity: 0.85,
  },
});
canvas.appendChild(rect);

3.2 圆形 Circle

js 复制代码
const circle = new Circle({
  style: {
    x: 400,
    y: 100,
    r: 50,
    fill: '#61DDAA',
    stroke: '#3BAE9A',
    lineWidth: 3,
  },
});
canvas.appendChild(circle);

3.3 直线 Line

js 复制代码
const line = new Line({
  style: {
    x1: 50, y1: 200,
    x2: 300, y2: 200,
    stroke: '#F6BD16',
    lineWidth: 4,
    lineDash: [10, 5],
  },
});
canvas.appendChild(line);

3.4 多边形 Polygon

js 复制代码
const polygon = new Polygon({
  style: {
    points: [
      [400, 200],
      [450, 260],
      [420, 340],
      [360, 340],
      [330, 260],
    ],
    fill: '#FAD400',
    stroke: '#D4A200',
    lineWidth: 2,
  },
});
canvas.appendChild(polygon);

3.5 路径 Path

js 复制代码
const path = new Path({
  style: {
    path: [
      ['M', 100, 400],
      ['C', 150, 350, 250, 450, 300, 400],
      ['L', 300, 500],
      ['Z'],
    ],
    fill: '#FF4D4F',
  },
});
canvas.appendChild(path);

3.6 文本 Text

js 复制代码
const text = new Text({
  style: {
    x: 400,
    y: 400,
    text: 'Hello, G!',
    fill: '#262626',
    fontSize: 24,
    textAlign: 'center',
    textBaseline: 'middle',
  },
});
canvas.appendChild(text);

3.7 图片 Image

js 复制代码
const img = new Image({
  style: {
    x: 500,
    y: 300,
    width: 100,
    height: 100,
    img: 'https://example.com/logo.png',
  },
});
canvas.appendChild(img);

四、使用 Group 分组

js 复制代码
const group = new Group();
canvas.appendChild(group);

// 将多个图形加入同一个组,方便统一变换或事件绑定
group.appendChild(new Rect({
  style: { x: 50, y: 520, width: 150, height: 60, fill: '#9254DE' },
}));
group.appendChild(new Text({
  style: { x: 125, y: 550, text: '分组示例', fill: '#fff', textAlign: 'center' },
}));

五、坐标变换与 Matrix

5.1 变换方法(针对单个元素)

js 复制代码
// 平移
rect.translate(100, 50);
// 旋转(角度制)
circle.rotate((Math.PI / 180) * 45, 400, 100);
// 缩放(相对于元素自身坐标原点)
polygon.scale(1.5, 1.5, 400, 260);

5.2 矩阵工具

js 复制代码
// 获取元素当前的变换矩阵
const m = line.getComputedMatrix(); // [a, b, c, d, e, f]

// 矩阵相乘
const m2 = Matrix.multiply(m, [1, 0, 0, 1, 20, 20]);

// 将客户端(页面)坐标转为画布坐标
const pt = canvas.getPointByClient(100, 100);

六、事件系统

G 的事件模型兼容 DOM API,可在 Canvas、Group 或单个 Shape 上注册。

js 复制代码
// 在元素上监听
rect.on('mouseenter', () => {
  rect.attr('opacity', 1);
});
rect.on('mouseleave', () => {
  rect.attr('opacity', 0.8);
});
rect.on('click', (ev) => {
  console.log('点击坐标:', ev.clientX, ev.clientY);
});

// 在画布上监听所有"点位"事件
canvas.on('pointerdown', (ev) => {
  console.log('按下:', ev.target.get('id'));
});

七、动画 API

js 复制代码
// 为单个属性创建动画
circle.animate(
  [{ r: 50 }, { r: 80 }, { r: 50 }],
  {
    duration: 2000,
    iterations: Infinity,
    easing: 'easeCubicInOut',
  }
);

// 停止动画
circle.stopAnimate();

八、交互示例:拖拽

js 复制代码
// 给元素启用拖拽
rect.on('pointerdown', (ev) => {
  canvas.setCursor('move');
  const start = { x: ev.x, y: ev.y };
  const origin = { x: rect.attr('x'), y: rect.attr('y') };
  const move = (moveEvt) => {
    const dx = moveEvt.x - start.x;
    const dy = moveEvt.y - start.y;
    rect.attr({ x: origin.x + dx, y: origin.y + dy });
  };
  const up = () => {
    canvas.setCursor('default');
    canvas.off('pointermove', move);
    canvas.off('pointerup', up);
  };
  canvas.on('pointermove', move);
  canvas.on('pointerup', up);
});

九、导出与销毁

js 复制代码
// 将画布导出为 DataURL
const dataURL = canvas.toDataURL('image/png', { backgroundColor: '#fff' });

// 清空所有元素
canvas.clear();

// 销毁 Canvas,释放资源
canvas.destroy();

十、小结

  1. 核心类CanvasGroup、各种 ShapeRectCirclePathText 等)。
  2. 绘图流程:创建 Canvas → appendChild Shape/Group → 调用属性与方法 → 渲染自动完成。
  3. 坐标与变换translaterotatescaleMatrix 工具。
  4. 事件与交互:兼容 DOM 事件模型,支持自定义拖拽、缩放等行为。
  5. 动画element.animate(keyframes, options) 简洁强大。
  6. 导出销毁toDataURLcleardestroy 方便画布管理。
相关推荐
杨超越luckly1 天前
HTML应用指南:利用GET请求获取全国小米之家门店位置信息
前端·arcgis·html·数据可视化·shp
新中地GIS开发老师2 天前
准大一GIS专业新生,如何挑选电脑?
javascript·arcgis·电脑·gis·大学生·webgis·地理信息科学
Bigemap软件3 天前
BigemapPro吸附功能 | 绘图共点共边,标绘从此无缝衔接!
arcgis·信息可视化·软件需求·地图·bigemappro
杨超越luckly8 天前
HTML应用指南:利用GET请求获取全国奈雪的茶门店位置信息
大数据·前端·python·arcgis·信息可视化·html
zhou_x_b8 天前
解决栅格数据裁剪矢量数据问题两种方法,ArcGIS解决与PYTHON解决
arcgis
维维180-3121-14558 天前
ArcGIS水文及空间分析与SWMM融合协同在城市排水防涝领域中的应用
arcgis·水文·内涝
GIS小小研究僧12 天前
ArcGIS Pro+PS 实现地形渲染效果图
arcgis·gis·qgis·地理信息
杨超越luckly13 天前
Python应用指南:使用PyKrige包实现ArcGIS的克里金插值法
python·算法·arcgis·信息可视化·克里金法
WangYan202213 天前
Python+ArcGIS+AI蒸散发与GPP估算|Penman-Monteith模型|FLUXNET数据处理|多源产品融合|专业科研绘图与可视化等
arcgis·蒸散发·光合作用·植被生产力估算
清纯世纪15 天前
Arcgis 10.7 矢量的分区统计
arcgis