下面是 AntV?G(以下簡稱 G)的中文入門與核心 API 教程,涵蓋從畫布創建、圖形繪制到事件與動畫等常用方法,每個 API 均附帶完整示例代碼。示例引用自官方“Getting Started”指南 ([g.antv.antgroup.com][1])。
一、安裝與引入
# 使用 npm(或 yarn / pnpm 同理)
npm install @antv/g --save
// 在項目中引入 G 的核心模塊
import { Canvas, Group, Rect, Circle, Line, Polygon, Path, Text, Image, Matrix } from '@antv/g';
二、創建 Canvas
2.1 構造函數
new Canvas({container: 'containerId', // 容器的 DOM id 或 HTMLElementwidth: 800, // 畫布寬度,默認為容器寬度height: 600, // 畫布高度pixelRatio: window.devicePixelRatio, // 設備像素比background: '#fff', // 背景色
});
2.2 示例
<!-- HTML -->
<div id="container" style="width:800px; height:600px;"></div>
// JavaScript
const canvas = new Canvas({container: 'container',width: 800,height: 600,background: '#f5f5f5',
});
三、繪制基礎圖形
G 提供了一系列 Shape 類,你可以直接 appendChild
到 Canvas 或者 Group 上。
3.1 矩形 Rect
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
const circle = new Circle({style: {x: 400,y: 100,r: 50,fill: '#61DDAA',stroke: '#3BAE9A',lineWidth: 3,},
});
canvas.appendChild(circle);
3.3 直線 Line
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
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
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
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
const img = new Image({style: {x: 500,y: 300,width: 100,height: 100,img: 'https://example.com/logo.png',},
});
canvas.appendChild(img);
四、使用 Group 分組
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 變換方法(針對單個元素)
// 平移
rect.translate(100, 50);
// 旋轉(角度制)
circle.rotate((Math.PI / 180) * 45, 400, 100);
// 縮放(相對于元素自身坐標原點)
polygon.scale(1.5, 1.5, 400, 260);
5.2 矩陣工具
// 獲取元素當前的變換矩陣
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 上注冊。
// 在元素上監聽
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
// 為單個屬性創建動畫
circle.animate([{ r: 50 }, { r: 80 }, { r: 50 }],{duration: 2000,iterations: Infinity,easing: 'easeCubicInOut',}
);// 停止動畫
circle.stopAnimate();
八、交互示例:拖拽
// 給元素啟用拖拽
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);
});
九、導出與銷毀
// 將畫布導出為 DataURL
const dataURL = canvas.toDataURL('image/png', { backgroundColor: '#fff' });// 清空所有元素
canvas.clear();// 銷毀 Canvas,釋放資源
canvas.destroy();
十、小結
- 核心類:
Canvas
、Group
、各種Shape
(Rect
、Circle
、Path
、Text
等)。 - 繪圖流程:創建 Canvas → appendChild Shape/Group → 調用屬性與方法 → 渲染自動完成。
- 坐標與變換:
translate
、rotate
、scale
及Matrix
工具。 - 事件與交互:兼容 DOM 事件模型,支持自定義拖拽、縮放等行為。
- 動畫:
element.animate(keyframes, options)
簡潔強大。 - 導出銷毀:
toDataURL
、clear
、destroy
方便畫布管理。