PixiJS 简介 #

什么是 2D 渲染? #

2D 渲染是将二维图形元素绘制到屏幕上的过程。在现代 Web 开发中,2D 渲染广泛应用于游戏开发、数据可视化、交互式图形和富媒体应用等领域。

text
┌─────────────────┐
│   2D 渲染技术    │
│   技术栈         │
├─────────────────┤
│  Canvas 2D - CPU渲染│
│  WebGL   - GPU渲染│
│  SVG     - 矢量图形│
│  CSS     - 样式渲染│
└─────────────────┘

什么是 PixiJS? #

PixiJS 是一个超快的开源 2D 渲染引擎,专为创建丰富的交互式体验而设计。它使用 WebGL 在 GPU 上渲染图形,实现接近原生应用的性能,同时在 WebGL 不可用时自动降级到 Canvas。

核心定位 #

text
┌─────────────────────────────────────────────────────────────┐
│                         PixiJS                               │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │  WebGL      │  │  Canvas     │  │  自动降级    │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │  精灵渲染    │  │  图形绘制    │  │  滤镜效果    │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
└─────────────────────────────────────────────────────────────┘

PixiJS 的历史 #

发展历程 #

text
2013年 ─── PixiJS 1.0 发布
    │
    │      Mat Groves 创建
    │      基于 WebGL 渲染
    │      支持 Canvas 降级
    │
2014年 ─── PixiJS 2.0
    │
    │      重构渲染架构
    │      更好的性能
    │      社区快速增长
    │
2015年 ─── PixiJS 3.0
    │
    │      全新的渲染系统
    │      更好的批处理
    │      滤镜支持
    │
2017年 ─── PixiJS 4.0
    │
    │      TypeScript 重写
    │      更好的类型支持
    │      性能大幅提升
    │
2019年 ─── PixiJS 5.0
    │
    │      现代化架构
    │      ES Module 支持
    │      新的资源加载器
    │
2022年 ─── PixiJS 7.0
    │
    │      移除遗留代码
    │      更小的包体积
    │      改进的 API
    │
2024年 ─── PixiJS 8.0
    │
    │      全新异步 API
    │      更好的初始化
    │      现代化设计
    │
至今   ─── 行业标准
    │
    │      最快的 2D 渲染引擎
    │      活跃的社区

里程碑版本 #

版本 时间 重要特性
1.0 2013 初始发布,WebGL 渲染
2.0 2014 重构架构,性能提升
3.0 2015 新渲染系统,滤镜支持
4.0 2017 TypeScript 重写
5.0 2019 ES Module,新加载器
6.0 2021 持续优化
7.0 2022 现代化,更小体积
8.0 2024 异步 API,全新设计

为什么选择 PixiJS? #

原生 Canvas 的问题 #

在使用 PixiJS 之前,2D 图形渲染面临以下问题:

javascript
// 原生 Canvas:CPU 渲染,性能有限
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 每帧都需要重新绘制
  ctx.drawImage(image, x, y);
  ctx.drawImage(image2, x2, y2);
  ctx.drawImage(image3, x3, y3);
  // ... 大量绘制操作
  
  requestAnimationFrame(render);
}

PixiJS 的解决方案 #

javascript
// PixiJS:GPU 渲染,性能极高
const app = new PIXI.Application();
await app.init({ width: 800, height: 600 });

// 创建精灵,GPU 自动批处理
const sprite1 = PIXI.Sprite.from('image1.png');
const sprite2 = PIXI.Sprite.from('image2.png');
const sprite3 = PIXI.Sprite.from('image3.png');

app.stage.addChild(sprite1, sprite2, sprite3);
// 渲染循环自动处理,无需手动管理

PixiJS 的核心特点 #

1. 极致性能 #

PixiJS 使用 WebGL 进行 GPU 加速渲染:

text
┌─────────────────────────────────────────────────────────────┐
│                    渲染性能对比                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   Canvas 2D (CPU)                                          │
│   ┌────────────────────────────────────────┐               │
│   │████████████████████                    │ ~1000 精灵     │
│   └────────────────────────────────────────┘               │
│                                                             │
│   PixiJS WebGL (GPU)                                       │
│   ┌────────────────────────────────────────┐               │
│   │████████████████████████████████████████│ ~50000 精灵   │
│   └────────────────────────────────────────┘               │
│                                                             │
│   性能提升:约 50 倍                                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2. 自动降级 #

