PixiJS 安装与配置 #
安装方式概览 #
PixiJS 提供多种安装方式,适应不同的开发场景:
text
┌─────────────────────────────────────────────────────────────┐
│ 安装方式选择 │
├─────────────────────────────────────────────────────────────┤
│ │
│ CDN 引入 ─── 快速原型、学习 │
│ │ │
│ ▼ │
│ NPM 安装 ─── 项目开发、构建工具 │
│ │ │
│ ▼ │
│ 源码编译 ─── 自定义需求、贡献代码 │
│ │
└─────────────────────────────────────────────────────────────┘
CDN 引入 #
直接使用 CDN #
最简单的方式是通过 CDN 引入 PixiJS:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PixiJS Demo</title>
</head>
<body>
<script src="https://pixijs.download/v8.0.0/pixi.min.js"></script>
<script>
const app = new PIXI.Application();
app.init({
width: 800,
height: 600,
backgroundColor: 0x1099bb
}).then(() => {
document.body.appendChild(app.canvas);
const text = new PIXI.Text({
text: 'Hello PixiJS!',
style: {
fontFamily: 'Arial',
fontSize: 36,
fill: 0xffffff
}
});
text.anchor.set(0.5);
text.x = app.screen.width / 2;
text.y = app.screen.height / 2;
app.stage.addChild(text);
});
</script>
</body>
</html>
CDN 选项 #
| CDN | 地址 | 特点 |
|---|---|---|
| 官方 CDN | https://pixijs.download/v8.0.0/pixi.min.js |
官方推荐 |
| unpkg | https://unpkg.com/pixi.js@8.0.0/dist/pixi.min.js |
版本灵活 |
| jsDelivr | https://cdn.jsdelivr.net/npm/pixi.js@8.0.0/dist/pixi.min.js |
全球加速 |
| cdnjs | https://cdnjs.cloudflare.com/ajax/libs/pixi.js/8.0.0/pixi.min.js |
稳定可靠 |
版本选择 #
html
<!-- 最新版本 -->
<script src="https://pixijs.download/release/pixi.min.js"></script>
<!-- 指定版本 -->
<script src="https://pixijs.download/v8.0.0/pixi.min.js"></script>
<!-- 开发版本(未压缩,便于调试) -->
<script src="https://pixijs.download/v8.0.0/pixi.js"></script>
NPM 安装 #
创建项目 #
bash
# 创建项目目录
mkdir pixijs-project
cd pixijs-project
# 初始化 npm
npm init -y
# 安装 PixiJS
npm install pixi.js
项目结构 #
text
pixijs-project/
├── src/
│ ├── index.js
│ └── assets/
│ └── images/
├── index.html
├── package.json
└── vite.config.js
入口文件 #
javascript
// src/index.js
import { Application, Sprite, Text } from 'pixi.js';
async function init() {
const app = new Application();
await app.init({
width: 800,
height: 600,
backgroundColor: 0x1099bb,
antialias: true,
resolution: window.devicePixelRatio || 1,
autoDensity: true
});
document.getElementById('app').appendChild(app.canvas);
const text = new Text({
text: 'Hello PixiJS!',
style: {
fontFamily: 'Arial',
fontSize: 36,
fill: 0xffffff
}
});
text.anchor.set(0.5);
text.x = app.screen.width / 2;
text.y = app.screen.height / 2;
app.stage.addChild(text);
}
init();
HTML 模板 #
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PixiJS Project</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #1a1a2e;
}
#app {
border: 2px solid #333;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/index.js"></script>
</body>
</html>
构建工具配置 #
Vite 配置 #
bash
# 安装 Vite
npm install -D vite
javascript
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
server: {
port: 3000,
open: true
},
build: {
target: 'esnext'
}
});
json
// package.json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
Webpack 配置 #
bash
# 安装 Webpack
npm install -D webpack webpack-cli webpack-dev-server
javascript
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
static: './dist',
port: 3000,
hot: true
},
module: {
rules: [
{
test: /\.(png|jpg|gif|svg)$/,
type: 'asset/resource'
}
]
}
};
Parcel 配置 #
bash
# 安装 Parcel
npm install -D parcel
json
// package.json
{
"scripts": {
"dev": "parcel index.html",
"build": "parcel build index.html"
}
}
TypeScript 配置 #
安装 TypeScript #
bash
npm install -D typescript
npx tsc --init
tsconfig.json #
json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"lib": ["ES2020", "DOM", "DOM.Iterable"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
TypeScript 示例 #
typescript
// src/main.ts
import {
Application,
Sprite,
Text,
TextStyle,
Container,
Graphics
} from 'pixi.js';
interface GameConfig {
width: number;
height: number;
backgroundColor: number;
}
class Game {
private app: Application;
private config: GameConfig;
constructor(config: GameConfig) {
this.config = config;
this.app = new Application();
}
async init(): Promise<void> {
await this.app.init({
width: this.config.width,
height: this.config.height,
backgroundColor: this.config.backgroundColor
});
document.getElementById('app')?.appendChild(this.app.canvas);
}
createSprite(texture: string): Sprite {
return Sprite.from(texture);
}
createText(content: string, style?: Partial<TextStyle>): Text {
return new Text({
text: content,
style: {
fontFamily: 'Arial',
fontSize: 24,
fill: 0xffffff,
...style
}
});
}
}
const game = new Game({
width: 800,
height: 600,
backgroundColor: 0x1099bb
});
game.init();
Application 配置详解 #
基础配置 #
javascript
const app = new Application();
await app.init({
// 画布尺寸
width: 800,
height: 600,
// 背景色
backgroundColor: 0x1099bb,
// 背景透明
backgroundAlpha: 1,
transparent: false,
// 抗锯齿
antialias: true,
// 分辨率
resolution: window.devicePixelRatio || 1,
// 自动调整分辨率
autoDensity: true,
// 渲染器偏好
preference: 'webgl2',
// 父容器
parent: document.getElementById('game-container'),
// Canvas ID
id: 'game-canvas'
});
高级配置 #
javascript
await app.init({
width: 800,
height: 600,
// 渲染配置
preference: 'webgl2',
antialias: true,
antialias: 'on', // 'on', 'off', 'inherit'
// 性能配置
autoDensity: true,
resolution: 2,
// 电源管理
powerPreference: 'high-performance',
// 透明背景
backgroundAlpha: 0,
// preserveDrawingBuffer(用于截图)
preserveDrawingBuffer: true,
// 清除颜色
clearBeforeRender: true,
// 批处理大小
batchMaxSize: 4096,
// 是否自动启动渲染循环
autoStart: true
});
响应式配置 #
javascript
async function createResponsiveApp() {
const app = new Application();
await app.init({
resizeTo: window,
backgroundColor: 0x1099bb,
autoDensity: true,
resolution: window.devicePixelRatio || 1
});
document.body.appendChild(app.canvas);
// 监听窗口大小变化
window.addEventListener('resize', () => {
console.log('窗口大小:', app.screen.width, app.screen.height);
});
return app;
}
全屏应用 #
javascript
async function createFullscreenApp() {
const app = new Application();
await app.init({
resizeTo: window,
backgroundColor: 0x000000
});
document.body.appendChild(app.canvas);
document.body.style.margin = '0';
document.body.style.overflow = 'hidden';
return app;
}
开发工具 #
浏览器开发工具 #
PixiJS DevTools 是一个浏览器扩展,用于调试 PixiJS 应用:
text
功能:
├── 查看显示对象树
├── 检查对象属性
├── 实时修改属性
├── 高亮显示对象
└── 性能分析
安装步骤:
- 安装 Chrome 扩展:PixiJS DevTools
- 在代码中启用:
javascript
// 开发模式下启用
if (import.meta.env.DEV) {
globalThis.__PIXI_APP__ = app;
globalThis.__PIXI_STAGE__ = app.stage;
}
VS Code 扩展 #
推荐安装的 VS Code 扩展:
| 扩展名 | 功能 |
|---|---|
| ESLint | 代码检查 |
| Prettier | 代码格式化 |
| TypeScript | TypeScript 支持 |
| GLSL | 着色器语法高亮 |
调试技巧 #
javascript
// 1. 显示 FPS
app.ticker.add(() => {
console.log('FPS:', app.ticker.FPS);
});
// 2. 显示渲染信息
console.log('渲染器:', app.renderer.type);
console.log('分辨率:', app.renderer.resolution);
console.log('屏幕尺寸:', app.screen.width, 'x', app.screen.height);
// 3. 显示对象计数
function countDisplayObjects(container) {
let count = 0;
container.children.forEach(child => {
count++;
if (child.children) {
count += countDisplayObjects(child);
}
});
return count;
}
console.log('显示对象数量:', countDisplayObjects(app.stage));
// 4. 性能监控
const stats = {
drawCalls: 0,
objectsRendered: 0
};
app.renderer.on('prerender', () => {
stats.drawCalls = 0;
});
app.renderer.on('postrender', () => {
console.log('绘制调用:', stats.drawCalls);
});
常见问题 #
1. WebGL 不可用 #
javascript
// 检测 WebGL 支持
function checkWebGL() {
try {
const canvas = document.createElement('canvas');
return !!(
window.WebGLRenderingContext &&
(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
);
} catch (e) {
return false;
}
}
if (!checkWebGL()) {
console.warn('WebGL 不可用,将使用 Canvas 渲染');
}
2. 跨域问题 #
javascript
// 加载跨域图片
const sprite = PIXI.Sprite.from('https://example.com/image.png', {
crossOrigin: 'anonymous'
});
3. 内存泄漏 #
javascript
// 正确销毁应用
function destroyApp(app) {
// 清理纹理
PIXI.Texture.removeFromCache('texture-id');
// 销毁应用
app.destroy(true, {
children: true,
texture: true,
textureSource: true,
context: true
});
}
4. 高 DPI 屏幕 #
javascript
// 处理高 DPI 屏幕
await app.init({
width: 800,
height: 600,
resolution: window.devicePixelRatio || 1,
autoDensity: true
});
// CSS 尺寸保持不变
app.canvas.style.width = '800px';
app.canvas.style.height = '600px';
项目模板 #
最小模板 #
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PixiJS Minimal</title>
<script src="https://pixijs.download/v8.0.0/pixi.min.js"></script>
</head>
<body>
<script>
(async () => {
const app = new PIXI.Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
})();
</script>
</body>
</html>
完整模板 #
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PixiJS App</title>
<style>
* { margin: 0; padding: 0; }
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #1a1a2e;
}
canvas {
border: 2px solid #333;
border-radius: 8px;
}
</style>
<script src="https://pixijs.download/v8.0.0/pixi.min.js"></script>
</head>
<body>
<script>
(async () => {
const app = new PIXI.Application();
await app.init({
width: 800,
height: 600,
backgroundColor: 0x1099bb,
antialias: true,
resolution: window.devicePixelRatio || 1,
autoDensity: true
});
document.body.appendChild(app.canvas);
const text = new PIXI.Text({
text: 'Hello PixiJS!',
style: {
fontFamily: 'Arial',
fontSize: 48,
fill: 0xffffff,
dropShadow: {
alpha: 0.5,
angle: Math.PI / 6,
blur: 4,
distance: 4
}
}
});
text.anchor.set(0.5);
text.x = app.screen.width / 2;
text.y = app.screen.height / 2;
app.stage.addChild(text);
app.ticker.add((ticker) => {
text.rotation += 0.01 * ticker.deltaTime;
});
})();
</script>
</body>
</html>
下一步 #
环境搭建完成后,接下来学习 基础概念,深入了解 PixiJS 的核心组件!
最后更新:2026-03-29