# 快速入门
本章带你从零开始创建一个 PixiJS 应用,并绘制基础图形。
# 创建 Application {#create-application}
PixiJS v8 使用异步的 init 方法来初始化应用:
import { Application } from 'pixi.js';
const app = new Application();
await app.init({
width: 800, // 画布宽度
height: 600, // 画布高度
backgroundColor: 0x1099bb, // 背景色
resolution: window.devicePixelRatio || 1, // 分辨率适配
antialias: true // 抗锯齿
});
document.body.appendChild(app.canvas);
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 绘制基础图形 {#basic-shapes}
# 矩形 {#rectangle}
import { Graphics } from 'pixi.js';
const rect = new Graphics()
.rect(0, 0, 200, 100) // x, y, width, height
.fill(0xff0000) // 填充颜色
.stroke({ width: 2, color: 0xffffff }); // 描边
rect.x = 50;
rect.y = 50;
app.stage.addChild(rect);
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 圆形 {#circle}
const circle = new Graphics()
.circle(0, 0, 50) // x, y, radius
.fill(0x00ff00);
circle.x = 150;
circle.y = 150;
app.stage.addChild(circle);
1
2
3
4
5
6
7
2
3
4
5
6
7
# 线条 {#line}
const line = new Graphics()
.moveTo(0, 0)
.lineTo(200, 100)
.stroke({ width: 3, color: 0xffffff });
app.stage.addChild(line);
1
2
3
4
5
6
2
3
4
5
6
# 多边形 {#polygon}
const polygon = new Graphics()
.poly([0, 0, 100, 0, 150, 50, 100, 100, 0, 100])
.fill(0xff00ff);
app.stage.addChild(polygon);
1
2
3
4
5
2
3
4
5
# 容器 Container {#container}
Container 是 PixiJS 场景图的核心概念,用于分组管理显示对象:
import { Container, Graphics } from 'pixi.js';
const container = new Container();
container.x = 200;
container.y = 200;
// 在容器中添加子元素
const box1 = new Graphics().rect(0, 0, 50, 50).fill(0xff0000);
const box2 = new Graphics().rect(60, 0, 50, 50).fill(0x00ff00);
const box3 = new Graphics().rect(30, 60, 50, 50).fill(0x0000ff);
container.addChild(box1, box2, box3);
app.stage.addChild(container);
// 整体旋转容器
app.ticker.add(() => {
container.rotation += 0.01;
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 在线 Demo {#online-demo}
# 关键概念 {#key-concepts}
| 概念 | 说明 |
|---|---|
| Application | 应用入口,管理渲染循环和画布 |
| Stage | 根容器,所有显示对象的顶层 |
| Container | 容器,用于分组管理子元素 |
| Graphics | 图形绘制 API,支持各种几何图形 |
| Ticker | 帧循环,驱动动画更新 |
← PixiJS 简介 Sprite 与纹理 →