pixijs-gamedev
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePixiJS Game Development
PixiJS 游戏开发
When to Use
适用场景
When the user is building 2D games or interactive graphics with PixiJS, asks about
sprite management, animation loops, event handling, or says "create a PixiJS app"
or "add sprites" or "animate this".
当用户使用PixiJS构建2D游戏或交互式图形、询问精灵管理、动画循环、事件处理,或者提到「创建PixiJS应用」、「添加精灵」、「为这个内容添加动画」时使用。
Instructions
使用指南
1. Application Setup
1. 应用初始化
- Create an instance and append its canvas to the DOM
Application - Always before using the app
await app.init({ width, height, background }) - Use or
Application.resize()for responsive canvasresizeTo: window - Prefer WebGL renderer (default); PixiJS falls back to Canvas automatically
- Set for smoother edges at a slight performance cost
antialias: true - Use for sharp rendering on HiDPI displays
resolution: window.devicePixelRatio
- 创建实例并将它的canvas元素挂载到DOM中
Application - 使用应用前必须先执行初始化
await app.init({ width, height, background }) - 使用或者配置
Application.resize()实现响应式canvasresizeTo: window - 优先使用WebGL渲染器(默认选项),PixiJS会自动降级到Canvas渲染
- 设置以获得更平滑的边缘,会带来轻微的性能损耗
antialias: true - 配置以在高DPI显示屏上实现清晰渲染
resolution: window.devicePixelRatio
2. Sprites and Textures
2. 精灵与纹理
- Load textures via — returns a promise
Assets.load('path/to/image.png') - Create sprites with or
Sprite.from(texture)new Sprite(texture) - Set to center the sprite's origin for rotation and scaling
anchor.set(0.5) - Use for atlas-based animations — define frames in a JSON descriptor
Spritesheet - Avoid creating textures from the same source repeatedly; caches automatically
Assets - Use as a placeholder while assets load
Texture.EMPTY
- 通过加载纹理,该方法返回一个promise
Assets.load('path/to/image.png') - 使用或者
Sprite.from(texture)创建精灵new Sprite(texture) - 设置将精灵的原点设为中心,方便旋转和缩放操作
anchor.set(0.5) - 使用实现图集动画,在JSON描述文件中定义帧信息
Spritesheet - 避免重复从相同源创建纹理,会自动缓存资源
Assets - 资源加载过程中使用作为占位符
Texture.EMPTY
3. Containers and Display Hierarchy
3. 容器与显示层级
- is the base display object — use it to group and transform children
Container - Children inherit parent transforms (position, scale, rotation, alpha)
- Use and set
sortableChildren: truefor draw-order controlzIndex - Remove off-screen objects from the stage to avoid unnecessary rendering
- Use for thousands of identical sprites (limited features, high speed)
ParticleContainer
- 是基础显示对象,可用于对子元素进行分组和变换操作
Container - 子元素会继承父元素的变换属性(位置、缩放、旋转、透明度)
- 配置并设置
sortableChildren: true来控制绘制顺序zIndex - 将不在屏幕内的对象从舞台移除,避免不必要的渲染
- 针对数千个相同精灵的场景使用,功能有限但性能极高
ParticleContainer
4. Animation
4. 动画
- Use for the main game loop
app.ticker.add((ticker) => { ... }) - gives frame-time-normalized delta (1.0 at target FPS)
ticker.deltaTime - For complex tweening, integrate GSAP:
gsap.to(sprite, { x: 200, duration: 1 }) - Use for frame-based animations from spritesheets
AnimatedSprite - Control playback: ,
animatedSprite.play(),.stop().gotoAndPlay(frame) - Set to control frame rate independently of the ticker
animationSpeed
- 使用实现主游戏循环
app.ticker.add((ticker) => { ... }) - 提供按帧率归一化的时间差(目标帧率下数值为1.0)
ticker.deltaTime - 复杂补间动画可集成GSAP:
gsap.to(sprite, { x: 200, duration: 1 }) - 使用实现基于精灵图集的帧动画
AnimatedSprite - 控制播放的方法:、
animatedSprite.play()、.stop().gotoAndPlay(frame) - 设置可以独立于ticker控制动画帧率
animationSpeed
5. Interaction and Events
5. 交互与事件
- Set on any display object to receive pointer events
eventMode = 'static' - Listen with — works for mouse and touch
.on('pointerdown', handler) - Use to define custom interaction regions (Circle, Rectangle, Polygon)
hitArea - For drag: track →
pointerdown→globalpointermoveonpointerupapp.stage - Set for interactive elements
cursor = 'pointer' - Disable interaction on non-interactive children to improve event performance
- 为任意显示对象设置即可接收指针事件
eventMode = 'static' - 通过监听事件,同时适配鼠标和触摸操作
.on('pointerdown', handler) - 使用定义自定义交互区域(圆形、矩形、多边形)
hitArea - 拖拽实现逻辑:在上监听
app.stage→pointerdown→globalpointermove事件序列pointerup - 为可交互元素设置
cursor = 'pointer' - 禁用不可交互子元素的交互能力以提升事件处理性能
6. Graphics and Drawing
6. 图形与绘制
- for vector shapes —
new Graphics(),rect(),circle()/moveTo()lineTo() - Chain drawing calls:
graphics.rect(0, 0, 100, 50).fill(0xff0000).stroke(0x000000) - Use to share drawing instructions across multiple Graphics objects
GraphicsContext - For static shapes, consider rendering to a texture with
app.renderer.generateTexture()
- 使用绘制矢量图形,支持
new Graphics()、rect()、circle()/moveTo()等方法lineTo() - 支持链式调用绘制方法:
graphics.rect(0, 0, 100, 50).fill(0xff0000).stroke(0x000000) - 使用可以在多个Graphics对象之间共享绘制指令
GraphicsContext - 针对静态图形,可以考虑使用渲染为纹理使用
app.renderer.generateTexture()
7. Filters and Effects
7. 滤镜与效果
- Apply filters via
displayObject.filters = [new BlurFilter(4)] - Common filters: ,
BlurFilter,ColorMatrixFilterDisplacementFilter - Chain multiple filters in the array — they apply in order
- Filters are GPU-intensive; limit their use on mobile or low-end devices
- Use for fading groups without affecting individual child alpha
AlphaFilter
- 通过为对象应用滤镜
displayObject.filters = [new BlurFilter(4)] - 常用滤镜:、
BlurFilter、ColorMatrixFilterDisplacementFilter - 可以在数组中串联多个滤镜,会按顺序生效
- 滤镜对GPU性能消耗较高,在移动端或低端设备上需控制使用量
- 使用实现组透明度渐变,不会影响子元素自身的透明度设置
AlphaFilter
8. Asset Loading
8. 资源加载
- Use then
Assets.add({ alias, src })for named assetsAssets.load(alias) - Bundle assets:
Assets.addBundle('game', { bg: 'bg.png', hero: 'hero.png' }) - Load bundles with — shows progress via callback
await Assets.loadBundle('game') - Supported formats: PNG, JPG, WebP, SVG, JSON (spritesheets), MP3/OGG (via plugins)
- Preload critical assets before showing the game; lazy-load secondary assets
- 使用注册资源,之后可通过
Assets.add({ alias, src })按别名加载Assets.load(alias) - 资源打包方法:
Assets.addBundle('game', { bg: 'bg.png', hero: 'hero.png' }) - 使用加载资源包,可通过回调获取加载进度
await Assets.loadBundle('game') - 支持的格式:PNG、JPG、WebP、SVG、JSON(精灵图集)、MP3/OGG(需插件支持)
- 展示游戏前预加载核心资源,非核心资源可延迟加载
9. Performance Tips
9. 性能优化建议
- Use for large numbers of simple sprites (10k+)
ParticleContainer - Minimize filter usage; each filter causes a render-texture pass
- Pool and reuse objects instead of creating/destroying frequently
- Use texture atlases to reduce draw calls (batch rendering)
- Call on removed display objects to free GPU memory
destroy() - Profile with and browser DevTools Performance tab
app.ticker.FPS - Avoid changing frequently — it breaks batching
blendMode
- 针对大量简单精灵(1万以上)使用
ParticleContainer - 减少滤镜使用,每个滤镜都会触发一次渲染纹理流程
- 采用对象池复用对象,避免频繁创建和销毁对象
- 使用纹理图集减少绘制调用(批处理渲染)
- 对移除的显示对象调用释放GPU内存
destroy() - 使用和浏览器开发者工具的性能面板进行性能分析
app.ticker.FPS - 避免频繁修改,会中断批处理
blendMode
References
参考资料
- — Common classes, methods, and setup patterns
references/api-cheatsheet.md - PixiJS Documentation
- PixiJS Examples
- —— 常用类、方法和初始化模式
references/api-cheatsheet.md - PixiJS 官方文档
- PixiJS 示例库
Examples
示例
User: "Set up a basic PixiJS game with a moving character"
Agent: Creates an Application, loads a character spritesheet via Assets, creates an
AnimatedSprite, adds it to the stage, and uses to update position
based on keyboard input. Sets on the stage for input handling.
app.ticker.add()eventModeUser: "Add particle effects when the player collects a coin"
Agent: Creates a ParticleContainer, spawns small sprites on collection events with
randomized velocity and alpha, updates particles in the ticker loop, and removes them
when alpha reaches zero. Pools particle sprites for reuse.
User: "Make the game responsive to window resize"
Agent: Sets on the Application, recalculates game object positions
relative to , and uses a resize observer to reposition UI
elements proportionally.
resizeTo: windowapp.screen.width/height用户: "搭建一个带有可移动角色的基础PixiJS游戏"
Agent: 创建Application实例,通过Assets加载角色精灵图集,创建AnimatedSprite并添加到舞台,使用根据键盘输入更新角色位置。为舞台设置支持输入处理。
app.ticker.add()eventMode用户: "玩家收集金币时添加粒子效果"
Agent: 创建ParticleContainer,在收集事件触发时生成带有随机速度和透明度的小型精灵,在ticker循环中更新粒子状态,透明度降为0时移除粒子。使用对象池复用粒子精灵提升性能。
用户: "让游戏适配窗口大小变化"
Agent: 在Application上配置,相对于重新计算游戏对象位置,使用resize observer按比例重新定位UI元素。",
resizeTo: windowapp.screen.width/height