javascript
const app = new PIXI.Application();
await app.init({
  preference: 'webgl2',  // 优先使用 WebGL 2
  // 自动降级到 WebGL 1 或 Canvas
});
text
┌─────────────────────────────────────────────────────────────┐
│                    渲染器选择                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   preference: 'webgl2'                                      │
│        │                                                    │
│        ▼                                                    │
│   ┌─────────────┐                                           │
│   │ WebGL 2 可用?│                                          │
│   └──────┬──────┘                                           │
│          │                                                  │
│     ┌────┴────┐                                             │
│     │         │                                             │
│    Yes       No                                             │
│     │         │                                             │
│     ▼         ▼                                             │
│  WebGL 2   WebGL 1 可用?                                   │
│              │                                              │
│         ┌────┴────┐                                         │
│         │         │                                         │
│        Yes       No                                         │
│         │         │                                         │
│         ▼         ▼                                         │
│     WebGL 1   Canvas                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

3. 强大的精灵系统 #

javascript
// 从图片创建精灵
const sprite = PIXI.Sprite.from('player.png');

// 从纹理创建精灵
const texture = PIXI.Texture.from('player.png');
const sprite = new PIXI.Sprite(texture);

// 精灵属性
sprite.x = 100;
sprite.y = 100;
sprite.rotation = Math.PI / 4;
sprite.scale.set(2, 2);
sprite.alpha = 0.8;

4. 灵活的图形绘制 #

javascript
const graphics = new PIXI.Graphics();

// 绘制矩形
graphics.rect(0, 0, 100, 50);
graphics.fill({ color: 0xff0000 });

// 绘制圆形
graphics.circle(200, 100, 50);
graphics.fill({ color: 0x00ff00 });

// 绘制多边形
graphics.poly([0, 0, 100, 0, 50, 100]);
graphics.fill({ color: 0x0000ff });

5. 丰富的滤镜效果 #

javascript
// 模糊滤镜
sprite.filters = [new PIXI.BlurFilter()];

// 颜色矩阵滤镜
const colorMatrix = new PIXI.ColorMatrixFilter();
colorMatrix.night();
sprite.filters = [colorMatrix];

// 位移滤镜(扭曲效果)
const displacement = new PIXI.DisplacementFilter(displacementSprite);
sprite.filters = [displacement];

6. 完善的事件系统 #

javascript
// 鼠标/触摸事件
sprite.eventMode = 'static';
sprite.on('pointerdown', (event) => {
  console.log('点击位置:', event.global);
});

sprite.on('pointerover', () => {
  sprite.alpha = 0.5;
});

sprite.on('pointerout', () => {
  sprite.alpha = 1;
});

PixiJS 与其他库对比 #

PixiJS vs Canvas API #

特性 PixiJS Canvas API
渲染方式 GPU 加速 CPU 渲染
性能 极高 中等
学习曲线 中等 平缓
功能丰富度 丰富 基础
跨平台 自动适配 需手动处理
适用场景 复杂图形 简单绘制

PixiJS vs Three.js #

特性 PixiJS Three.js
类型 2D 渲染引擎 3D 渲染库
维度 2D 3D
学习曲线 中等 较陡
性能 极高
适用场景 2D 图形/游戏 3D 场景

PixiJS vs Phaser #

特性 PixiJS Phaser
类型 渲染引擎 游戏框架
物理引擎 无内置 内置多种
音频系统 完整
游戏功能 需自己实现 内置完整
灵活性 极高 中等
适用场景 图形渲染 游戏开发

PixiJS 的应用场景 #

1. 游戏开发 #

javascript
class Game {
  constructor() {
    this.app = new PIXI.Application();
    this.init();
  }
  
  async init() {
    await this.app.init({ width: 800, height: 600 });
    document.body.appendChild(this.app.canvas);
    
    this.player = PIXI.Sprite.from('player.png');
    this.player.anchor.set(0.5);
    this.app.stage.addChild(this.player);
    
    this.app.ticker.add((ticker) => {
      this.update(ticker.deltaTime);
    });
  }
  
  update(delta) {
    this.player.rotation += 0.01 * delta;
  }
}

2. 数据可视化 #

javascript
function createChart(data) {
  const container = new PIXI.Container();
  
  const maxValue = Math.max(...data.map(d => d.value));
  const barWidth = 50;
  const gap = 10;
  
  data.forEach((item, index) => {
    const bar = new PIXI.Graphics();
    const height = (item.value / maxValue) * 300;
    
    bar.rect(index * (barWidth + gap), 300 - height, barWidth, height);
    bar.fill({ color: item.color });
    
    container.addChild(bar);
  });
  
  return container;
}

3. 交互式图形 #

javascript
function createInteractiveMap() {
  const map = new PIXI.Container();
  
  regions.forEach(region => {
    const shape = new PIXI.Graphics();
    shape.poly(region.points);
    shape.fill({ color: region.color });
    
    shape.eventMode = 'static';
    shape.on('pointerover', () => {
      shape.alpha = 0.7;
    });
    shape.on('pointerout', () => {
      shape.alpha = 1;
    });
    
    map.addChild(shape);
  });
  
  return map;
}

4. 动画效果 #

