logo

G

  • Tutorials
  • API
  • Examples
  • Plugins
  • Productsantv logo arrow
  • 6.1.26
  • Getting Started
  • Section I - Defining the Scenario
  • Section II - Using the renderer
  • Section III - Adding some interaction
  • Diving Deeper
    • Scene Graph
    • 创造一个“太阳系”
    • 使用相机
    • 使用插件
    • 实现一个简单的动画
    • GPGPU 初体验
    • 进入 3D 世界
    • 使用 Box2D 物理引擎
    • 使用 matter.js 物理引擎
    • 使用 Yoga 布局引擎
    • Takeover D3's rendering
    • Takeover Observable Plot's rendering
    • Choose a renderer
    • Rendering on demand
  • Advanced Topics
    • 性能优化
    • 自定义图形
    • 理解事件传播路径
    • Using react-g
    • Exporting the contents of the canvas
    • Using lite version

使用插件

Previous
使用相机
Next
实现一个简单的动画

Resource

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

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

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
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

插件可以极大程度丰富渲染器的能力,在本教程中我们将使用 g-webgl 渲染器,配合 g-plugin-3d 插件渲染一个简单的立方体。更多用法可以参考插件系统。

其中会涉及以下 API:

  • 使用 registerPlugin 为渲染器注册插件
  • 使用 getCamera 获取画布相机
  • 使用 setPosition 设置相机位置

最终示例:

  • 官网示例
  • CodeSandbox 示例

使用 WebGL 渲染器

我们使用 g-webgl 渲染器,并为其注册:

  • g-plugin-3d 提供 3D 渲染能力
  • g-plugin-control 提供交互能力
import { Canvas } from '@antv/g';
import { Renderer } from '@antv/g-webgl';
import { Plugin as Plugin3D } from '@antv/g-plugin-3d';
import { Plugin as PluginControl } from '@antv/g-plugin-control';
// 创建 WebGL 渲染器
const webglRenderer = new Renderer();
// 注册 3D 插件
webglRenderer.registerPlugin(new Plugin3D());
// 注册 Control 插件
webglRenderer.registerPlugin(new PluginControl());
// 创建画布
const canvas = new Canvas({
container: 'container',
width: 600,
height: 500,
renderer: webglRenderer,
});

创建一个立方体

我们创建一个 200 * 200 * 200 的立方体,并通过 map 给它贴个图:

import {
MeshBasicMaterial,
CubeGeometry,
Mesh,
Plugin as Plugin3D,
} from '@antv/g-plugin-3d';
const cubeGeometry = new CubeGeometry();
const basicMaterial = new MeshBasicMaterial({
map: 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*_aqoS73Se3sAAAAAAAAAAAAAARQnAQ',
});
const cube = new Mesh({
style: {
fill: '#1890FF',
opacity: 1,
width: 200,
height: 200,
depth: 200,
geometry: cubeGeometry,
material: basicMaterial,
},
});
canvas.appendChild(cube);

然后使用 setPosition 移动它到画布中央:

cube.setPosition(300, 250, 0);

调整相机视角

现在让我们将相机位置稍稍调整一下,来到立方体的斜上方观察。

  • 使用 getCamera 获取画布相机
  • 使用 setPosition 设置相机位置
const camera = canvas.getCamera();
camera.setPosition(300, 0, 500);

旋转起来

让立方体旋转和其他基础图形一样,使用 rotate 即可:

canvas.addEventListener(CanvasEvent.AFTER_RENDER, () => {
cube.rotate(0, 1, 0); // 绕 Y 轴旋转 1 度
});