logo

G

  • 教程
  • API
  • 示例
  • 插件
  • 所有产品antv logo arrow
  • 6.1.26
  • 开始使用
  • 第一节:定义场景
  • 第二节:使用渲染器
  • 第三节:增加交互
  • 进阶内容
    • 场景图
    • 创造一个“太阳系”
    • 使用相机
    • 实现一个简单的动画
    • 使用插件
    • GPGPU 初体验
    • 进入 3D 世界
    • 使用 Box2D 物理引擎
    • 使用 matter.js 物理引擎
    • 使用 Yoga 布局引擎
    • 接管 D3 渲染
    • 接管 Observable Plot 渲染
    • 按需引入渲染器
    • 按需渲染
  • 高级话题
    • 性能优化
    • 自定义图形
    • 理解事件传播路径
    • 使用 React 定义图形
    • 导出画布内容
    • 使用轻量版

使用 Yoga 布局引擎

上一篇
使用 matter.js 物理引擎
下一篇
接管 D3 渲染

资源

Ant Design
Galacea Effects
Umi-React 应用开发框架
Dumi-组件/文档研发工具
ahooks-React Hooks 库

社区

体验科技专栏
seeconfSEE Conf-蚂蚁体验科技大会

帮助

GitHub
StackOverflow

more products更多产品

Ant DesignAnt Design-企业级 UI 设计语言
yuque语雀-知识创作与分享工具
EggEgg-企业级 Node 开发框架
kitchenKitchen-Sketch 工具集
GalaceanGalacean-互动图形解决方案
xtech蚂蚁体验科技
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Yoga 是 Facebook 提供的跨平台布局引擎,基于 Flex,属性和 CSS Flex 完全一致,因此也可以阅读 MDN flex 布局的基本概念 获取更多概念知识。

通过 g-plugin-yoga 插件的支持,我们可以给已有 2D 图形增加 Flex 属性。

在该示例中,我们创建了一个常见的自适应布局效果:

注册插件

创建一个渲染器并注册插件:

import { Canvas, CanvasEvent } from '@antv/g';
import { Renderer } from '@antv/g-canvas';
import { Plugin as PluginYoga } from '@antv/g-plugin-yoga';
const renderer = new Renderer();
const plugin = new PluginYoga();
renderer.registerPlugin(plugin);
const canvas = new Canvas({
container: 'container',
width: 600,
height: 500,
renderer,
});

创建 Flex 容器

我们使用 Rect 创建一个淡蓝色背景容器。

首先通过 display: 'flex' 将它声明为一个 Flex 容器。目前我们仅支持 Rect 和 Group 作为 Flex 容器,详见声明 Flex 容器。

然后使用 flexDirection 属性让子元素竖向排列。

最后使用 padding 在四周留白:

const root = new Rect({
id: 'root',
style: {n
fill: '#C6E5FF',
width: 500,
height: 300,
x: 50,
y: 50,
display: 'flex', // 声明为 Flex 容器
flexDirection: 'column',
padding: [10, 10, 10, 10],
},
});
canvas.appendChild(root);

创建顶部 Header

接下来我们往容器中添加第一个元素,一个固定高度的 Header。

注意宽度我们使用了百分比 width: '100%',即父元素(淡蓝色容器)的宽度。

const topPanel = new Rect({
style: {
fill: 'white',
stroke: 'grey',
lineWidth: 1,
opacity: 0.8,
width: '100%',
height: 60,
marginBottom: 10,
},
});

创建下方自适应区域

固定 Header 之后,我们希望下方区域占满容器的剩余空间。

这里我们创建了一个 Group,没有继续使用 Rect 的原因是我们不希望它作为容器本身被渲染出来。

使用 flexGrow 这样它的高度会根据父容器自适应,同时声明自身也是一个 Flex 容器,后续会添加更多子元素。

const bottomPanel = new Group({
style: {
display: 'flex',
width: '100%',
flexGrow: 1,
},
});

继续划分区域

接下来我们继续划分刚创建的下方区域,这次创建一个水平方向的两栏布局。

bottomPanel.appendChild(leftPanel);
bottomPanel.appendChild(rightPanel);

元素居中

居中也是一个常见的需求,例如顶部 Header 中使用 justifyContent 和 alignItems 实现:

const topPanel = new Rect({
style: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
});
topPanel.appendChild(
new Text({
style: {
fontFamily: 'PingFang SC',
fontSize: 24,
fill: '#1890FF',
text: '1',
},
}),
);