javascript
function createParticleSystem() {
  const container = new PIXI.Container();
  const particles = [];
  
  for (let i = 0; i < 100; i++) {
    const particle = PIXI.Sprite.from('particle.png');
    particle.x = Math.random() * 800;
    particle.y = Math.random() * 600;
    particle.vx = (Math.random() - 0.5) * 2;
    particle.vy = (Math.random() - 0.5) * 2;
    
    container.addChild(particle);
    particles.push(particle);
  }
  
  app.ticker.add(() => {
    particles.forEach(p => {
      p.x += p.vx;
      p.y += p.vy;
    });
  });
  
  return container;
}

5. 图像编辑器 #

javascript
class ImageEditor {
  constructor() {
    this.app = new PIXI.Application();
    this.init();
  }
  
  async init() {
    await this.app.init({ width: 800, height: 600 });
    
    this.image = PIXI.Sprite.from('photo.jpg');
    this.app.stage.addChild(this.image);
    
    this.setupFilters();
  }
  
  setupFilters() {
    const brightness = new PIXI.ColorMatrixFilter();
    const contrast = new PIXI.ColorMatrixFilter();
    
    this.image.filters = [brightness, contrast];
    
    // UI 控制滤镜参数
    this.controls = { brightness, contrast };
  }
  
  setBrightness(value) {
    this.controls.brightness.brightness(value, true);
  }
}

PixiJS 的核心概念 #

渲染器(Renderer) #

javascript
// 自动选择最佳渲染器
const app = new PIXI.Application();
await app.init({
  width: 800,
  height: 600,
  preference: 'webgl2'
});

// 查看当前渲染器
console.log(app.renderer.type);  // 'WEBGL' 或 'CANVAS'

舞台(Stage) #

javascript
// stage 是根容器,所有显示对象都添加到这里
app.stage.addChild(sprite);

// stage 本身是一个 Container
console.log(app.stage instanceof PIXI.Container);  // true

容器(Container) #

javascript
// Container 用于组织显示对象
const container = new PIXI.Container();
container.addChild(sprite1, sprite2, sprite3);

// 容器可以嵌套
const parent = new PIXI.Container();
parent.addChild(container);

// 容器的变换影响所有子对象
container.x = 100;
container.rotation = Math.PI / 4;

显示对象(DisplayObject) #

text
┌─────────────────────────────────────────────────────────────┐
│                    显示对象继承体系                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   DisplayObject                                             │
│        │                                                    │
│        ├── Container                                        │
│        │      │                                             │
│        │      ├── Sprite                                    │
│        │      │      │                                      │
│        │      │      ├── AnimatedSprite                     │
│        │      │      └── TilingSprite                       │
│        │      │                                             │
│        │      ├── Graphics                                  │
│        │      │                                             │
│        │      ├── Text                                      │
│        │      │                                             │
│        │      └── ParticleContainer                         │
│        │                                                    │
│        └── Mesh                                             │
│               │                                             │
│               └── SimpleMesh                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

PixiJS 的设计哲学 #

1. 性能优先 #

javascript
// 批处理渲染:相同纹理的精灵自动批处理
const sprites = [];
for (let i = 0; i < 10000; i++) {
  const sprite = PIXI.Sprite.from('particle.png');
  sprite.x = Math.random() * 800;
  sprite.y = Math.random() * 600;
  sprites.push(sprite);
  app.stage.addChild(sprite);
}
// 一次绘制调用,而非 10000 次

2. 灵活性 #

javascript
// PixiJS 提供底层能力,你可以自由组合
const sprite = PIXI.Sprite.from('image.png');
sprite.filters = [new PIXI.BlurFilter()];
sprite.blendMode = 'add';

// 或使用高级封装
class Button extends PIXI.Container {
  constructor(text) {
    super();
    this.bg = new PIXI.Graphics();
    this.label = new PIXI.Text({ text });
    this.addChild(this.bg, this.label);
  }
}

3. 现代化 #

javascript
// PixiJS 8 使用现代异步 API
const app = new PIXI.Application();
await app.init({ width: 800, height: 600 });

// 支持 ES Module
import { Application, Sprite } from 'pixi.js';

// 支持 TypeScript
const sprite: PIXI.Sprite = PIXI.Sprite.from('image.png');

学习建议 #

  1. 掌握 JavaScript 基础:ES6+ 语法、异步编程、类
  2. 理解渲染原理:了解 WebGL 和 Canvas 的区别
  3. 从简单开始:先创建简单的图形,逐步增加复杂度
  4. 多看示例:官方示例库有大量可学习的代码
  5. 动手实践:通过实际项目学习最快

下一步 #

现在你已经了解了 PixiJS 是什么,接下来学习 安装与配置,开始你的图形渲染之旅!

最后更新:2026-03-29