added pixlJS official skills and the prototype document

This commit is contained in:
2026-11-01 20:15:27 +01:00
parent db608f1f45
commit d966af3f8f
93 changed files with 14681 additions and 0 deletions
@@ -0,0 +1,224 @@
---
name: pixijs-accessibility
description: "Use this skill when adding screen reader and keyboard navigation to PixiJS v8 apps. Covers AccessibilitySystem options (enabledByDefault, debug, activateOnTab, deactivateOnMouseMove), per-container accessibility properties, shadow DOM overlay, mobile touch-hook activation. Triggers on: accessibility, a11y, screen reader, ARIA, keyboard navigation, tab order, AccessibilitySystem, accessibleTitle, accessibleHint, tabIndex, accessibleChildren."
license: MIT
---
Enable screen reader and keyboard navigation via PixiJS's AccessibilitySystem. The system creates an invisible shadow DOM overlay positioned over accessible containers so assistive technology can discover and activate them.
## Quick Start
```ts
const button = new Sprite(await Assets.load("button.png"));
button.accessible = true;
button.accessibleTitle = "Play game";
button.accessibleHint = "Starts a new game session";
button.eventMode = "static";
button.tabIndex = 0;
app.stage.addChild(button);
app.renderer.accessibility.setAccessibilityEnabled(true);
button.on("pointertap", () => startGame());
```
**Related skills:** `pixijs-events` (pointer/tap handlers), `pixijs-scene-dom-container` (HTML elements on canvas), `pixijs-application` (init options).
**Key points:**
- By default the system activates only after the user presses Tab. Set `enabledByDefault: true` in Application init for immediate activation.
- On mobile, the system creates a hidden touch hook; screen-reader focus activates accessibility for the whole session.
- The AccessibilitySystem requires the main thread; it is not available in a Web Worker.
## Core Patterns
### Container accessible properties
```ts
import { Container, Sprite } from "pixi.js";
const container = new Container();
container.accessible = true;
container.accessibleTitle = "Navigation menu";
container.accessibleHint = "Contains links to other pages";
container.eventMode = "static"; // required for custom tabIndex to apply
container.tabIndex = 0;
container.accessibleType = "div"; // defaults to 'button'
const sprite = new Sprite();
sprite.accessible = true;
sprite.accessibleTitle = "Close dialog";
sprite.accessibleText = "X"; // text content of the shadow div
sprite.eventMode = "static";
sprite.tabIndex = 1;
```
Available properties on any Container:
- `accessible` (boolean) - enables the accessible overlay div
- `accessibleTitle` (string) - sets the `title` attribute on the shadow div
- `accessibleHint` (string) - sets the `aria-label` attribute
- `accessibleText` (string) - sets inner text content of the shadow div
- `accessibleType` (string) - HTML tag for the shadow element, defaults to `'button'`
- `tabIndex` (number) - tab order for keyboard navigation (only applied when `interactive` is true / `eventMode` is `'static'` or `'dynamic'`)
- `accessibleChildren` (boolean, default `true`) - when `false`, prevents child containers from being accessible
- `accessiblePointerEvents` (string) - CSS `pointer-events` value on the shadow div
### Custom tab order
Give each accessible container a `tabIndex` to control the order assistive tech walks through them. Higher numbers come later; equal numbers fall back to scene-graph order.
```ts
menuButton.accessible = true;
menuButton.eventMode = "static";
menuButton.tabIndex = 1;
playButton.accessible = true;
playButton.eventMode = "static";
playButton.tabIndex = 2;
settingsButton.accessible = true;
settingsButton.eventMode = "static";
settingsButton.tabIndex = 3;
```
`tabIndex` is only forwarded to the shadow div when the container is `interactive` (`eventMode` is `'static'` or `'dynamic'`). Without that, the system clamps the div's tabIndex back to `0`, and the order you set is ignored.
### Programmatic control
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
// Enable accessibility at runtime
app.renderer.accessibility.setAccessibilityEnabled(true);
// Check current state
console.log(app.renderer.accessibility.isActive);
console.log(app.renderer.accessibility.isMobileAccessibility);
// Full init options:
await app.init({
accessibilityOptions: {
enabledByDefault: true, // activate immediately (default: false)
debug: true, // makes overlay divs visible (default: false)
activateOnTab: true, // Tab key activates system (default: true)
deactivateOnMouseMove: false, // stay active when mouse moves (default: true)
},
});
```
The system can also be configured via static defaults before creating the Application:
```ts
import { AccessibilitySystem, Application } from "pixi.js";
AccessibilitySystem.defaultOptions.enabledByDefault = true;
AccessibilitySystem.defaultOptions.deactivateOnMouseMove = false;
const app = new Application();
await app.init();
```
### Handling accessible interactions
```ts
import { Sprite } from "pixi.js";
const button = new Sprite();
button.eventMode = "static";
button.accessible = true;
button.accessibleTitle = "Submit form";
button.tabIndex = 0;
// Screen readers trigger click/tap events through the shadow DOM element
button.on("pointertap", () => {
submitForm();
});
```
When accessibility is active and a user activates a shadow div (via Enter/Space key or screen reader action), the system dispatches `click`, `pointertap`, and `tap` FederatedEvents to the corresponding container. Focus on the shadow div dispatches `mouseover`, and focus-out dispatches `mouseout`. Both `eventMode` and `accessible` should be set for full keyboard + pointer support.
## Common Mistakes
### [MEDIUM] Expecting accessibility to be active without Tab key press
The AccessibilitySystem does not create its DOM overlay until the user presses Tab (or, on mobile, focuses the touch hook). If your application needs accessibility immediately:
```ts
const app = new Application();
await app.init({
accessibilityOptions: {
enabledByDefault: true,
},
});
```
Or at runtime:
```ts
app.renderer.accessibility.setAccessibilityEnabled(true);
```
Without one of these, automated accessibility testing tools will not find the overlay elements.
### [MEDIUM] Setting accessible without accessibleTitle
Wrong:
```ts
const sprite = new Sprite();
sprite.accessible = true;
// no title or hint set
```
Correct:
```ts
const sprite = new Sprite();
sprite.accessible = true;
sprite.accessibleTitle = "Play button";
sprite.accessibleHint = "Click to start the game";
```
A container with `accessible = true` but no `accessibleTitle` or `accessibleHint` gets a fallback title of `"container {tabIndex}"`. Screen readers will announce this generic label with no useful context. Always provide at least `accessibleTitle`.
### [MEDIUM] Accessibility deactivates when moving mouse
By default, `deactivateOnMouseMove` is `true`. Any mouse movement after Tab-activation will deactivate the overlay. This is by design (assumes keyboard-only users don't use a mouse), but it makes testing with a mouse frustrating.
```ts
await app.init({
accessibilityOptions: {
deactivateOnMouseMove: false,
},
});
```
### [MEDIUM] Not importing accessibility extension in custom builds
When using `skipExtensionImports: true` for a custom build, the accessibility extension is not automatically registered. You must import it explicitly:
```ts
import "pixi.js/accessibility";
import { Application } from "pixi.js";
const app = new Application();
await app.init({ skipExtensionImports: true });
```
Without this import, `app.renderer.accessibility` will be undefined and no shadow DOM layer will be created.
## API Reference
- [AccessibilitySystem](https://pixijs.download/release/docs/accessibility.AccessibilitySystem.html.md)
- [AccessibilitySystemOptions](https://pixijs.download/release/docs/accessibility.AccessibilitySystemOptions.html.md)
- [AccessibilityOptions](https://pixijs.download/release/docs/accessibility.AccessibilityOptions.html.md)
- [AccessibleOptions](https://pixijs.download/release/docs/accessibility.AccessibleOptions.html.md)
- [PointerEvents](https://pixijs.download/release/docs/accessibility.PointerEvents.html.md)
+293
View File
@@ -0,0 +1,293 @@
---
name: pixijs-application
description: "Use this skill when creating and configuring a PixiJS v8 Application. Covers new Application() + async app.init() options (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, webgl/webgpu/canvasOptions per-renderer overrides), app.stage/renderer/canvas/screen/domContainerRoot access, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), custom ApplicationPlugin via ExtensionType.Application, start/stop lifecycle, and app.destroy() with releaseGlobalResources. Triggers on: Application, app.init, app.stage, app.renderer, app.canvas, app.screen, app.domContainerRoot, ApplicationOptions, ApplicationPlugin, ExtensionType.Application, resizeTo, sharedTicker, skipExtensionImports, preferWebGLVersion, preserveDrawingBuffer, cullable, CullerPlugin, app.start, app.stop, app.destroy, releaseGlobalResources."
license: MIT
---
`Application` is the convenience wrapper that owns a renderer, a root `stage` Container, a canvas, and the Ticker/Resize plugins. In v8 the constructor takes no arguments; all configuration is passed to the async `app.init()` call which instantiates the renderer via `autoDetectRenderer`.
## Quick Start
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({
resizeTo: window,
background: "#1099bb",
antialias: true,
preference: "webgl",
autoDensity: true,
resolution: window.devicePixelRatio,
});
document.body.appendChild(app.canvas);
```
**Related skills:** `pixijs-core-concepts` (renderers, render pipeline), `pixijs-ticker` (render loop detail), `pixijs-scene-container` (working with `app.stage`), `pixijs-environments` (non-browser setups).
## Core Patterns
### Lifecycle: construct, init, render, destroy
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
// ... run scene, ticker drives app.render() automatically ...
app.destroy(
{ removeView: true, releaseGlobalResources: true },
{ children: true, texture: true, textureSource: true },
);
```
- `new Application()` allocates the instance but creates nothing. Options passed here are ignored with a v8 deprecation warning.
- `app.init(options)` is async. It builds the renderer, wires up plugins, and must complete before you can use `app.canvas`, `app.renderer`, or `app.screen`.
- The TickerPlugin calls `app.render()` every frame once init resolves (unless `autoStart: false`).
- `app.destroy(rendererDestroyOptions, stageDestroyOptions)` — the first argument forwards to `renderer.destroy()`. Pass `true` or `{ removeView: true }` to remove the canvas from the DOM. Add `releaseGlobalResources: true` to drain global pools (batches, texture caches) when tearing down and re-creating an app in the same tab; omitting it is the usual cause of flickering and stale textures after a re-init (see `pixijs-performance`).
### Key init options
```ts
await app.init({
width: 800,
height: 600,
background: 0x1099bb,
backgroundAlpha: 1,
antialias: true,
resolution: window.devicePixelRatio,
autoDensity: true,
preference: "webgpu",
autoStart: true,
sharedTicker: false,
resizeTo: window,
canvas: document.querySelector("#game-canvas") as HTMLCanvasElement,
});
```
For every option — view/canvas, background, renderer preference (including the array form), ticker, resize, culler, events, accessibility, WebGL/WebGPU context flags, Graphics bezier smoothness, GC, and per-renderer overrides (`webgl` / `webgpu` / `canvasOptions`) — see [references/application-options.md](references/application-options.md).
### Application properties
```ts
app.stage; // root Container; add all display objects here
app.renderer; // the WebGL/WebGPU/Canvas renderer instance
app.canvas; // the HTMLCanvasElement (insert it into the DOM yourself)
app.screen; // Rectangle describing the visible area in CSS pixels
app.domContainerRoot; // HTMLDivElement that holds DOMContainer overlays
```
`app.stage` is a plain `Container`. For scene graph detail (transforms, addChild, destroy) see `pixijs-scene-container`. For renderer-level operations (extract, generateTexture, custom systems) see `pixijs-core-concepts` and `pixijs-custom-rendering`. `app.domContainerRoot` is the `<div>` that the renderer uses to host `DOMContainer` overlays; append it next to `app.canvas` when you need DOM elements pinned to scene nodes (see `pixijs-scene-dom-container`).
### ResizePlugin
Set `resizeTo` at init (or reassign `app.resizeTo` later) to have the plugin listen for the `resize` event and call `renderer.resize()` with the target element's client size. Combine with `autoDensity: true` and `resolution: window.devicePixelRatio` for high-DPI output.
```ts
await app.init({ resizeTo: window });
app.resizeTo = document.querySelector("#game-container") as HTMLElement;
app.resize(); // immediate resize to the target's current size
app.queueResize(); // defer the resize to the next animation frame
app.cancelResize(); // drop a pending queueResize
```
The plugin keeps the canvas matched to the target. `app.screen` and `app.canvas.width/height` update in response; read them after the resize to place UI.
- `app.resize()` — immediate synchronous resize.
- `app.queueResize()` — coalesces rapid calls by deferring to the next frame; internally used by the `window.resize` listener to avoid redundant work.
- `app.cancelResize()` — cancels a queued resize. Call this before tearing down your own layout code that triggered `queueResize`.
### Ticker basics
The TickerPlugin creates `app.ticker` and registers `app.render()` on it at `UPDATE_PRIORITY.LOW`. Control the loop with `app.start()`/`app.stop()` and add callbacks with `app.ticker.add` / `app.ticker.addOnce`:
```ts
app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
});
app.ticker.addOnce(() => {
console.log("runs once on the next frame, then removes itself");
});
app.stop(); // pause the render loop (e.g. tab hidden)
app.start(); // resume
```
The callback receives the `Ticker` instance; read `ticker.deltaTime` for a frame-rate-independent multiplier (~1.0 at 60fps), `ticker.deltaMS` for real milliseconds, or `ticker.FPS` for the current frame rate. See `pixijs-ticker` for priorities, FPS capping, `onRender`, shared vs private tickers, and the v8 callback signature change.
### Manual render loop
```ts
await app.init({ autoStart: false, width: 800, height: 600 });
document.body.appendChild(app.canvas);
function frame() {
updateScene();
app.render();
requestAnimationFrame(frame);
}
frame();
```
`autoStart: false` prevents the TickerPlugin from starting the ticker automatically. Call `app.render()` yourself (or `app.renderer.render({ container: app.stage })` for the same effect). If you still want registered ticker callbacks to fire, call `app.ticker.update()` inside your loop before `app.render()`.
### CullerPlugin (opt-in)
The CullerPlugin skips rendering containers that fall outside `app.renderer.screen`. It isn't registered by default; add it before creating your app:
```ts
import {
Application,
Container,
Sprite,
extensions,
CullerPlugin,
Rectangle,
} from "pixi.js";
extensions.add(CullerPlugin);
const app = new Application();
await app.init({ width: 800, height: 600 });
const world = new Container();
world.cullable = true; // this container is culled when its bounds leave the screen
world.cullableChildren = true; // default; set `false` to skip recursing into children
const tile = Sprite.from("tile.png");
tile.cullable = true;
world.addChild(tile);
app.stage.addChild(world);
```
Containers are not culled unless `cullable` is set. Override the default bounds check with `container.cullArea = new Rectangle(x, y, w, h)` when child bounds are expensive to compute. The plugin wraps `app.render()` so `Culler.shared.cull(app.stage, app.renderer.screen)` runs before every frame. See `pixijs-performance` for when culling pays off.
### Custom Application plugins
Extend `Application` by registering a class with `static init`, `static destroy`, and `static extension = ExtensionType.Application`. Both methods are called with `this` bound to the Application instance, so `this.renderer` and `this.stage` are available.
```ts
import {
Application,
ExtensionType,
extensions,
type ApplicationOptions,
} from "pixi.js";
class FpsOverlay {
public static extension = ExtensionType.Application;
public static init(this: Application, options: Partial<ApplicationOptions>) {
// runs inside app.init() after the renderer is created
// attach props/methods to `this` to expose them on the app
}
public static destroy(this: Application) {
// runs inside app.destroy() — tear down anything you attached
}
}
extensions.add(FpsOverlay);
```
Plugins initialize in registration order and destroy in reverse. To add typed options for your plugin, extend `PixiMixins.ApplicationOptions`:
```ts
declare global {
namespace PixiMixins {
interface ApplicationOptions {
fpsOverlay?: { visible?: boolean };
}
}
}
await app.init({ fpsOverlay: { visible: true } });
```
The built-in `ResizePlugin`, `TickerPlugin`, and opt-in `CullerPlugin` all use this same contract. If you set `skipExtensionImports: true`, register the built-ins you need yourself (`extensions.add(ResizePlugin, TickerPlugin)`).
## Common Mistakes
### [CRITICAL] Passing options to the constructor
Wrong:
```ts
const app = new Application({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
```
Correct:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
```
In v8 the `Application` constructor takes no arguments. Options passed there are ignored and log a deprecation warning; the renderer is only created inside the async `init()` call.
### [HIGH] Using app.view instead of app.canvas
Wrong:
```ts
document.body.appendChild(app.view);
```
Correct:
```ts
document.body.appendChild(app.canvas);
```
`app.view` was renamed to `app.canvas` in v8. The old getter still works but emits a deprecation warning.
### [MEDIUM] Touching app.canvas or app.renderer before init resolves
Wrong:
```ts
const app = new Application();
document.body.appendChild(app.canvas);
app.init({ width: 800, height: 600 });
```
Correct:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
```
`app.renderer`, `app.canvas`, and `app.screen` are only populated once the `init()` promise resolves. Accessing them earlier returns `undefined`.
## API Reference
- [Application](https://pixijs.download/release/docs/app.Application.html.md)
- [ApplicationOptions](https://pixijs.download/release/docs/app.ApplicationOptions.html.md)
- [ApplicationPlugin](https://pixijs.download/release/docs/app.ApplicationPlugin.html.md)
- [ResizePlugin](https://pixijs.download/release/docs/app.ResizePlugin.html.md)
- [ResizePluginOptions](https://pixijs.download/release/docs/app.ResizePluginOptions.html.md)
- [TickerPlugin](https://pixijs.download/release/docs/app.TickerPlugin.html.md)
- [TickerPluginOptions](https://pixijs.download/release/docs/app.TickerPluginOptions.html.md)
- [CullerPlugin](https://pixijs.download/release/docs/app.CullerPlugin.html.md)
- [autoDetectRenderer](https://pixijs.download/release/docs/rendering.autoDetectRenderer.html.md)
@@ -0,0 +1,314 @@
# ApplicationOptions reference
Every option accepted by `app.init(options)`. Options come from three type sources merged into a single interface:
- `AutoDetectOptions` → base renderer options (width/height/resolution/etc.)
- `PixiMixins.ApplicationOptions` → plugin options (`resizeTo`, `autoStart`, `sharedTicker`, `culler`)
- System defaults → each renderer system (background, view, hello, GC, context, backbuffer, events, graphics) contributes its own options
Options with no default are unset unless you pass them. `Partial<ApplicationOptions>` means everything is optional.
## View / canvas
Configures the main canvas and how it maps to CSS pixels.
| Option | Type | Default | Description |
| ------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `width` | `number` | `800` | Initial width in CSS pixels. |
| `height` | `number` | `600` | Initial height in CSS pixels. |
| `canvas` | `ICanvas` | — | Existing `HTMLCanvasElement` (or `OffscreenCanvas`) to render into instead of creating one. |
| `view` | `ICanvas` | — | **Deprecated since 8.0.0.** Alias for `canvas`. |
| `resolution` | `number` | `1` | Device pixel ratio. Set to `window.devicePixelRatio` for HiDPI. |
| `autoDensity` | `boolean` | `false` | Scale CSS dimensions of the canvas so `width`/`height` stay in CSS pixels while the backing store matches `resolution`. Only honored on `HTMLCanvasElement` (ignored on `OffscreenCanvas`). |
| `antialias` | `boolean` | `false` | GPU MSAA where supported. On WebGL, this only affects the main context — use `useBackBuffer: true` if you need antialiased filtering. |
| `depth` | `boolean` | — | Allocate a depth buffer for the main view. Always on for WebGL; needed for z-ordered rendering. |
| `transient` | `boolean` | `false` | WebGPU only, with `antialias`. Discard the canvas's multisample depth/stencil buffer at the end of each pass, and its colour buffer on GPUs that aren't tile-based (tile-based GPUs already discard colour). Only for apps that never reopen the canvas pass while still needing depth or stencil: no filters or masks popping back onto it, no render with `clear: false`. |
```ts
await app.init({
width: 1280,
height: 720,
resolution: window.devicePixelRatio,
autoDensity: true,
antialias: true,
});
```
## Background
Controls the clear color applied each frame.
| Option | Type | Default | Description |
| ------------------- | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `backgroundColor` | `ColorSource` | `0x000000` | Canvas clear color. Accepts hex, CSS string, `[r, g, b, a]`, or any `ColorSource`. |
| `background` | `ColorSource` | — | Alias for `backgroundColor`. If both are set, `background` wins. |
| `backgroundAlpha` | `number` | `1` | Clear alpha, `0`–`1`. **Cannot be changed after init** — the backing canvas is allocated with or without alpha support based on this value. Set `< 1` now if you may ever need transparency. |
| `clearBeforeRender` | `boolean` | `true` | Clear the target before each frame. Disable only if you're drawing a full-frame background yourself (e.g. a full-screen sprite). |
```ts
await app.init({
backgroundColor: 0x1099bb,
backgroundAlpha: 1,
});
```
## Renderer preference
Picks which renderer gets created.
| Option | Type | Default | Description |
| --------------- | --------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `preference` | `'webgl' \| 'webgpu' \| 'canvas' \| RendererPreference[]` | `'webgl'` | Pick a preferred renderer. String = try first, then fall back through the default priority (`webgl` → `webgpu` → `canvas`). Array = try only the listed renderers, in order (acts as a blocklist too — anything not listed is excluded). See ["Array form"](#preference-array-form) below. |
| `webgl` | `Partial<WebGLOptions>` | — | Options applied **only** when the WebGL renderer is selected. Merged over the top-level options. |
| `webgpu` | `Partial<WebGPUOptions>` | — | Options applied **only** when the WebGPU renderer is selected. |
| `canvasOptions` | `Partial<CanvasOptions>` | — | Options applied **only** when the Canvas2D renderer is selected. |
### preference: array form
Passing an array to `preference` restricts `autoDetectRenderer` to exactly the listed renderers, in the given order. Any renderer not in the array is **excluded entirely** — the array doubles as a blocklist.
```ts
// Try WebGPU first, then fall back to WebGL. Never use Canvas2D.
await app.init({ preference: ["webgpu", "webgl"] });
// Only ever use Canvas2D (e.g. in a WebGL-disabled environment).
await app.init({ preference: ["canvas"] });
// Skip WebGPU entirely while keeping the default webgl → canvas fallback order.
await app.init({ preference: ["webgl", "canvas"] });
```
Contrast with the string form, which falls through the **full** default priority if the first choice fails:
```ts
// Tries webgpu, then webgl, then canvas — all three are candidates.
await app.init({ preference: "webgpu" });
```
Use the array when you need to guarantee a renderer is never picked (e.g. WebGPU is broken on a target device, or you want to forbid Canvas2D's feature subset).
## Shared rendering
Apply to every renderer type.
| Option | Type | Default | Description |
| ------------------------------ | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `roundPixels` | `boolean` | `false` | Round vertex positions to whole pixels at shader time. Eliminates subpixel shimmer for pixel-art but blurs smooth motion. |
| `skipExtensionImports` | `boolean` | `false` | Disable automatic import of default extensions. With `true`, import the subsystems you need manually (`import 'pixi.js/accessibility'`, `'pixi.js/app'`, `'pixi.js/events'`, …). Renderer loader extensions (`WebGLLoader`/`WebGPULoader`/`CanvasLoader`) are skipped too, so import any backend-specific plugin modules yourself. Used for custom tree-shaken builds. |
| `hello` | `boolean` | `false` | Log the PixiJS version and renderer type banner to the console on init. |
| `failIfMajorPerformanceCaveat` | `boolean` | `false` | Fail WebGL context creation if the browser reports major performance issues (blocklisted GPU, software fallback). Set `true` for high-performance apps that should refuse slow paths. |
```ts
await app.init({
roundPixels: true,
hello: true,
});
```
## Graphics
Graphics rendering options.
| Option | Type | Default | Description |
| ------------------ | -------- | ------- | ------------------------------------------------------------------------------------------ |
| `bezierSmoothness` | `number` | `0.5` | Controls curve tessellation for Graphics bezier paths. Higher = smoother (more triangles). |
```ts
await app.init({
bezierSmoothness: 0.75,
});
```
## Ticker (TickerPluginOptions)
Controls the built-in render loop.
| Option | Type | Default | Description |
| -------------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoStart` | `boolean` | `true` | Start the render loop automatically after `init()` resolves. Setting `false` disables `app.render()` being called each frame, but **does not** stop `Ticker.shared` if you've opted into `sharedTicker: true`. |
| `sharedTicker` | `boolean` | `false` | Use `Ticker.shared` instead of creating a per-Application ticker. Useful for syncing multiple apps; loses per-app control over start/stop. |
See `pixijs-ticker` for the ticker API itself.
```ts
await app.init({
autoStart: false,
sharedTicker: false,
});
function loop() {
app.renderer.render(app.stage);
requestAnimationFrame(loop);
}
loop();
```
## Resize (ResizePluginOptions)
| Option | Type | Default | Description |
| ---------- | ----------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `resizeTo` | `Window \| HTMLElement` | `null` | Element the renderer should auto-resize to match. `window` resizes to the viewport; an element uses `clientWidth`/`clientHeight`. Leave `null` to opt out of auto-resize. |
The plugin listens for `resize` events on `window` and calls `renderer.resize()`. You can reassign `app.resizeTo` at runtime, and call `app.resize()`, `app.queueResize()`, or `app.cancelResize()` from user code.
```ts
await app.init({
resizeTo: window,
});
```
## Culler (CullerPluginOptions)
Opt-in plugin (must `extensions.add(CullerPlugin)` to activate).
| Option | Type | Default | Description |
| ------------------------ | --------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `culler.updateTransform` | `boolean` | `false` (effectively) | Must be explicitly set to `true` to run transform updates before culling. Otherwise PixiJS skips transform updates, and cull bounds may lag one frame for moving objects. |
```ts
import { CullerPlugin, extensions } from "pixi.js";
extensions.add(CullerPlugin);
await app.init({
culler: { updateTransform: true },
});
```
## Events
| Option | Type | Default | Description |
| -------------------------- | -------------------------------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `eventMode` | `'none' \| 'passive' \| 'auto' \| 'static' \| 'dynamic'` | `'passive'` | Default interaction mode for every container. See `pixijs-events`. |
| `eventFeatures.move` | `boolean` | `true` | Fire `pointermove`/`mousemove`/`touchmove` + `pointerover`/`pointerout`. |
| `eventFeatures.globalMove` | `boolean` | `true` | Fire `globalpointermove`/`globalmousemove`/`globaltouchmove` regardless of hit target. Expensive; turn off if you don't need it. |
| `eventFeatures.click` | `boolean` | `true` | Fire `pointerdown`/`pointerup`/`click`/`tap`. |
| `eventFeatures.wheel` | `boolean` | `true` | Fire `wheel`. |
```ts
await app.init({
eventMode: "static",
eventFeatures: {
move: true,
globalMove: false,
click: true,
wheel: true,
},
});
```
## Accessibility
Accessibility options. Pass these on the top-level init options.
| Option | Type | Default | Description |
| -------------------------------------------- | --------- | ------- | ----------------------------------------------------------------------------- |
| `accessibilityOptions.enabledByDefault` | `boolean` | `false` | Enable accessibility overlays immediately instead of waiting for the Tab key. |
| `accessibilityOptions.debug` | `boolean` | `false` | Show the accessibility overlay divs visibly for debugging. |
| `accessibilityOptions.activateOnTab` | `boolean` | `true` | Activate overlays when the user presses Tab. |
| `accessibilityOptions.deactivateOnMouseMove` | `boolean` | `true` | Deactivate overlays when the mouse moves. |
See `pixijs-accessibility` for the full accessibility API.
```ts
await app.init({
accessibilityOptions: {
enabledByDefault: true,
activateOnTab: true,
deactivateOnMouseMove: true,
},
});
```
## WebGL-only options
Applied when the WebGL renderer is selected.
| Option | Type | Default | Description |
| ----------------------- | ----------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `context` | `WebGL2RenderingContext \| null` | `null` | Use this existing WebGL context instead of creating one. Useful for hand-managing the context or integrating with other renderers. |
| `powerPreference` | `'high-performance' \| 'low-power'` | `undefined` | Hint the browser which GPU to pick on multi-GPU systems. If omitted, PixiJS internally passes `'default'` to the GPU context; `'default'` is not settable from user code. |
| `premultipliedAlpha` | `boolean` | `true` | Tell the compositor the drawing buffer contains premultiplied-alpha colors. Changing this affects blending math. |
| `preserveDrawingBuffer` | `boolean` | `false` | Keep the drawing buffer between frames. Required if you need `canvas.toDataURL()` or `canvas.toBlob()` to capture arbitrary frames. |
| `preferWebGLVersion` | `1 \| 2` | `2` | Preferred WebGL version. PixiJS v8 was designed for WebGL2 — WebGL1 is a legacy fallback. |
| `multiView` | `boolean` | `false` | Enable rendering to multiple canvases from one renderer. |
| `useBackBuffer` | `boolean` | `false` | Render to an intermediate texture instead of directly to the canvas. Required for advanced blend modes and filters that sample the backdrop. Enables `antialias` on the back buffer independently from the main context. |
```ts
await app.init({
preference: "webgl",
webgl: {
preferWebGLVersion: 2,
useBackBuffer: true,
powerPreference: "high-performance",
},
});
```
## WebGPU-only options
| Option | Type | Default | Description |
| ---------------------- | ----------------------------------- | ----------- | ----------------------------------------------------------------------------------------------- |
| `powerPreference` | `'high-performance' \| 'low-power'` | `undefined` | Hint for `requestAdapter()`. |
| `forceFallbackAdapter` | `boolean` | `false` | Force the software/fallback adapter. For testing only. |
| `gpu` | `{ adapter, device }` | — | Use a pre-created `GPUAdapter` + `GPUDevice` pair. Useful for sharing a device between engines. |
```ts
await app.init({
preference: ["webgpu", "webgl"],
webgpu: {
powerPreference: "high-performance",
},
});
```
## Garbage collection
All time values are milliseconds.
| Option | Type | Default | Description |
| ----------------- | --------- | ------- | ------------------------------------------------------------ |
| `gcActive` | `boolean` | `true` | Enable the unified renderer garbage collector. |
| `gcMaxUnusedTime` | `number` | `60000` | How long a resource can go unused before the GC collects it. |
| `gcFrequency` | `number` | `30000` | How often the GC sweep runs. |
### Deprecated (GC — prefer the unified options above)
`TextureGCSystem` and `RenderableGCSystem` still accept these, but they've been deprecated since 8.15.0 in favor of `gcActive`/`gcMaxUnusedTime`/`gcFrequency`. Passing them still works for the deprecation window but logs warnings.
| Option | Deprecated since | Replacement |
| --------------------------- | ---------------- | ----------------------------------------------------------- |
| `textureGCActive` | 8.15.0 | `gcActive` |
| `textureGCMaxIdle` | 8.15.0 | `gcMaxUnusedTime` (note: this is frames; the new API is ms) |
| `textureGCCheckCountMax` | 8.15.0 | `gcFrequency` (frames → ms) |
| `textureGCAMaxIdle` | 8.3.0 | `textureGCMaxIdle` (typo fix) → now `gcMaxUnusedTime` |
| `renderableGCActive` | 8.15.0 | `gcActive` |
| `renderableGCMaxUnusedTime` | 8.15.0 | `gcMaxUnusedTime` |
| `renderableGCFrequency` | 8.15.0 | `gcFrequency` |
```ts
await app.init({
gcActive: true,
gcMaxUnusedTime: 60_000,
gcFrequency: 30_000,
});
```
## Per-renderer overrides
`webgl`, `webgpu`, and `canvasOptions` are merged over the top-level options once the selected renderer is known:
```ts
await app.init({
antialias: false,
webgl: { antialias: true, useBackBuffer: true },
webgpu: { antialias: true },
canvasOptions: {
/* canvas-specific */
},
});
```
If WebGL wins, the renderer sees `antialias: true` + `useBackBuffer: true`. If WebGPU wins, just `antialias: true`. The three sub-keys are stripped before the options reach the renderer.
+303
View File
@@ -0,0 +1,303 @@
---
name: pixijs-assets
description: "Use this skill when loading and managing resources in PixiJS v8. Covers Assets.init, Assets.load/add/unload, bundles, manifests, background loading, onProgress, caching, spritesheets, video textures, web fonts, bitmap fonts, animated GIFs, compressed textures, SVG as texture or Graphics, resolution detection, per-asset data options, and forcing a specific loader with the parser field (for extension-less URLs). Triggers on: Assets, Assets.load, Assets.init, loadBundle, manifest, backgroundLoad, Spritesheet, Cache, LoadOptions, unload, parser, loadParser, loadWebFont, loadBitmapFont, loadVideoTextures, GifSource, VideoSourceOptions."
license: MIT
---
The `Assets` API is PixiJS's asset loader, resolver, and cache in one singleton. Use it to load textures, video, spritesheets, fonts, JSON, and other resources with format detection, resolution switching, bundle grouping, progress tracking, and GPU cleanup.
## Quick Start
```ts
await Assets.init({ basePath: "/static/" });
const texture = await Assets.load("bunny.png");
const sprite = new Sprite(texture);
app.stage.addChild(sprite);
const [hero, enemy] = await Assets.load(["hero.png", "enemy.png"]);
await Assets.load({
alias: "logo",
src: "logo.webp",
});
const logo = new Sprite(Assets.get("logo"));
```
`Assets.init()` is optional but recommended for setting `basePath`, `texturePreference`, or a manifest. After init, call `Assets.load()` with a URL, alias, array, or `UnresolvedAsset`; resolved assets are cached and re-resolved by `Assets.get()`.
## Supported file types
| Type | Extensions | Parser ID | Loader |
| ------------------- | ---------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Textures | `.png`, `.jpg`, `.jpeg`, `.webp`, `.avif` | `texture` | `loadTextures` |
| SVG | `.svg` | `svg` | `loadSvg` (see `references/svg.md`) |
| Video textures | `.mp4`, `.m4v`, `.webm`, `.ogg`, `.ogv`, `.h264`, `.avi`, `.mov` | `video` | `loadVideoTextures` (see `references/video.md`) |
| Sprite sheets | `.json` (Spritesheet format) | `spritesheet` | `spritesheetAsset` (see `references/spritesheet.md`) |
| Bitmap fonts | `.fnt`, `.xml` | `bitmap-font` | `loadBitmapFont` (loading works by default; rendering `BitmapText` requires `'pixi.js/text-bitmap'`; see `references/fonts.md`) |
| Web fonts | `.ttf`, `.otf`, `.woff`, `.woff2` | `web-font` | `loadWebFont` (see `references/fonts.md`) |
| JSON | `.json` | `json` | `loadJson` |
| Text | `.txt` | `text` | `loadTxt` |
| Compressed textures | `.basis`, `.dds`, `.ktx`, `.ktx2` | `basis`, `dds`, `ktx`, `ktx2` | See `references/compressed-textures.md` |
| Animated GIFs | `.gif` | `gif` | Requires `'pixi.js/gif'`; returns `GifSource` (see `references/gif.md`) |
The **Parser ID** column is the value you pass to the top-level `parser` field on an asset descriptor to force a specific loader. See "Forcing a parser" below.
## Forcing a parser with `parser`
By default, PixiJS picks a loader by matching the file extension or MIME type. When your URL lacks an extension (CDN signed URLs, blob URLs, API endpoints, content-hashed paths), the resolver can't tell the loader what to do. Set the top-level `parser` field on the asset descriptor to force a specific loader:
```ts
// Signed CDN URL with no extension
const texture = await Assets.load({
src: "https://cdn.example.com/signed/abc123?token=xyz",
parser: "texture",
});
// API endpoint that returns JSON
const data = await Assets.load({
alias: "config",
src: "https://api.example.com/v1/config",
parser: "json",
});
// Extension-less font URL with explicit family
await Assets.load({
src: "https://cdn.example.com/fonts/hero-v2",
parser: "web-font",
data: { family: "Hero", weights: ["400", "700"] },
});
// Video stream without a file extension
const clipTexture = await Assets.load({
src: "https://cdn.example.com/stream/xyz",
parser: "video",
data: { mime: "video/mp4", muted: true, playsinline: true },
});
```
The `parser` field goes at the top level of the asset descriptor (alongside `src` and `data`), not inside `data`. It takes any parser ID from the "Supported file types" table above:
- `'texture'`, `'svg'`, `'video'`: image, SVG, and video textures
- `'json'`, `'text'`: JSON and plain text
- `'web-font'`, `'bitmap-font'`: web and bitmap fonts
- `'spritesheet'`: texture atlas JSON
- `'gif'`: animated GIFs (requires `'pixi.js/gif'`)
- `'basis'`, `'dds'`, `'ktx'`, `'ktx2'`: compressed textures (each requires its side-effect import)
### When you need it
- **Signed CDN URLs**: `https://cdn.example.com/get?id=abc123` has no extension the loader can test against.
- **Blob or ObjectURL**: `URL.createObjectURL(blob)` produces `blob:...` URLs with no extension.
- **Custom routing**: `/api/assets/hero-v2` where the server decides the content type.
- **Content-hashed paths without suffix**: some build pipelines produce names like `/static/abc123def` instead of `/static/abc123def.png`.
If the URL _does_ have an extension, you don't need `parser`; let auto-detection do its job. Only set `parser` when detection can't work.
### `loadParser` is deprecated
The v7 `loadParser` field still works but emits a deprecation warning. Use `parser` for new code.
```ts
// Old (deprecated)
await Assets.load({ src: "...", loadParser: "loadTextures" });
// New
await Assets.load({ src: "...", parser: "texture" });
```
## Topics
Every asset workflow is covered in a reference file. Pick the one that matches the question:
| Topic | Reference | When |
| ------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------- |
| Texture atlases and animations | [references/spritesheet.md](references/spritesheet.md) | Loading sprite sheets with `AnimatedSprite` |
| Video textures | [references/video.md](references/video.md) | `.mp4`, `.webm`, autoplay, looping, mobile |
| Web and bitmap fonts | [references/fonts.md](references/fonts.md) | `.woff2`, `.fnt`, font families, SDF fonts |
| Animated GIFs | [references/gif.md](references/gif.md) | `.gif`, `GifSprite`, playback control |
| Grouping assets by feature | [references/bundles.md](references/bundles.md) | `addBundle`, `loadBundle`, `unloadBundle` |
| Declaring everything upfront | [references/manifests.md](references/manifests.md) | `Assets.init({ manifest })` workflows |
| Cache lookups and cleanup | [references/caching.md](references/caching.md) | `Assets.get`, `Assets.unload`, `Cache` |
| Priming future assets | [references/background.md](references/background.md) | `backgroundLoad`, `backgroundLoadBundle` |
| Loading screens | [references/progress.md](references/progress.md) | `onProgress`, LoadOptions progress |
| GPU-compressed formats | [references/compressed-textures.md](references/compressed-textures.md) | `.ktx2`, `.basis`, `.dds`, `.ktx` |
| Vector vs raster SVG | [references/svg.md](references/svg.md) | `parseAsGraphicsContext`, texture mode |
| Retina + format detection | [references/resolution.md](references/resolution.md) | `@{1,2}x`, `format` preferences |
## Decision guide
- **Need to load a single image?** Use `Assets.load(url)`. No setup required.
- **Loading many assets grouped by level/scene?** Use a bundle. See `references/bundles.md`.
- **Know all assets at build time?** Use a manifest in `Assets.init`. See `references/manifests.md`.
- **Need a loading bar?** Pass a progress callback to `Assets.load`. See `references/progress.md`.
- **Smooth transitions between levels?** Background-load the next level. See `references/background.md`.
- **Memory budget matters?** Use compressed textures and `Assets.unload` between screens. See `references/compressed-textures.md` and `references/caching.md`.
- **Need crisp SVG icons at any size?** Load as Graphics, not texture. See `references/svg.md`.
- **Retina + WebP/AVIF?** Configure `texturePreference` and use format patterns. See `references/resolution.md`.
## Load options and error handling
There are two separate "options" concepts when loading assets:
1. **`LoadOptions`**: the second argument to `Assets.load`/`loadBundle`. Controls error recovery, retries, progress, and completion callbacks across a whole load.
2. **`data`**: a field on each asset descriptor. Forwards parser-specific options (scale mode, resolution, font family, autoplay flags, etc.) to the specific loader for that asset.
### LoadOptions (per call)
```ts
await Assets.load(["hero.png", "enemy.png"], {
onProgress: (p) => updateBar(p),
onError: (err, url) => {
const src = typeof url === "string" ? url : url.src;
console.warn("failed:", src, err);
},
strategy: "retry",
retryCount: 3,
retryDelay: 250,
});
```
- `onProgress(progress)`: `[0, 1]` as assets in the call complete.
- `onError(error, url)`: `url` is `string | ResolvedAsset`. Guard before reading `.src`; when `url` is a string, `.src` is undefined.
- `strategy: 'throw' | 'skip' | 'retry'` — default `'throw'`. `'skip'` resolves with any successful assets; `'retry'` reattempts the failed ones.
- `retryCount` — default `3`, retries per asset when `strategy` is `'retry'`.
- `retryDelay` — default `250` ms between retries.
Global defaults live on `Loader.defaultOptions`, or pass `loadOptions` to `Assets.init()`.
### `data` options (per asset)
Each loader parser reads its own options from the `data` field on the asset descriptor. Use the table below to pick the right options for each asset type:
| Asset type | `data` shape | Key options | Reference |
| ------------------ | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| Texture (image) | `TextureSourceOptions` | `resolution`, `scaleMode`, `alphaMode`, `autoGenerateMipmaps`, `antialias`, `addressMode` | `references/resolution.md` |
| SVG | `{ parseAsGraphicsContext?, resolution? }` | `parseAsGraphicsContext` for Graphics mode; `resolution` for sharper raster | `references/svg.md` |
| Video | `VideoSourceOptions` | `autoPlay`, `loop`, `muted`, `playsinline`, `preload`, `updateFPS`, `crossorigin`, `mime` | `references/video.md` |
| Web font | `LoadFontData` | `family`, `weights`, `style`, `display`, `unicodeRange`, `featureSettings` | `references/fonts.md` |
| Bitmap font | (none; auto-configured) | Distance-field detection sets scale mode and mipmaps | `references/fonts.md` |
| Spritesheet | `{ texture?, imageFilename?, ignoreMultiPack?, textureOptions?, cachePrefix? }` | `textureOptions` forwards `TextureSourceOptions` (e.g. `scaleMode`) to the atlas image; `texture` to skip image load; `imageFilename` to override the referenced image; `ignoreMultiPack` to skip multi-pack follow-ups; `cachePrefix` to namespace frames | `references/spritesheet.md` |
| GIF | `GifBufferOptions` | `fps`, `scaleMode`, `resolution`, `autoGenerateMipmaps` | `references/gif.md` |
| Compressed texture | `TextureSourceOptions` | `scaleMode`, `addressMode`, `autoGenerateMipmaps` | `references/compressed-textures.md` |
| JSON / Text | (none) | Returned as-is | — |
Example combining `LoadOptions` and `data`:
```ts
await Assets.load(
{
alias: "hero",
src: "hero.png",
data: { scaleMode: "nearest", resolution: 2 },
},
{ strategy: "retry", retryCount: 3 },
);
```
Inside a manifest or bundle, every entry can carry its own `data`:
```ts
await Assets.init({
manifest: {
bundles: [
{
name: "level1",
assets: [
{ alias: "tiles", src: "tiles.png", data: { scaleMode: "nearest" } },
{ alias: "font", src: "hero.woff2", data: { family: "Hero" } },
{
alias: "clip",
src: "intro.mp4",
data: { autoPlay: false, muted: true },
},
],
},
],
},
});
```
## Runtime configuration
`Assets.init(options)` accepts, alongside `basePath` and `manifest`:
- `defaultSearchParams` — string or `Record<string, any>` appended to every resolved URL. Useful for cache busting.
- `skipDetections: boolean` — bypass browser format detection for faster init. Requires explicit `texturePreference.format`.
- `bundleIdentifier: BundleIdentifierOptions` — customize how bundle keys resolve so the same alias can live in multiple bundles.
- `loadOptions: Partial<LoadOptions>` — set the default `strategy`, `retryCount`, `retryDelay`, and callbacks for every subsequent `Assets.load` call.
- `preferences: Partial<AssetsPreferences>` — `crossOrigin`, `preferWorkers`, `preferCreateImageBitmap`, `parseAsGraphicsContext`.
After init, preferences can still be tuned:
```ts
Assets.setPreferences({
crossOrigin: "anonymous",
preferCreateImageBitmap: false,
});
for (const detection of Assets.detections) {
console.log(detection.extension);
}
Assets.reset();
```
- `Assets.setPreferences(preferences)` — push new preferences to every parser that supports them.
- `Assets.detections` — getter exposing the registered `FormatDetectionParser` list; use when inspecting what formats the current environment advertises.
- `Assets.reset()` — internal full reset (resolver + loader + cache). Intended for tests so a fresh `Assets.init` can run.
## Common Mistakes
### [CRITICAL] Using `Texture.from(url)` to load
Wrong:
```ts
const texture = Texture.from("https://example.com/image.png");
```
Correct:
```ts
const texture = await Assets.load("https://example.com/image.png");
```
In v8, `Texture.from()` only reads the cache. It does not fetch from a URL. Use `Assets.load()` first; the return value is the texture itself.
### [HIGH] Using positional `Assets.add` signature
Wrong:
```ts
Assets.add("bunny", "bunny.png");
```
Correct:
```ts
Assets.add({ alias: "bunny", src: "bunny.png" });
```
The positional `Assets.add(key, url)` form was removed in v8. Use the options object with `alias` and `src` properties.
### [HIGH] Not unloading textures between levels
`Assets.load()` caches textures indefinitely. For level-based games or screens with distinct asset sets, call `Assets.unloadBundle()` when transitioning to release GPU memory.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [Loader](https://pixijs.download/release/docs/assets.Loader.html.md)
- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md)
- [Cache](https://pixijs.download/release/docs/assets.Cache.html.md)
- [LoadOptions](https://pixijs.download/release/docs/assets.LoadOptions.html.md)
- [AssetInitOptions](https://pixijs.download/release/docs/assets.AssetInitOptions.html.md)
- [AssetsManifest](https://pixijs.download/release/docs/assets.AssetsManifest.html.md)
- [AssetsBundle](https://pixijs.download/release/docs/assets.AssetsBundle.html.md)
- [BackgroundLoader](https://pixijs.download/release/docs/assets.BackgroundLoader.html.md)
- [Spritesheet](https://pixijs.download/release/docs/assets.Spritesheet.html.md)
@@ -0,0 +1,137 @@
# Background Loading
Background loading lets PixiJS fetch and prepare assets passively while other work happens. Use it to prime the next level while the current one is playing, preload assets during a splash screen, or prepare UI assets during initial load. `backgroundLoad` and `backgroundLoadBundle` are non-blocking and return immediately.
## Quick Start
```ts
await Assets.loadBundle("menu");
showMenu();
Assets.backgroundLoadBundle("level1");
playerClicksStart(() => {
Assets.loadBundle("level1").then(() => startLevel());
});
```
The `backgroundLoadBundle` call starts loading `level1` immediately without blocking. The later `loadBundle` call resolves quickly if background loading finished in the meantime.
## Core Patterns
### Background-loading a single asset
```ts
Assets.backgroundLoad("images/level2-assets.png");
// later, when we need it:
const texture = await Assets.load("images/level2-assets.png");
```
Fire-and-forget. Background loading happens one asset at a time to avoid blocking the main thread. When your code later calls `Assets.load(url)` for the same asset, it either resolves immediately (if background work finished) or waits for the already-in-progress load.
### Background-loading an array
```ts
Assets.backgroundLoad([
"images/sprite1.png",
"images/sprite2.png",
"images/background.png",
]);
```
Queues multiple assets for background loading. They're processed sequentially.
### Background-loading a bundle
```ts
await Assets.init({
manifest: {
bundles: [
{ name: "home", assets: [{ alias: "bg", src: "home-bg.png" }] },
{ name: "level-1", assets: [{ alias: "map", src: "level1-map.json" }] },
],
},
});
await Assets.loadBundle("home");
showHome();
Assets.backgroundLoadBundle("level-1");
onPlayClicked(async () => {
await Assets.loadBundle("level-1");
startLevel();
});
```
Same idea for bundles. Bundle assets are queued one at a time. Requires the bundle to exist via the manifest or `addBundle`.
### Interrupting background loading
```ts
Assets.backgroundLoadBundle("level-2");
onPlayerDecidedLevel3(async () => {
await Assets.loadBundle("level-3");
});
```
Calling `Assets.load()` or `Assets.loadBundle()` interrupts background loading safely. The current background asset finishes, then the explicit load takes priority. Your explicit load resolves normally.
### Combining with a progress bar
Background loading has no progress callback; it runs silently. To show a loading bar, use `Assets.loadBundle(name, onProgress)` in the foreground instead. Typical pattern: use background loading for nice-to-have preloads and foreground loading for the bundles you're actually waiting on.
## Common Mistakes
### [HIGH] Expecting progress from background loading
Wrong:
```ts
Assets.backgroundLoadBundle("level2", (p) => updateBar(p));
```
Correct:
```ts
Assets.backgroundLoadBundle("level2");
// show a spinner or no UI while it runs
```
`backgroundLoad` and `backgroundLoadBundle` don't accept progress callbacks. They're silent. For visible progress, use the foreground `Assets.load` / `Assets.loadBundle` with an `onProgress` argument.
### [MEDIUM] Assuming background load completes before next foreground load
Wrong:
```ts
Assets.backgroundLoadBundle("level-2");
setTimeout(() => startLevel2(), 0);
```
Correct:
```ts
Assets.backgroundLoadBundle("level-2");
onStart(async () => {
await Assets.loadBundle("level-2");
startLevel2();
});
```
Background loading is best-effort. If the player hits Start before it finishes, the foreground `loadBundle` still needs to await the remaining work. Always `await` the real load before using the assets.
### [MEDIUM] Background-loading assets that are never used
Each queued background load consumes bandwidth and GPU memory. If the player never visits level 2, you've wasted that bandwidth. Background-load only what you're confident will be needed soon.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [BackgroundLoader](https://pixijs.download/release/docs/assets.BackgroundLoader.html.md)
@@ -0,0 +1,122 @@
# Bundles
A bundle is a named group of assets you can load or unload as a unit. Use bundles to batch assets per game level, UI screen, or feature so that a single `loadBundle(name)` call resolves everything needed for that context. Bundles play well with background loading and manifest-based workflows.
## Quick Start
```ts
Assets.addBundle("level1", [
{ alias: "bg", src: "level1/background.png" },
{ alias: "tileset", src: "level1/tiles.json" },
{ alias: "theme", src: "level1/music.mp3" },
]);
const resources = await Assets.loadBundle("level1");
const bg = Sprite.from("bg");
```
`loadBundle(name)` returns a `Record<alias, asset>`. Each alias is also available via `Assets.get(alias)` after the bundle resolves.
## Core Patterns
### Programmatic bundles
```ts
Assets.addBundle("ui", [
{ alias: "button", src: "ui/button.png" },
{ alias: "panel", src: "ui/panel.png" },
{ alias: "cursor", src: "ui/cursor.png" },
]);
await Assets.loadBundle("ui");
```
`addBundle(name, assets)` registers a bundle at runtime. The assets array uses the same `{ alias, src, data? }` shape as `Assets.add()`.
### Loading multiple bundles at once
```ts
await Assets.loadBundle(["ui", "level1", "sounds"]);
```
Pass an array of bundle names to load them in parallel. The returned object is keyed by bundle name: `{ ui: {...}, level1: {...}, sounds: {...} }`.
### Progress across a bundle
```ts
await Assets.loadBundle("level1", (progress) => {
loadingBar.width = progress * maxBarWidth;
});
```
The second argument is a `ProgressCallback` that fires as each asset in the bundle completes. Progress is normalized `[0, 1]` across the entire bundle.
### Unloading a bundle
```ts
await Assets.unloadBundle("level1");
```
Tears down every asset in the bundle, releases GPU memory, and removes cached entries. Remove any Sprites or Text that reference the bundle's textures before unloading.
### Sharing assets between bundles
```ts
Assets.addBundle("main", [{ alias: "hero", src: "hero.png" }]);
Assets.addBundle("bossArea", [{ alias: "hero", src: "hero.png" }]);
```
If two bundles declare the same alias with the same `src`, the underlying texture is loaded once and shared. There is no reference counting: unloading either bundle destroys the shared texture, and the other bundle's alias stays broken until you reload it.
### Bundle IDs
```ts
const resources = await Assets.loadBundle("level1");
const bg = resources["bg"];
const fromCache = Assets.get("bg");
const fromNamespaced = Assets.get("level1-bg");
```
Inside the resolver, bundle assets are stored under a combined key like `'level1-bg'` by default. The plain `'bg'` alias still resolves thanks to resolver shortcuts. If you need to override the format, pass `bundleIdentifier` to `Assets.init()`.
## Common Mistakes
### [HIGH] Unloading while assets are still in use
Wrong:
```ts
await Assets.unloadBundle("level1");
// level1 sprites still on the stage; they now reference destroyed textures
```
Correct:
```ts
level1Container.destroy({ children: true });
await Assets.unloadBundle("level1");
```
Always destroy (or detach from the scene) any display objects that reference the bundle's textures before unloading. Otherwise the renderer hits freed GPU memory and errors.
### [MEDIUM] Confusing `addBundle` and `init` manifests
Wrong:
```ts
await Assets.init();
Assets.addBundle('ui', [...]);
await Assets.loadBundle('ui');
```
Both work; this is not actually wrong; but a manifest passed to `Assets.init({ manifest: {...} })` registers all bundles at init time in one place. Prefer manifests when you know all bundles upfront; prefer `addBundle` when bundles are discovered dynamically at runtime.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [AssetsBundle](https://pixijs.download/release/docs/assets.AssetsBundle.html.md)
- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md)
@@ -0,0 +1,143 @@
# Caching
Every asset loaded through `Assets` is cached until you explicitly unload it. The cache is a global singleton keyed by the resolved URL, alias, and any bundle identifier. Use the cache to avoid double-loading, retrieve loaded assets synchronously, and reclaim GPU memory when an asset is no longer needed.
## Quick Start
```ts
await Assets.load("hero.png");
const cached = Assets.get("hero.png");
const sprite = new Sprite(cached);
await Assets.unload("hero.png");
```
`Assets.load` adds the asset to the cache; `Assets.get` retrieves it synchronously; `Assets.unload` removes it and releases the underlying GPU resource.
## Core Patterns
### Synchronous access to already-loaded assets
```ts
await Assets.load(["hero.png", "enemy.png"]);
const hero = Assets.get("hero");
const enemy = Assets.get("enemy");
if (hero) {
app.stage.addChild(new Sprite(hero));
}
```
`Assets.get(alias)` returns `undefined` if the asset has not been loaded yet. It is synchronous; use it in tight loops or anywhere `await` would be awkward.
### Multiple keys at once
```ts
await Assets.load(["hero", "enemy", "boss"]);
const all = Assets.get(["hero", "enemy", "boss"]);
const heroTex = all["hero"];
```
Passing an array returns an object keyed by alias. Useful for retrieving all the assets a scene needs in one call.
### Deduping load calls
```ts
const tex1 = await Assets.load("hero.png");
const tex2 = await Assets.load("hero.png");
console.log(tex1 === tex2); // true
```
Calling `Assets.load` with the same key multiple times returns the same cached result immediately on subsequent calls. Safe to call from multiple async functions concurrently.
### Unloading
```ts
sprite.destroy();
await Assets.unload("hero.png");
```
`Assets.unload(id)` removes the asset from the cache, calls `destroy()` on the texture (releasing GPU memory), and removes any loader-specific wrappers. Always destroy or detach display objects that reference the asset before unloading, or you'll hit freed GPU memory.
### Unloading a bundle
```ts
level1Container.destroy({ children: true });
await Assets.unloadBundle("level1");
```
Prefer `unloadBundle` over manually iterating. It has no reference counting: every asset in the bundle is removed from the cache and destroyed, even if another bundle declares the same `src`, and that bundle's alias stays broken until you reload it. Detach anything on the scene that still uses those assets first.
### Inspecting the cache
```ts
import { Cache } from "pixi.js";
const key = "hero.png";
if (Cache.has(key)) {
const texture = Cache.get(key);
}
```
The low-level `Cache` class backs `Assets.get`. It exposes `has(key)`, `get(key)`, `set(key, value)`, and `remove(key)`. Most code should go through `Assets.get/unload` instead, but direct `Cache` access is useful for diagnostics or custom loader plugins.
## Common Mistakes
### [CRITICAL] Using `Assets.get` before `Assets.load`
Wrong:
```ts
const texture = Assets.get("hero.png");
const sprite = new Sprite(texture); // texture is undefined
```
Correct:
```ts
await Assets.load("hero.png");
const texture = Assets.get("hero.png");
const sprite = new Sprite(texture);
```
`Assets.get` is synchronous and returns `undefined` if the asset hasn't been loaded yet. Always await `Assets.load` first, or use the return value of `Assets.load` directly.
### [HIGH] Not unloading between levels
Textures stay in the cache indefinitely. A game that loads level after level without calling `Assets.unload` or `Assets.unloadBundle` slowly accumulates GPU memory until it hits browser limits.
```ts
await Assets.unloadBundle("level1");
await Assets.loadBundle("level2");
```
### [MEDIUM] Using sprites after unload
Wrong:
```ts
const sprite = new Sprite(texture);
await Assets.unload("hero.png");
// sprite still references the destroyed texture
```
Correct:
```ts
sprite.destroy();
await Assets.unload("hero.png");
```
`Assets.unload` destroys the underlying texture. Any sprite still referencing it will render Texture.EMPTY or crash depending on the backend. Destroy the leaf (or reassign its texture) before unloading.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [Cache](https://pixijs.download/release/docs/assets.Cache.html.md)
- [Texture](https://pixijs.download/release/docs/rendering.Texture.html.md)
@@ -0,0 +1,120 @@
# Compressed Textures
GPU-compressed texture formats (DDS, KTX, KTX2, Basis) use 4–8x less GPU memory than PNG/JPEG and skip runtime decoding. Use them for large textures, high-asset-count games, and anywhere memory budget matters. Each format requires a side-effect import to register its loader.
## Quick Start
```ts
import "pixi.js/ktx2";
import { Assets, Sprite } from "pixi.js";
const texture = await Assets.load("background.ktx2");
const bg = new Sprite(texture);
app.stage.addChild(bg);
```
Without the side-effect import, the loader won't know how to parse the file and will skip it silently.
## Core Patterns
### Format imports
```ts
import "pixi.js/dds"; // DirectDraw Surface (.dds)
import "pixi.js/ktx"; // KTX (Khronos Texture) v1
import "pixi.js/ktx2"; // KTX v2 (with Basis Universal support)
import "pixi.js/basis"; // Basis Universal (.basis)
```
Each import registers a `LoaderParser` that can decode the matching file extension. Import only the formats you use; the loaders include decoder runtime that adds to your bundle size.
### Format selection matrix
| Format | Platforms | Notes |
| ------ | --------- | --------------------------------------------------------------------------------------------------------------- |
| DDS | All | Legacy desktop formats (DXT, BC). Fast decoder; wide support. |
| KTX | All | Older Khronos container. Prefer KTX2 for new projects. |
| KTX2 | All | Newer container; typically used with Basis Universal. GPU-native when available. |
| Basis | All | Supercompressed; transcodes to the GPU-native format at load time. Best for "one file, any platform" workflows. |
Use KTX2 + Basis for new projects unless you have a specific need for one of the others.
### With the resolver
```ts
import "pixi.js/ktx2";
import { Assets } from "pixi.js";
Assets.add({
alias: "background",
src: "background.{ktx2,webp,png}",
});
const texture = await Assets.load("background");
```
List compressed textures as first-preference format in the resolver. On browsers or hardware that can't sample the compressed format, the resolver falls back to WebP or PNG automatically.
### Async decoding
```ts
import "pixi.js/basis";
import { Assets } from "pixi.js";
const texture = await Assets.load("hero.basis");
```
Basis Universal decodes asynchronously on a worker thread (where supported). You don't need to await anything beyond the normal `Assets.load`; the loader handles decoding.
### Multiple compressed formats at once
```ts
import "pixi.js/ktx2";
import "pixi.js/basis";
import "pixi.js/dds";
```
Multiple format imports can coexist. Each registers an extension for its own file type. If you only use one format, import only that one to keep the bundle smaller.
## Common Mistakes
### [CRITICAL] Missing the format import
Wrong:
```ts
import { Assets } from "pixi.js";
await Assets.load("background.ktx2");
```
Correct:
```ts
import "pixi.js/ktx2";
import { Assets } from "pixi.js";
await Assets.load("background.ktx2");
```
Without the side-effect import, no loader parser is registered for `.ktx2` files. The load silently does nothing (or errors) and you get `undefined` back.
### [HIGH] Relying on mipmaps from compressed textures in Canvas2D
Compressed textures require WebGL or WebGPU. The Canvas2D backend can't sample them. If you need Canvas support, include a PNG/WebP fallback via the resolver format list:
```ts
Assets.add({ alias: "bg", src: "bg.{ktx2,png}" });
```
### [MEDIUM] Large Basis files in WebGL1
Basis Universal transcodes to different GPU formats based on what the device supports. On WebGL1 without extensions, some devices fall back to an uncompressed format, defeating the memory savings. Check `renderer.context.supports` for supported compressed formats if you're targeting older hardware.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [loadKTX2](https://pixijs.download/release/docs/assets.loadKTX2.html.md)
- [TextureSource](https://pixijs.download/release/docs/rendering.TextureSource.html.md)
@@ -0,0 +1,205 @@
# Fonts
PixiJS loads two kinds of fonts through `Assets`: web fonts (TTF/OTF/WOFF/WOFF2) via `loadWebFont`, and bitmap fonts (FNT/XML) via `loadBitmapFont`. Use web fonts for `Text` and `HTMLText`; use bitmap fonts for `BitmapText` when you need GPU-friendly rendering without runtime text layout.
## Web fonts
### Quick Start
```ts
await Assets.load("fonts/titan-one.woff2");
const text = new Text({
text: "Hello world",
style: { fontFamily: "Titan One", fontSize: 48 },
});
```
Once the font is loaded, reference it by its derived family name in any `TextStyle`. PixiJS registers the font with the browser's `FontFaceSet`, so DOM elements and Canvas can use it too.
### Family name derivation
```ts
// Loaded URL → Derived family name
// fonts/titan-one.woff → 'Titan One'
// fonts/open_sans.ttf → 'Open Sans'
// fonts/my-custom-font.otf → 'My Custom Font'
```
By default, the family name is the filename without extension, with dashes and underscores replaced by spaces and title-cased. Override it with `data.family`.
### Load options via `data`
```ts
await Assets.load({
alias: "hero-font",
src: "fonts/hero.woff2",
data: {
family: "HeroFont",
weights: ["normal", "bold"],
style: "italic",
display: "swap",
unicodeRange: "U+0000-00FF",
stretch: "expanded",
featureSettings: '"liga" 1',
},
});
```
Fields on `data` map directly to FontFace descriptors:
| Option | Purpose |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `family` | Override the derived font family name |
| `weights` | Array of weights to register. One `FontFace` per weight, all sharing the same URL. Valid values: `'normal'`, `'bold'`, `'100'`–`'900'` |
| `style` | `'normal'`, `'italic'`, `'oblique'` |
| `display` | CSS `font-display` (`'auto'`, `'block'`, `'swap'`, `'fallback'`, `'optional'`) |
| `unicodeRange` | Restrict which codepoints the font covers |
| `stretch` | `'normal'`, `'condensed'`, `'expanded'`, etc. |
| `variant` | CSS font-variant value |
| `featureSettings` | OpenType feature settings like `'"liga" 1, "dlig" 1'` |
### Loading multiple weights
```ts
await Assets.load({
src: "fonts/inter.woff2",
data: {
family: "Inter",
weights: ["400", "700"],
},
});
```
A single URL registers as multiple weights. Use when your font file contains a variable font or when your platform lets one file satisfy multiple weights.
### Supported extensions
`.ttf`, `.otf`, `.woff`, `.woff2`. WOFF2 is the smallest and universally supported in current browsers. Prefer it unless you're targeting very old environments.
## Bitmap fonts
### Quick Start
```ts
import "pixi.js/text-bitmap";
await Assets.load("fonts/arial.fnt");
const text = new BitmapText({
text: "Score: 9999",
style: { fontFamily: "Arial", fontSize: 32 },
});
```
The side-effect import registers the `CanvasBitmapTextPipe` and `BitmapTextPipe` rendering pipes. `Assets.load('font.fnt')` works without it and returns a `BitmapFont`, but rendering a `BitmapText` fails at render time without the import.
### Supported formats
| Extension | Format |
| --------- | ------------------ |
| `.fnt` | BMFont text or XML |
| `.xml` | BMFont XML |
The parser sniffs the content to pick between text and XML automatically.
### Texture page loading
```ts
// my-font.fnt references my-font_0.png, my-font_1.png
await Assets.load("fonts/my-font.fnt");
```
Bitmap fonts reference page images by filename in the `.fnt` data. The parser resolves these relative to the `.fnt` URL and loads them automatically. Any search params on the `.fnt` URL (e.g. cache busting) propagate to the page texture URLs.
### Signed Distance Field (SDF) fonts
The parser detects distance field metadata in the `.fnt` file and enables `linear` scale mode plus disables mipmaps automatically. No extra configuration needed from the caller. SDF fonts stay crisp at any size, so you can render a single bitmap font at many different sizes.
### Accessing the BitmapFont instance
```ts
await Assets.load({ alias: "arial", src: "fonts/arial.fnt" });
const font = Assets.get("arial");
console.log(font.chars);
console.log(font.fontFamily);
```
The cached asset is a `BitmapFont` instance. `Assets.get('arial')` and `Assets.get('arial-bitmap')` both return it, and `Assets.get('Arial-bitmap')` works if `fontFamily` matches.
## Forcing the font parser
If your font URL lacks an extension, force the loader:
```ts
await Assets.load({
src: "https://cdn.example.com/fonts/abc123",
parser: "web-font",
data: { family: "Hero", weights: ["400", "700"] },
});
await Assets.load({
src: "https://cdn.example.com/fonts/hero-bmfont",
parser: "bitmap-font",
});
```
See the main `SKILL.md` section on "Forcing a parser with `parser`" for the full list of parser IDs.
## Common Mistakes
### [HIGH] Forgetting the bitmap-font import
Wrong:
```ts
import { Assets, BitmapText } from "pixi.js";
await Assets.load("arial.fnt");
const text = new BitmapText({ text: "Hi", style: { fontFamily: "Arial" } });
app.stage.addChild(text);
```
Correct:
```ts
import "pixi.js/text-bitmap";
import { Assets, BitmapText } from "pixi.js";
await Assets.load("arial.fnt");
const text = new BitmapText({ text: "Hi", style: { fontFamily: "Arial" } });
app.stage.addChild(text);
```
`Assets.load('arial.fnt')` succeeds in the default bundle and returns a `BitmapFont`, but `'pixi.js/text-bitmap'` registers the `CanvasBitmapTextPipe` and `BitmapTextPipe`. Without it, `BitmapText` renders nothing or errors at render time.
### [HIGH] Using Text before the font is loaded
Wrong:
```ts
const text = new Text({ text: "Hi", style: { fontFamily: "Hero" } });
Assets.load("fonts/hero.woff2");
```
Correct:
```ts
await Assets.load("fonts/hero.woff2");
const text = new Text({ text: "Hi", style: { fontFamily: "Hero" } });
```
The browser falls back to a system font if the named family isn't registered yet, then the `Text` is cached at that fallback style. Reloading the font doesn't repaint existing Text objects.
### [MEDIUM] Family name mismatch
If you don't pass `data.family`, the family name is derived from the filename. `my_hero_font.woff` becomes `'My Hero Font'`; use exactly that string in your `TextStyle.fontFamily`, or set `data.family` to an explicit value.
## API Reference
- [loadWebFont](https://pixijs.download/release/docs/assets.loadWebFont.html.md)
- [loadBitmapFont](https://pixijs.download/release/docs/assets.loadBitmapFont.html.md)
- [LoadFontData](https://pixijs.download/release/docs/assets.LoadFontData.html.md)
- [BitmapFont](https://pixijs.download/release/docs/scene.BitmapFont.html.md)
@@ -0,0 +1,171 @@
# Animated GIFs
PixiJS loads animated GIFs through `Assets.load()` and returns a `GifSource` containing all decoded frames. Pass the source to `GifSprite` for playback, looping, and frame control. GIF support is opt-in via the `'pixi.js/gif'` side-effect import.
## Quick Start
```ts
import "pixi.js/gif";
import { Assets, GifSprite } from "pixi.js";
const source = await Assets.load("explosion.gif");
const gif = new GifSprite(source);
app.stage.addChild(gif);
```
Without `'pixi.js/gif'`, the `.gif` loader parser isn't registered and `Assets.load()` won't know what to do with the file.
## Core Patterns
### Load options via `data`
```ts
const source = await Assets.load({
src: "pixel-art.gif",
data: {
fps: 12,
scaleMode: "nearest",
resolution: 2,
autoGenerateMipmaps: false,
},
});
```
`data` accepts `GifBufferOptions`, which extends `CanvasSourceOptions`:
| Option | Default | Purpose |
| --------------------- | ---------- | ---------------------------------------------------------------- |
| `fps` | `30` | Fallback frame rate when the GIF has no per-frame delay metadata |
| `scaleMode` | `'linear'` | `'nearest'` for pixel art, `'linear'` for smooth scaling |
| `resolution` | `1` | Render resolution of the decoded frames |
| `autoGenerateMipmaps` | `false` | Generate mipmaps for downscaling |
Any other `CanvasSourceOptions` field works here too.
### GifSprite options
```ts
const gif = new GifSprite({
source,
autoPlay: true,
loop: true,
animationSpeed: 0.5,
autoUpdate: true,
fps: 30,
onComplete: () => console.log("done"),
onLoop: () => console.log("looped"),
onFrameChange: (frame) => console.log(frame),
});
```
Construction options control playback behavior; they're independent of the load-time `data` options.
### Loading from a data URI
```ts
const source = await Assets.load(
"data:image/gif;base64,R0lGODlhAQABAAAAACw...",
);
```
The parser matches both `.gif` file extensions and `data:image/gif` URIs. No extra configuration needed.
### Playback control
```ts
gif.play();
gif.stop();
gif.currentFrame = 5;
gif.animationSpeed = 0.5;
gif.loop = false;
console.log(gif.totalFrames);
console.log(gif.playing);
console.log(gif.progress);
console.log(gif.duration);
```
### Sharing a source across sprites
```ts
const source = await Assets.load("spin.gif");
const a = new GifSprite(source);
const b = new GifSprite(source);
a.animationSpeed = 1;
b.animationSpeed = 0.25;
```
Multiple `GifSprite` instances can share the same `GifSource`; each gets independent playback state. The underlying textures are shared, so this is cheap.
### Cleanup
```ts
gif.destroy(); // destroys the sprite, not the source
gif.destroy(true); // destroys the sprite AND the source (breaks other sprites using it)
await Assets.unload("explosion.gif"); // unload through the Assets system
```
Prefer `Assets.unload` unless you know no other sprite shares the same `GifSource`.
## Forcing the GIF parser
If your GIF URL lacks an extension, force the parser:
```ts
const source = await Assets.load({
src: "https://cdn.example.com/gif/abc123",
parser: "gif",
data: { fps: 24 },
});
```
See the main `SKILL.md` section on "Forcing a parser with `parser`" for the full list of parser IDs.
## Common Mistakes
### [CRITICAL] Missing the GIF import
Wrong:
```ts
import { Assets } from "pixi.js";
await Assets.load("explosion.gif");
```
Correct:
```ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
await Assets.load("explosion.gif");
```
Without `'pixi.js/gif'`, the loader parser isn't registered. The call fails or returns undefined.
### [MEDIUM] Using GIF when a spritesheet would be cheaper
GIF decoding creates one texture per frame. For a 30-frame animation that's 30 separate uploads. A spritesheet packs all frames into a single atlas texture, which batches better and uses less GPU memory. Prefer spritesheets for performance-critical game animations; use GIFs for convenience and one-off effects.
### [MEDIUM] destroy(true) when other sprites share the source
```ts
const source = await Assets.load("spin.gif");
const a = new GifSprite(source);
const b = new GifSprite(source);
a.destroy(true); // WRONG: also destroys source, breaking sprite b
```
Pass `true` to `destroy` only if you know nothing else references the `GifSource`. Otherwise call plain `destroy()` and `Assets.unload()` when the source is no longer needed.
## API Reference
- [GifSource](https://pixijs.download/release/docs/gif.GifSource.html.md)
- [GifSprite](https://pixijs.download/release/docs/gif.GifSprite.html.md)
- [GifBufferOptions](https://pixijs.download/release/docs/gif.GifBufferOptions.html.md)
- [GifAsset](https://pixijs.download/release/docs/gif.GifAsset.html.md)
@@ -0,0 +1,175 @@
# Manifests
A manifest is a JSON-shaped description of every bundle in your application. Pass it to `Assets.init({ manifest })` and the resolver registers every bundle at startup, so later code can reference them by name. Use manifests when you know your asset graph upfront and want one source of truth.
## Quick Start
```ts
await Assets.init({
manifest: {
bundles: [
{
name: "load-screen",
assets: [{ alias: "logo", src: "logo.png" }],
},
{
name: "game",
assets: [
{ alias: "hero", src: "hero.{webp,png}" },
{ alias: "enemies", src: "enemies.json" },
],
},
],
},
});
await Assets.loadBundle("load-screen");
await Assets.loadBundle("game");
```
Each bundle has a `name` and an `assets` array of `UnresolvedAsset` entries. Format expansions (`{webp,png}`) and resolution patterns (`@{1,2}x`) work inside `src`.
## Core Patterns
### Inline manifest object
```ts
const manifest = {
bundles: [
{
name: "ui",
assets: [
{ alias: "button", src: "ui/button.png" },
{ alias: "panel", src: "ui/panel.png" },
],
},
],
};
await Assets.init({ manifest });
```
The manifest can be any plain object matching the `AssetsManifest` shape. Pass it directly to `init`.
### Manifest from a URL
```ts
await Assets.init({ manifest: "assets/manifest.json" });
```
When `manifest` is a string, PixiJS loads it as JSON first, then registers the bundles. Useful when your build tooling generates a manifest at deploy time (e.g., with `@assetpack/core`).
### Format and resolution patterns in manifests
```ts
const manifest = {
bundles: [
{
name: "hero",
assets: [{ alias: "hero", src: "hero@{0.5,1,2}x.{webp,avif,png}" }],
},
],
};
```
The resolver expands the pattern to six candidates and picks the best match based on `window.devicePixelRatio` and browser format support. Configure preferences in `Assets.init({ texturePreference: {...} })`.
### Multiple aliases per entry
```ts
const manifest = {
bundles: [
{
name: "characters",
assets: [
{ alias: ["hero", "player"], src: "hero.png" },
{ alias: "npc1", src: "villager.png" },
],
},
],
};
```
An asset can expose multiple aliases. `Assets.load('hero')` and `Assets.load('player')` return the same texture.
### Data options in manifest entries
```ts
const manifest = {
bundles: [
{
name: "pixel-art",
assets: [
{
alias: "tile",
src: "tile.png",
data: { scaleMode: "nearest" },
},
],
},
],
};
```
Each asset entry can include a `data` field forwarded to the loader. Use it for `scaleMode`, `autoGenerateMipmaps`, `parseAsGraphicsContext`, FontFace descriptors, etc.
### Background-loading from a manifest
```ts
await Assets.init({ manifest });
await Assets.loadBundle("load-screen");
Assets.backgroundLoadBundle("game");
await Assets.loadBundle("game");
```
After init, you can start background loading of other bundles immediately. The call is non-blocking; the `await Assets.loadBundle('game')` later resolves quickly if the background work finished.
## Common Mistakes
### [HIGH] Calling `Assets.init` twice
Wrong:
```ts
await Assets.init({ manifest });
await Assets.init({ basePath: "https://cdn.example.com/" });
```
Correct:
```ts
await Assets.init({ manifest, basePath: "https://cdn.example.com/" });
```
`Assets.init()` can only be called once. The second call is ignored with a warning. Combine all configuration into a single call.
### [MEDIUM] Missing format expansion on manifest entries
Wrong:
```ts
{ alias: 'hero', src: 'hero.webp' }
```
Correct:
```ts
{ alias: 'hero', src: 'hero.{webp,png}' }
```
Listing only one format blocks the resolver from falling back on browsers without WebP/AVIF support. Always list at least one fallback.
### [MEDIUM] Loading manifest after `Assets.add`
If you call `Assets.add(...)` or `Assets.addBundle(...)` before `Assets.init({ manifest })`, the manifest bundles will append to the existing state but preference-detection (format, resolution) hasn't run yet. Prefer calling `init` first, then adding ad-hoc assets.
## API Reference
- [AssetsManifest](https://pixijs.download/release/docs/assets.AssetsManifest.html.md)
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md)
- [UnresolvedAsset](https://pixijs.download/release/docs/assets.UnresolvedAsset.html.md)
@@ -0,0 +1,142 @@
# Progress Tracking
`Assets.load` and `Assets.loadBundle` accept a progress callback that fires as each asset completes. Use it to drive loading bars, percentage readouts, or spinner state updates during long loads. The progress value is normalized `[0, 1]` across the entire call.
## Quick Start
```ts
const loadingBar = new Graphics();
app.stage.addChild(loadingBar);
await Assets.load(["hero.png", "enemy.png", "map.json"], (progress) => {
loadingBar.clear();
loadingBar.rect(0, 0, progress * 400, 20).fill(0x66ccff);
});
```
The callback is invoked after each asset resolves. Final invocation reaches `1.0` just before the promise resolves.
## Core Patterns
### Progress on a single asset
```ts
await Assets.load("large-atlas.json", (progress) => {
console.log(`${Math.round(progress * 100)}%`);
});
```
Even for a single asset, the callback fires (typically once, reaching `1.0`). For most cases, progress for a single call is not useful; prefer progress on bundles or arrays.
### Progress on an array
```ts
const assets = await Assets.load(
["hero.png", "enemy.png", "map.json", "music.mp3"],
(progress) => updateBar(progress),
);
```
Progress is distributed evenly across the N assets. When the third asset in a four-asset array finishes, progress is `0.75`.
### Progress on a bundle
```ts
await Assets.loadBundle("level1", (progress) => {
loadingText.text = `Loading… ${Math.round(progress * 100)}%`;
});
```
Each asset in the bundle contributes equally. If the bundle has 10 entries, each contributes `0.1` to the total.
### Progress via `LoadOptions.onProgress`
```ts
await Assets.load("game.json", {
onProgress: (progress) => updateBar(progress),
onError: (err, asset) => {
const src = typeof asset === "string" ? asset : asset.src;
console.warn("failed:", src, err);
},
});
```
Instead of a callback as the second argument, pass a `LoadOptions` object. This is the preferred form when you also need error handling or retry strategies. Note that `onError` receives `string | ResolvedAsset`; guard before accessing `.src`.
### Global progress across multiple loads
```ts
async function loadAllWithTotal(tasks: Array<() => Promise<any>>) {
let done = 0;
for (const task of tasks) {
await task();
done++;
updateBar(done / tasks.length);
}
}
await loadAllWithTotal([
() => Assets.load("menu.json"),
() => Assets.loadBundle("level1"),
() => Assets.loadBundle("sounds"),
]);
```
Progress callbacks are scoped per call. If you need a single bar across several sequential loads, wrap the calls manually and count completions yourself.
## Common Mistakes
### [HIGH] Treating progress callback as completion
Wrong:
```ts
Assets.load("hero.png", (progress) => {
if (progress === 1) {
showHero();
}
});
```
Correct:
```ts
await Assets.load("hero.png", (progress) => updateBar(progress));
showHero();
```
`progress === 1` may fire slightly before the returned promise resolves. Always use the `await` or `.then()` to know when loading is truly complete. The progress callback is for UI updates only.
### [MEDIUM] Progress not updating smoothly
Each asset contributes a discrete step. If your bundle has three assets, progress jumps `0 -> 0.33 -> 0.66 -> 1.0`. For a smoother bar, split large bundles into smaller ones, or animate the bar width toward the target value:
```ts
let target = 0;
await Assets.loadBundle("game", (p) => {
target = p;
});
app.ticker.add(() => {
loadingBar.width += (target * maxWidth - loadingBar.width) * 0.1;
});
```
### [MEDIUM] Progress via background loading
Wrong:
```ts
Assets.backgroundLoadBundle("game", (p) => updateBar(p));
```
Background loading has no progress callback. For visible progress, use `Assets.loadBundle` (foreground). See `references/background.md`.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [LoadOptions](https://pixijs.download/release/docs/assets.LoadOptions.html.md)
- [ProgressCallback](https://pixijs.download/release/docs/assets.ProgressCallback.html.md)
@@ -0,0 +1,142 @@
# Resolution and Format Detection
PixiJS's asset resolver can pick the best asset variant for the current device based on pixel density (`@0.5x`, `@1x`, `@2x`) and supported image formats (`avif`, `webp`, `png`). Use resolution and format patterns to serve one asset spec that adapts to retina displays, format support, and bandwidth budgets.
## Quick Start
```ts
await Assets.init({
texturePreference: {
resolution: window.devicePixelRatio,
format: ["avif", "webp", "png"],
},
});
Assets.add({ alias: "hero", src: "hero@{0.5,1,2}x.{webp,png}" });
const texture = await Assets.load("hero");
```
The resolver expands the pattern to six candidates (`hero@0.5x.webp`, `hero@0.5x.png`, `hero@1x.webp`, ...) and picks the best match based on device pixel ratio and format support.
## Core Patterns
### Configuring preferences at init
```ts
await Assets.init({
texturePreference: {
resolution: window.devicePixelRatio, // e.g., 2 on retina
format: ["avif", "webp", "png"], // preferred-first order
},
});
```
- `resolution` is a single number (best-match threshold) or array of acceptable resolutions.
- `format` is ordered by preference. The resolver tries each in turn and uses the first one the browser supports.
### Resolution patterns in src
```ts
Assets.add({ alias: "bg", src: "bg@{0.5,1,2}x.png" });
```
The resolver expands this to `bg@0.5x.png`, `bg@1x.png`, `bg@2x.png` and picks based on `texturePreference.resolution`. Encoded resolution sets the texture's source resolution automatically, so the sprite's `width` / `height` appear as logical size regardless of the file chosen.
### Format patterns in src
```ts
Assets.add({ alias: "icon", src: "icon.{avif,webp,png}" });
```
Format detection runs once during `Assets.init()`. The resolver learns which formats the browser supports, then picks the highest-preference supported format per load.
### Combined resolution + format
```ts
Assets.add({ alias: "hero", src: "hero@{0.5,1,2}x.{avif,webp,png}" });
```
Both patterns can appear in the same `src`. The resolver does a Cartesian product: 3 resolutions × 3 formats = 9 candidates. It picks the best combination based on both preferences.
### Manual resolution override
```ts
Assets.add({
alias: "sharp",
src: "sharp.png",
data: { resolution: 2 },
});
```
If a file is already at a known resolution but lacks the `@2x` filename suffix, pass `resolution` in `data` to tell the loader. Useful when your tooling doesn't produce suffixed filenames.
### Custom retina prefix
```ts
import { Resolver } from "pixi.js";
Resolver.RETINA_PREFIX = /@([0-9\.]+)density/;
Assets.add({ alias: "hero", src: "hero@{1,2}density.png" });
```
Change the resolution filename pattern if your build pipeline uses a different convention. Default is `/@([0-9\.]+)x/`.
### Skipping format detection
```ts
await Assets.init({
skipDetections: true,
texturePreference: { format: ["webp"] },
});
```
If you know your target browser supports a specific format, `skipDetections: true` skips the runtime detection (a small init-time saving). Useful for embedded or kiosk deployments where format support is fixed.
## Common Mistakes
### [HIGH] Wrong pattern syntax
Wrong:
```ts
Assets.add({ alias: "hero", src: "hero@[1,2]x.png" });
```
Correct:
```ts
Assets.add({ alias: "hero", src: "hero@{1,2}x.png" });
```
The expansion syntax uses `{}` (like shell brace expansion), not `[]`. Square brackets aren't recognized and the resolver tries to load the literal filename.
### [MEDIUM] Missing fallback format
Wrong:
```ts
Assets.add({ alias: "hero", src: "hero.avif" });
```
Correct:
```ts
Assets.add({ alias: "hero", src: "hero.{avif,png}" });
```
If a browser doesn't support AVIF, the loader fails. Always list at least one fallback format that all target browsers support.
### [MEDIUM] Mismatch between spritesheet.json `meta.scale` and actual image
In v8, a spritesheet's `meta.scale` field directly sets the resolution of the atlas texture. If the JSON says `"1"` but the image was exported at 2x, frames render at double the intended size. Verify `meta.scale` matches the actual image resolution; atlas tools like TexturePacker set this automatically.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md)
- [AssetInitOptions](https://pixijs.download/release/docs/assets.AssetInitOptions.html.md)
@@ -0,0 +1,119 @@
# Spritesheet: Texture Atlases and Animations
Load and use texture atlases and animation sheets with PixiJS's `Spritesheet` class. Atlases reduce draw calls by packing many textures into a single image.
## Quick Start
```ts
const sheet = await Assets.load("spritesheet.json");
const hero = new Sprite(sheet.textures["hero.png"]);
app.stage.addChild(hero);
const walk = new AnimatedSprite(sheet.animations["walk"]);
walk.animationSpeed = 0.15;
walk.play();
app.stage.addChild(walk);
```
When loaded through `Assets.load()`, the JSON file is fetched, the atlas image is loaded, and `sheet.parse()` is called automatically. The returned object is a `Spritesheet` instance.
## Core Patterns
### SpritesheetData JSON format
```json
{
"frames": {
"hero.png": {
"frame": { "x": 0, "y": 0, "w": 64, "h": 64 },
"sourceSize": { "w": 64, "h": 64 },
"spriteSourceSize": { "x": 0, "y": 0, "w": 64, "h": 64 },
"anchor": { "x": 0.5, "y": 0.5 },
"borders": { "left": 10, "top": 10, "right": 10, "bottom": 10 }
},
"walk_01.png": {
"frame": { "x": 64, "y": 0, "w": 64, "h": 64 },
"rotated": true,
"trimmed": true,
"sourceSize": { "w": 80, "h": 80 },
"spriteSourceSize": { "x": 8, "y": 8, "w": 64, "h": 64 }
}
},
"animations": {
"walk": ["walk_01.png", "walk_02.png", "walk_03.png"]
},
"meta": {
"image": "spritesheet.png",
"size": { "w": 512, "h": 256 },
"scale": "1"
}
}
```
Key fields:
- `frames` maps frame names to rectangle data, trim info, anchors, and 9-slice borders.
- `rotated` indicates the frame is stored rotated 90 degrees in the atlas. The parser swaps width/height automatically.
- `trimmed` indicates transparent padding was removed. `sourceSize` is the original dimensions; `spriteSourceSize` is the trimmed region within it.
- `animations` maps animation names to ordered arrays of frame names.
- `meta.scale` sets the resolution of the texture source. `"2"` means the atlas is @2x.
- `meta.image` is the atlas image filename, resolved relative to the JSON file.
### Manual Spritesheet creation
```ts
const texture = await Assets.load("atlas.png");
const sheet = new Spritesheet({
texture,
data: spritesheetJsonData,
cachePrefix: "myAtlas_",
});
await sheet.parse();
const frame = new Sprite(sheet.textures["hero.png"]);
```
`parse()` is async for large spritesheets (over 1000 frames); it batches texture creation across multiple frames. For smaller sheets, `parseSync()` is also available.
`cachePrefix` prepends a string to all cached texture names, preventing collisions when multiple atlases share frame names (e.g., `"hero.png"` in two different sheets).
### Preloaded texture with Assets
```ts
const atlasTexture = await Assets.load("images/spritesheet.png");
Assets.add({
alias: "atlas",
src: "images/spritesheet.json",
data: { texture: atlasTexture },
});
const sheet = await Assets.load("atlas");
```
### Multi-pack spritesheets
When `meta.related_multi_packs` is present, the loader automatically loads and links related spritesheets. All linked sheets are accessible via `sheet.linkedSheets`.
### Cleanup
```ts
sheet.destroy();
sheet.destroy(true); // also destroys the base atlas texture
```
## Common Mistakes
### [HIGH] Spritesheet meta.scale behavior change
In v8, `meta.scale` directly sets the texture source resolution. If your atlas was exported at @2x but `meta.scale` says `"1"`, frames render at double the intended size. Ensure `meta.scale` matches the actual resolution of the atlas image. Tools like TexturePacker set this automatically.
### [MEDIUM] Not awaiting spritesheet parse
`parse()` is async. Accessing `sheet.textures` before it resolves returns undefined entries. When loading via `Assets.load()`, parsing is handled automatically.
## API Reference
- [Spritesheet](https://pixijs.download/release/docs/assets.Spritesheet.html.md)
- [spritesheetAsset](https://pixijs.download/release/docs/assets.spritesheetAsset.html.md)
- [AnimatedSprite](https://pixijs.download/release/docs/scene.AnimatedSprite.html.md)
@@ -0,0 +1,132 @@
# SVG Loading
PixiJS loads `.svg` files in one of two modes: rasterized to a texture (fast, fixed resolution) or parsed into a `GraphicsContext` (scalable vector, reusable across `Graphics` instances). Choose texture mode for backgrounds and decorative elements at a fixed size; choose Graphics mode for icons, UI elements, or anything that needs to scale or be modified at runtime.
## Quick Start
```ts
const svgTexture = await Assets.load("icon.svg");
const sprite = new Sprite(svgTexture);
const svgContext = await Assets.load({
src: "icon.svg",
data: { parseAsGraphicsContext: true },
});
const graphic = new Graphics(svgContext);
```
By default, SVG files rasterize to a texture at their native size. Pass `parseAsGraphicsContext: true` in the `data` field to parse as vector geometry instead.
## Core Patterns
### Texture mode (default)
```ts
const icon = await Assets.load("close.svg");
const button = new Sprite(icon);
```
The SVG is rasterized to a bitmap via the browser's native SVG-to-image pipeline, then uploaded as a `Texture`. Rendering is batched just like a regular sprite. Scaling up beyond the rasterized resolution pixelates; the rasterization happens once.
### Graphics mode
```ts
const context = await Assets.load({
src: "logo.svg",
data: { parseAsGraphicsContext: true },
});
const small = new Graphics(context);
small.scale.set(0.5);
const large = new Graphics(context);
large.scale.set(3);
```
The SVG is parsed into a `GraphicsContext` (a compiled list of fill/stroke instructions). Both `Graphics` instances share the same context; cheap, and both stay crisp at any scale.
### Resolution for sharper texture mode
```ts
const icon = await Assets.load({
src: "icon.svg",
data: { resolution: 2 },
});
```
For texture mode, you can pass `resolution` in `data` to rasterize at a higher density. Pairs with `autoGenerateMipmaps` for smooth downscaling. Doesn't apply in Graphics mode.
### Global default
```ts
import { loadSvg } from "pixi.js";
loadSvg.config.parseAsGraphicsContext = true;
```
Flip the default mode globally. Any subsequent `Assets.load('*.svg')` call parses as Graphics unless overridden in the asset's `data` options.
### What Graphics mode parses
Graphics mode reads `<path>` (including `fill-rule="evenodd"` holes), `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>`, `<polyline>`, and `<g>`. Styling comes from the `fill`, `stroke`, `stroke-width`, `fill-opacity`, `stroke-opacity`, and `opacity` attributes or inline `style="..."`. Fills and strokes can reference `<linearGradient>` and `<radialGradient>` definitions through `url(#id)`; `gradientUnits` and percentage coordinates are honored. Not supported: `transform` attributes, `<style>` blocks, `stroke-dasharray`/`stroke-linecap`/`stroke-linejoin`, `gradientTransform`, `spreadMethod`, `stop-opacity`, `<text>`, `<image>`, `<use>`, `<clipPath>`, `<mask>`, `<pattern>`, and filters. Unsupported elements are skipped with a console warning. Texture mode has none of these limits because the browser rasterizes the file.
### When to use which mode
| Mode | Best for | Cost |
| ----------------------------------------- | ------------------------------------------------- | -------------------------------------------------------------- |
| Texture (default) | Icons at a known size, backgrounds, complex SVGs | One-time rasterization; fast per-frame; pixelates when scaled |
| Graphics (`parseAsGraphicsContext: true`) | Scalable icons, UI elements, runtime modification | Higher initial parse cost; crisp at any scale; shared contexts |
If you need the same SVG at multiple sizes, Graphics mode is usually faster because you parse once and scale cheaply. If you have one fixed-size SVG, texture mode is simpler and batches with other sprites.
## Common Mistakes
### [HIGH] Expecting scalability in texture mode
Wrong:
```ts
const icon = await Assets.load("icon.svg");
const sprite = new Sprite(icon);
sprite.scale.set(5); // pixelates
```
Correct (if you need scaling):
```ts
const context = await Assets.load({
src: "icon.svg",
data: { parseAsGraphicsContext: true },
});
const graphic = new Graphics(context);
graphic.scale.set(5); // crisp
```
Or rasterize at higher resolution:
```ts
const icon = await Assets.load({
src: "icon.svg",
data: { resolution: 5 },
});
```
Texture mode is frozen at rasterization time. Use Graphics mode or high `resolution` when the final size isn't known upfront.
### [MEDIUM] External references in SVG files
SVGs that reference external images via `<image href="...">` may fail to load if the reference is cross-origin without CORS headers. Inline the image data as base64 or serve everything from the same origin.
### [MEDIUM] CSS in `<style>` elements
Graphics mode does not read `<style>` blocks or class selectors at all; only presentation attributes and inline `style="..."` are parsed, so class-styled shapes render with the default black fill. Move the styling inline, or use texture mode for full CSS fidelity.
## API Reference
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
- [LoadSVGConfig](https://pixijs.download/release/docs/assets.LoadSVGConfig.html.md)
- [Graphics](https://pixijs.download/release/docs/scene.Graphics.html.md)
- [GraphicsContext](https://pixijs.download/release/docs/scene.GraphicsContext.html.md)
@@ -0,0 +1,158 @@
# Video Textures
PixiJS loads videos through `Assets.load()` and returns a regular `Texture`. Pass the texture to a `Sprite` and it paints the current video frame each render. Use video textures for backgrounds, cutscenes, or any animated surface driven by a video source.
Supported extensions: `.mp4`, `.m4v`, `.webm`, `.ogg`, `.ogv`, `.h264`, `.avi`, `.mov`. Browser support varies; always provide a fallback format.
## Quick Start
```ts
const videoTex = await Assets.load("intro.mp4");
const sprite = new Sprite(videoTex);
app.stage.addChild(sprite);
```
The returned texture wraps a `VideoSource`. The video starts playing automatically unless you set `autoPlay: false` in the `data` options.
## Core Patterns
### Load options via `data`
```ts
const texture = await Assets.load({
src: "city.mp4",
data: {
autoPlay: false,
loop: true,
muted: true,
preload: true,
playsinline: true,
updateFPS: 30,
alphaMode: "premultiply-alpha-on-upload",
},
});
```
`data` accepts `VideoSourceOptions` fields. Defaults come from `VideoSource.defaultOptions`.
| Option | Default | Purpose |
| ------------- | ---------------------- | ---------------------------------------------------------- |
| `autoLoad` | `true` | Start downloading the video as soon as it's assigned |
| `autoPlay` | `true` | Start playing once `canplay` fires |
| `loop` | `false` | Restart at the end |
| `muted` | `true` | Required for autoplay on most browsers |
| `playsinline` | `true` | Prevents iOS fullscreen takeover |
| `preload` | `false` | Await `canplaythrough` before resolving |
| `updateFPS` | `0` | Texture update rate. `0` updates every render frame |
| `crossorigin` | `true` | CORS mode for cross-origin URLs |
| `alphaMode` | auto-detected | `'no-premultiply-alpha'` for straight alpha |
| `mime` | derived from extension | Force a specific MIME type when the URL lacks an extension |
### Format fallback
```ts
Assets.add({
alias: "clip",
src: "clip.{webm,mp4}",
});
const texture = await Assets.load("clip");
```
List multiple formats so the resolver picks the first one the browser supports. WebM and MP4 together cover all current browsers.
### Mobile autoplay
```ts
const texture = await Assets.load({
src: "ad.mp4",
data: {
muted: true,
playsinline: true,
autoPlay: true,
},
});
```
iOS and mobile Chrome only autoplay muted, inline video. Set both `muted: true` and `playsinline: true` or playback stalls on the first frame until the user taps.
### Manual playback control
```ts
const texture = await Assets.load({
src: "boss-fight.mp4",
data: { autoPlay: false, preload: true },
});
const videoSource = texture.source as VideoSource;
startButton.on("pointertap", () => {
videoSource.resource.play();
});
```
With `autoPlay: false`, grab the underlying `VideoSource` from `texture.source` and call `.play()`, `.pause()`, or `.currentTime =` on its `resource` (the `HTMLVideoElement`). Pair with `preload: true` to guarantee the first frame is uploaded before you call `play()`.
### Updating at a fixed rate
```ts
await Assets.load({
src: "background.mp4",
data: { updateFPS: 15 },
});
```
`updateFPS` caps how often the GPU texture re-uploads from the video element. `0` re-uploads every render tick (smoothest; highest cost). `15` caps it to 15 uploads per second, which saves bandwidth on static-ish video backgrounds.
## Forcing the video parser
If your video URL lacks an extension (e.g., a CDN signed URL or a blob), the loader can't pick a parser by test. Force it with the top-level `parser` field:
```ts
const texture = await Assets.load({
src: "https://cdn.example.com/stream/abc123",
parser: "video",
data: { mime: "video/mp4" },
});
```
See the main `SKILL.md` section on "Forcing a parser with `parser`" for the full list of parser IDs.
## Common Mistakes
### [HIGH] Autoplay without mute on mobile
Wrong:
```ts
await Assets.load({ src: "ad.mp4", data: { autoPlay: true } });
```
Correct:
```ts
await Assets.load({
src: "ad.mp4",
data: { autoPlay: true, muted: true, playsinline: true },
});
```
Mobile browsers block autoplay with sound. The promise resolves, but the video stays frozen on frame 0 until the user interacts.
### [MEDIUM] Expecting sprite.texture to update itself
The `Sprite` reflects the current video frame automatically because `VideoSource` re-uploads on every render. You don't need to call `update()` yourself. If playback looks frozen, check that the underlying video element is actually playing (`videoSource.resource.paused` should be `false`).
### [MEDIUM] Missing CORS for cross-origin video
Video served from another origin without `Access-Control-Allow-Origin` headers taints the canvas and most WebGL operations (`readPixels`, snapshots) fail silently. Either serve with CORS headers or pass `data: { crossorigin: false }` and accept that the texture can't be extracted.
## API Reference
- [VideoSource](https://pixijs.download/release/docs/rendering.VideoSource.html.md)
- [VideoSourceOptions](https://pixijs.download/release/docs/rendering.VideoSourceOptions.html.md)
- [loadVideoTextures](https://pixijs.download/release/docs/assets.loadVideoTextures.html.md)
- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md)
+215
View File
@@ -0,0 +1,215 @@
---
name: pixijs-blend-modes
description: "Use this skill when compositing display objects with blend modes in PixiJS v8. Covers standard modes (normal, add, multiply, screen, erase, min, max), advanced modes via pixi.js/advanced-blend-modes (color-burn, overlay, hard-light, etc.), batch-friendly ordering. Triggers on: blendMode, additive, multiply, screen, overlay, color-burn, color-dodge, advanced-blend-modes, glow, erase."
license: MIT
---
Set `container.blendMode` to composite display objects with GPU blend equations (standard modes) or filter-based advanced modes. Blend-mode transitions break render batches, so group like-mode siblings together.
## Quick Start
```ts
const light = new Sprite(await Assets.load("light.png"));
light.blendMode = "add";
app.stage.addChild(light);
const shadow = new Sprite(await Assets.load("shadow.png"));
shadow.blendMode = "multiply";
app.stage.addChild(shadow);
import "pixi.js/advanced-blend-modes";
const overlay = new Sprite(await Assets.load("overlay.png"));
overlay.blendMode = "color-burn";
app.stage.addChild(overlay);
```
**Related skills:** `pixijs-filters` (advanced modes use the filter pipeline), `pixijs-performance` (batching with blend modes), `pixijs-color` (color manipulation).
## Core Patterns
### Standard blend modes
Standard modes are built in and use GPU blend equations directly:
```ts
import { Sprite } from "pixi.js";
sprite.blendMode = "normal"; // standard alpha compositing (effective default at root)
sprite.blendMode = "add"; // additive (lighten, glow effects)
sprite.blendMode = "multiply"; // multiply (darken, shadow effects)
sprite.blendMode = "screen"; // screen (lighten, dodge effects)
sprite.blendMode = "erase"; // erase pixels from render target
sprite.blendMode = "none"; // no blending, overwrites destination
sprite.blendMode = "inherit"; // inherit from parent (this is the actual default value)
sprite.blendMode = "min"; // keeps minimum of source and destination (WebGL2+ only)
sprite.blendMode = "max"; // keeps maximum of source and destination (WebGL2+ only)
```
These are hardware-accelerated and cheap. They do not require filters.
### Advanced blend modes
Advanced modes require an explicit import to register the extensions. On the WebGL renderer they also require `useBackBuffer: true` at init time, or PixiJS logs a warning and the blend silently falls back:
```ts
import "pixi.js/advanced-blend-modes";
import { Application, Sprite, Assets } from "pixi.js";
const app = new Application();
await app.init({ useBackBuffer: true }); // required for advanced modes on WebGL
const texture = await Assets.load("overlay.png");
const overlay = new Sprite(texture);
overlay.blendMode = "color-burn";
```
Available advanced modes:
| Mode | Effect |
| -------------- | ----------------------------------------------- |
| `color-burn` | Darkens by increasing contrast |
| `color-dodge` | Brightens by decreasing contrast |
| `darken` | Keeps darker of two layers |
| `difference` | Absolute difference |
| `divide` | Divides bottom by top |
| `exclusion` | Similar to difference, lower contrast |
| `hard-light` | Multiply or screen based on top layer |
| `hard-mix` | High contrast threshold blend |
| `lighten` | Keeps lighter of two layers |
| `linear-burn` | Adds and subtracts to darken |
| `linear-dodge` | Adds layers together |
| `linear-light` | Linear burn or dodge based on top layer |
| `luminosity` | Luminosity of top, hue/saturation of bottom |
| `negation` | Inverted difference |
| `overlay` | Multiply or screen based on bottom layer |
| `pin-light` | Replaces based on lightness comparison |
| `saturation` | Saturation of top, hue/luminosity of bottom |
| `soft-light` | Gentle overlay effect |
| `subtract` | Subtracts top from bottom |
| `vivid-light` | Color burn or dodge based on top layer |
| `color` | Hue and saturation of top, luminosity of bottom |
You set advanced blend modes the same way as standard ones, via the `blendMode` property. They use filters internally, so they cost more than standard modes.
### Batch-friendly ordering
Different blend modes break the rendering batch. Order objects to minimize transitions:
```ts
import { Container, Sprite } from "pixi.js";
const scene = new Container();
scene.addChild(screenSprite1); // 'screen'
scene.addChild(screenSprite2); // 'screen'
scene.addChild(normalSprite1); // 'normal'
scene.addChild(normalSprite2); // 'normal'
```
2 draw calls. Alternating order (`screen, normal, screen, normal`) would produce 4.
## Common Mistakes
### [HIGH] Not importing advanced-blend-modes extension
Wrong:
```ts
import { Sprite } from "pixi.js";
sprite.blendMode = "color-burn"; // silently falls back to normal
```
Correct:
```ts
import "pixi.js/advanced-blend-modes";
import { Sprite } from "pixi.js";
sprite.blendMode = "color-burn";
```
Advanced blend modes (color-burn, overlay, etc.) require the extension import. Without it, only standard modes (normal, add, multiply, screen) are available. The invalid mode silently falls back.
### [MEDIUM] Mixing blend modes across adjacent objects
Different blend modes break the render batch. `screen / normal / screen / normal` produces 4 draw calls, while `screen / screen / normal / normal` produces 2. Sort children so objects with the same blend mode are adjacent.
### [HIGH] Using the v7 BLEND_MODES enum
Wrong:
```ts
import { BLEND_MODES } from "pixi.js";
sprite.blendMode = BLEND_MODES.ADD; // runtime error: BLEND_MODES is undefined
```
Correct:
```ts
sprite.blendMode = "add";
```
In v8, `BLEND_MODES` is a TypeScript type only (a union of string literals). There is no runtime enum export, so `BLEND_MODES.ADD` evaluates to accessing a property on `undefined`. Use the string form.
### [HIGH] Advanced blend modes without useBackBuffer
Wrong:
```ts
import "pixi.js/advanced-blend-modes";
await app.init({
/* no useBackBuffer */
});
sprite.blendMode = "color-burn"; // logs a warning, falls back
```
Correct:
```ts
import "pixi.js/advanced-blend-modes";
await app.init({ useBackBuffer: true });
sprite.blendMode = "color-burn";
```
Advanced modes read from the back buffer. On WebGL, the blend silently falls back if the back buffer is not enabled. WebGPU enables the back buffer unconditionally.
### [MEDIUM] Advanced blend modes clipped or scaled on high-DPI renderers
Advanced blend modes are filter-based and use `Filter.defaultOptions`, whose resolution defaults to `1`. On a high-DPI render target the blended object can look clipped, scaled, or only partially applied.
Wrong:
```ts
import "pixi.js/advanced-blend-modes";
sprite.blendMode = "overlay"; // renders at resolution 1, can clip on retina
```
Correct:
```ts
import { Filter } from "pixi.js";
import "pixi.js/advanced-blend-modes";
Filter.defaultOptions.resolution = "inherit"; // set before creating affected objects
sprite.blendMode = "overlay";
```
Setting `Filter.defaultOptions.resolution = "inherit"` makes advanced blend modes render at the render target's resolution. This costs more memory and runtime, so apply it where fidelity matters.
## API Reference
- [Container.blendMode](https://pixijs.download/release/docs/scene.Container.html.md)
- [OverlayBlend](https://pixijs.download/release/docs/filters.OverlayBlend.html.md)
- [ColorBurnBlend](https://pixijs.download/release/docs/filters.ColorBurnBlend.html.md)
- [ColorDodgeBlend](https://pixijs.download/release/docs/filters.ColorDodgeBlend.html.md)
- [HardLightBlend](https://pixijs.download/release/docs/filters.HardLightBlend.html.md)
- [SoftLightBlend](https://pixijs.download/release/docs/filters.SoftLightBlend.html.md)
- [DifferenceBlend](https://pixijs.download/release/docs/filters.DifferenceBlend.html.md)
+299
View File
@@ -0,0 +1,299 @@
---
name: pixijs-color
description: "Use this skill when creating, converting, or manipulating colors in PixiJS v8. Covers Color class input formats (hex, CSS names, RGB/HSL objects, arrays, Uint8Array), conversion methods (toHex, toNumber, toArray, toRgba), component access, setAlpha/multiply/premultiply, Color.shared singleton. Triggers on: Color, ColorSource, hex, rgb, hsl, tint, premultiply, Color.shared, color conversion."
license: MIT
---
The `Color` class creates and converts colors for tints, fills, strokes, and anywhere PixiJS accepts a `ColorSource`. Most APIs accept raw hex/strings directly, so explicit `new Color(...)` is only needed when converting formats or manipulating values.
## Quick Start
```ts
const fillColor = new Color("#ff6600");
console.log(fillColor.toHex()); // '#ff6600'
console.log(fillColor.toNumber()); // 0xff6600
console.log(fillColor.toArray()); // [1, 0.4, 0, 1]
const g = new Graphics().rect(0, 0, 200, 100).fill(fillColor);
app.stage.addChild(g);
const sprite = Sprite.from("hero.png");
sprite.tint = "dodgerblue";
app.stage.addChild(sprite);
const t = Color.shared.setValue(0xffffff).multiply([1, 0.5, 0.5]).toNumber();
sprite.tint = t;
```
**Related skills:** `pixijs-scene-graphics` (fill/stroke colors), `pixijs-scene-sprite` (tint), `pixijs-blend-modes` (compositing).
## Core Patterns
### Accepted input formats
```ts
import { Color } from "pixi.js";
// Hex integer
new Color(0xff0000);
// Hex strings
new Color("#ff0000");
new Color("#f00");
new Color("ff0000");
// CSS color names
new Color("red");
new Color("dodgerblue");
// RGB/RGBA objects (components 0-255)
new Color({ r: 255, g: 0, b: 0 });
new Color({ r: 255, g: 0, b: 0, a: 0.5 });
// HSL/HSLA objects
new Color({ h: 0, s: 100, l: 50 });
new Color({ h: 0, s: 100, l: 50, a: 0.5 });
// HSV/HSVA objects
new Color({ h: 0, s: 100, v: 100 });
// CSS strings
new Color("rgb(255, 0, 0)");
new Color("rgba(255, 0, 0, 0.5)");
new Color("hsl(0, 100%, 50%)");
// Normalized 0-1 arrays (Float32Array or plain arrays)
new Color([1, 0, 0]); // RGB
new Color([1, 0, 0, 0.5]); // RGBA
// Uint8 arrays (components 0-255)
new Color(new Uint8Array([255, 0, 0]));
new Color(new Uint8ClampedArray([255, 0, 0, 128]));
// 8-digit hex with alpha
new Color("#ff0000ff");
new Color("#f00f");
// Copy from another Color instance
const red = new Color("red");
const copy = new Color(red);
```
### Conversion methods
```ts
import { Color } from "pixi.js";
const color = new Color("#ff6600");
color.toHex(); // '#ff6600'
color.toHexa(); // '#ff6600ff' (hex with alpha)
color.toNumber(); // 0xff6600
color.toArray(); // [1, 0.4, 0, 1] (normalized RGBA)
color.toRgbArray(); // [1, 0.4, 0] (normalized RGB, no alpha)
color.toRgbaString(); // 'rgba(255,102,0,1)'
color.toRgba(); // { r: 1, g: 0.4, b: 0, a: 1 }
color.toRgb(); // { r: 1, g: 0.4, b: 0 }
color.toUint8RgbArray(); // [255, 102, 0]
// setValue() is the chainable way to change a color's value
color.setValue(0xff0000).toHex(); // '#ff0000'
```
### Component access
```ts
import { Color } from "pixi.js";
const color = new Color("rgba(255, 128, 0, 0.8)");
color.red; // 1
color.green; // ~0.502
color.blue; // 0
color.alpha; // 0.8
```
All component getters return normalized 0-1 values.
### Manipulation
```ts
import { Color } from "pixi.js";
const color = new Color("red");
// Set alpha (chainable)
color.setAlpha(0.5);
// Multiply with another color (destructive, modifies in place)
color.multiply(0x808080);
// Premultiply alpha (destructive, RGB channels multiplied by alpha)
color.premultiply(0.8);
// Premultiply alpha only (RGB unchanged)
color.premultiply(0.8, false);
// Chain operations
new Color("white").setAlpha(0.5).multiply([0.8, 0.2, 0.2]);
```
`multiply()` and `premultiply()` are destructive; they modify the color and set `value` to null (original format is lost).
### Non-destructive premultiplied output
```ts
import { Color } from "pixi.js";
const color = new Color("red").setAlpha(0.5);
const packed = color.toPremultiplied(color.alpha); // 0x7F7F0000
const alphaOnly = color.toPremultiplied(color.alpha, false); // 0x7FFF0000
```
`toPremultiplied(alpha, applyToRGB?)` returns a 32-bit `0xAARRGGBB` integer without mutating `this`. Use it in batchers and tint math where the source color must be reused. When `applyToRGB` is `false`, only the alpha byte is packed; the RGB stays at its full value.
### Reusing output buffers
```ts
import { Color } from "pixi.js";
const rgba = new Float32Array(4);
const rgb = new Float32Array(3);
const rgb8 = new Uint8Array(3);
app.ticker.add(() => {
Color.shared.setValue(sprite.tint).toArray(rgba).toRgbArray(rgb);
Color.shared.toUint8RgbArray(rgb8);
});
```
`toArray(out?)`, `toRgbArray(out?)`, and `toUint8RgbArray(out?)` accept a reusable `number[]`, `Float32Array`, `Uint8Array`, or `Uint8ClampedArray` and write into it. Pass your own buffer in hot paths to avoid allocating per frame; omit the argument and the `Color` instance returns its internal cache array.
### Packing for GPU buffers
| Method | Returns |
| ------------------------ | ------------------------------------------------------------ |
| `toBgrNumber()` | 24-bit `0xBBGGRR` integer with R/B swapped |
| `toLittleEndianNumber()` | Same 24-bit swap, convenient for little-endian vertex writes |
Both are cheap and useful when emitting colors straight into packed vertex attributes.
### Color.shared for temporary operations
```ts
import { Color } from "pixi.js";
// One-off conversion without allocating a new Color
const hex = Color.shared.setValue("#ff6600").toNumber();
const arr = Color.shared.setValue(0xff0000).toArray();
```
`Color.shared` is a singleton that avoids allocating a new `Color` on every call. This matters in hot paths like render loops or per-frame tint calculations where repeated `new Color()` creates GC pressure. Do not store references to it; other code may mutate it.
```ts
import { Color } from "pixi.js";
// Good: reuse shared instance in a per-frame callback
app.ticker.add(() => {
const t = performance.now() / 1000;
sprite.tint = Color.shared
.setValue("white")
.multiply([Math.sin(t) * 0.5 + 0.5, 0.2, 0.8])
.toNumber();
});
```
### Validating input
```ts
import { Color } from "pixi.js";
Color.isColorLike("red"); // true
Color.isColorLike("#ff0000"); // true
Color.isColorLike(0xff0000); // true
Color.isColorLike([1, 0, 0]); // true
Color.isColorLike({ r: 1, g: 0, b: 0 }); // true
Color.isColorLike({ foo: 1 }); // false
Color.isColorLike(null); // false
```
`Color.isColorLike()` checks the structural shape (string, number, array, or recognized object). It doesn't validate that a string is a real CSS color name, nor that array values fall in range. Use it as a type guard before passing user input to `new Color()` or `setValue()`.
## Common Mistakes
### [MEDIUM] Expecting toRgba() to return 0-255 values
Wrong:
```ts
import { Color } from "pixi.js";
const { r, g, b } = new Color({ r: 255, g: 128, b: 0 }).toRgba();
// r = 1, g = ~0.502, b = 0 (NOT 255, 128, 0)
```
Correct:
```ts
import { Color } from "pixi.js";
// Use toUint8RgbArray() for 0-255 output
const [r, g, b] = new Color({ r: 255, g: 128, b: 0 }).toUint8RgbArray();
// r = 255, g = 128, b = 0
```
RGB object _inputs_ use 0-255 range (`{ r: 255, g: 0, b: 0 }`), but all output methods (`toRgba()`, `toRgb()`, `toArray()`, `toRgbArray()`) normalize to 0-1. Use `toUint8RgbArray()` when you need 0-255 integers for CSS or external APIs.
### [MEDIUM] Using 0-255 range in color arrays
Wrong:
```ts
import { Color } from "pixi.js";
new Color([255, 0, 0]); // NOT red; values are interpreted as 0-1
```
Correct:
```ts
import { Color } from "pixi.js";
new Color([1, 0, 0]); // red via normalized array
new Color(0xff0000); // red via hex
new Color("red"); // red via CSS name
new Color(new Uint8Array([255, 0, 0])); // red via Uint8Array (0-255)
```
Plain number arrays (`number[]` and `Float32Array`) use normalized 0-1 range. `[255, 0, 0]` clamps to `[1, 0, 0]` because values are clamped, but `[200, 100, 50]` does not produce the expected color. Use `Uint8Array` or `Uint8ClampedArray` for 0-255 input.
### [MEDIUM] Using utils.string2hex or utils.hex2string
Wrong:
```ts
import { utils } from "pixi.js";
const hex = utils.string2hex("#ff0000");
```
Correct:
```ts
import { Color } from "pixi.js";
const hex = new Color("#ff0000").toNumber();
const str = new Color(0xff0000).toHex();
```
The `utils` namespace was removed in v8. Use the `Color` class for all color conversions.
## API Reference
- [Color](https://pixijs.download/release/docs/color.Color.html.md)
- [ColorSource](https://pixijs.download/release/docs/color.ColorSource.html.md)
@@ -0,0 +1,132 @@
---
name: pixijs-core-concepts
description: "Use this skill when understanding how PixiJS v8 renders frames: the systems-and-pipes renderer, the render loop, and how the library adapts to different environments. Covers WebGLRenderer/WebGPURenderer/CanvasRenderer selection, renderer.render() pipeline, environment detection, rendering into RenderTextures and RenderTargets (flipY, mipLevel, layer, bind/push/pop, copyDepthTexture), WebGL context loss and WebGPU device loss recovery, and pointers to per-topic deep dives. Triggers on: renderer, WebGL, WebGPU, Canvas, render loop, render pipeline, systems, environments, autoDetectRenderer, RenderTexture, RenderTarget, render to texture, flipY, mipLevel, layer, 3D texture, depth slice, renderTarget.bind, copyToTexture, copyDepthTexture, depth-only, WebGLLoader, WebGPULoader, CanvasLoader, RendererLoader, lazy-load renderer systems, code splitting, context lost, webglcontextlost, device lost, GPUDevice.lost."
license: MIT
---
Foundational model for how PixiJS v8 gets pixels on the screen: the renderer decides which GPU backend to use, the render loop drives per-frame work, and the environment layer adapts the library to browser, Web Worker, or SSR contexts. For the scene graph itself (Containers, transforms, destroy), see `pixijs-scene-core-concepts`.
## Quick Start
```ts
console.log(app.renderer.name); // 'webgl' | 'webgpu' | 'canvas'
app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
});
const tex = app.renderer.extract.texture({ target: app.stage });
app.renderer.render({ container: app.stage });
```
`app.renderer` is the `WebGLRenderer`, `WebGPURenderer`, or `CanvasRenderer` chosen by `autoDetectRenderer`. The TickerPlugin drives `renderer.render()` automatically; call it manually only with `autoStart: false`. Backend selection happens in `Application.init({ preference })`; see `pixijs-application` for setup.
**Related skills:** `pixijs-application` (Application construction and lifecycle), `pixijs-ticker` (per-frame logic, priorities, FPS capping), `pixijs-environments` (Web Worker, SSR, strict CSP), `pixijs-custom-rendering` (writing a RenderPipe), `pixijs-scene-core-concepts` (scene graph basics).
## Topics
| Topic | Reference | When |
| ------------------- | ------------------------------------------------------ | --------------------------------------------------------- |
| Choosing a backend | [references/renderers.md](references/renderers.md) | Preference forms, per-renderer options, systems and pipes |
| Per-frame execution | [references/render-loop.md](references/render-loop.md) | Priority order, time units, manual rendering |
For deep dives into any single topic, open the corresponding reference file. Non-browser targets (`DOMAdapter`, `WebWorkerAdapter`, custom adapters, strict CSP) are covered in the `pixijs-environments` skill.
## Decision guide
- **Setting up an Application?** Start with `pixijs-application`. This skill explains what the renderer does under the hood.
- **Choosing between WebGL and WebGPU?** Use `['webgpu', 'webgl']` as your preference array. WebGPU is fastest where available; WebGL is the reliable fallback. See `references/renderers.md`.
- **Running in a Web Worker?** Set `DOMAdapter.set(WebWorkerAdapter)` before `app.init`. See the `pixijs-environments` skill for complete setup.
- **Need manual control over when rendering happens?** Set `autoStart: false` and call `app.renderer.render(app.stage)` from your own loop. See `references/render-loop.md`.
- **Integrating with a physics library?** Add your update at `UPDATE_PRIORITY.HIGH` so physics runs before the render at `LOW`. See `references/render-loop.md`.
- **Writing a custom renderable?** Implement a `RenderPipe`. See `pixijs-custom-rendering` skill.
- **Rendering into a texture or a custom render target?** Pass `target` to `renderer.render()`, or build a `RenderTarget` with explicit color and depth attachments. See `references/renderers.md`.
- **Running under strict CSP?** Import `'pixi.js/unsafe-eval'`. See the `pixijs-environments` skill.
## Quick concepts
### Renderer = systems + pipes
Each renderer is composed of `Systems` (lifecycle services: textures, buffers, state, filters, masks) and `RenderPipes` (per-renderable instruction builders: sprite, graphics, mesh, particle, text, tiling). Writing a custom renderable means implementing a `RenderPipe` and registering it via extensions. Backend-specific systems and pipes can be dynamic-imported through a renderer loader extension (`WebGLLoader`, `WebGPULoader`, `CanvasLoader`); see `references/renderers.md`.
### The render loop
`app.ticker.add(fn)` registers a callback that runs every frame. The `TickerPlugin` registers `app.render()` at `UPDATE_PRIORITY.LOW`, so ticker callbacks at `NORMAL` or `HIGH` run before the draw. Disable the plugin with `autoStart: false` for manual control.
### Environments
`DOMAdapter` abstracts every DOM call PixiJS makes (canvas creation, image loading, fetch, XML parsing). Swap with `DOMAdapter.set(WebWorkerAdapter)` for Workers or implement a custom `Adapter` for Node/SSR. Must be done before `Application.init`.
## Common Mistakes
### [HIGH] Accessing app.renderer before init() resolves
Wrong:
```ts
const app = new Application();
app.init({ width: 800, height: 600 });
console.log(app.renderer.name); // undefined — init() is async
```
Correct:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
console.log(app.renderer.name); // 'webgl' | 'webgpu' | 'canvas'
```
`Application.init()` is async. `app.renderer`, `app.canvas`, and `app.screen` do not exist until after the promise resolves.
### [HIGH] Setting DOMAdapter after Application.init
Wrong:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
DOMAdapter.set(WebWorkerAdapter); // too late — init already allocated resources
```
Correct:
```ts
DOMAdapter.set(WebWorkerAdapter);
const app = new Application();
await app.init({ width: 800, height: 600 });
```
The adapter abstracts DOM calls the renderer makes during construction (canvas creation, image loading, fetch). Swap it before `init()` or the wrong adapter is baked into the renderer.
### [MEDIUM] Treating `preference` as a guarantee
Wrong:
```ts
await app.init({ preference: "webgpu" });
// assume WebGPU is active
useWebGPUOnlyFeature(app.renderer);
```
Correct:
```ts
await app.init({ preference: "webgpu" });
if (app.renderer.name === "webgpu") {
useWebGPUOnlyFeature(app.renderer);
}
```
`preference` is a hint, not a demand. If the browser lacks WebGPU support, PixiJS falls back to WebGL (or Canvas). Always branch on `renderer.name` for backend-specific code.
## API Reference
- [autoDetectRenderer](https://pixijs.download/release/docs/rendering.autoDetectRenderer.html.md)
- [AbstractRenderer](https://pixijs.download/release/docs/rendering.AbstractRenderer.html.md)
- [WebGLRenderer](https://pixijs.download/release/docs/rendering.WebGLRenderer.html.md)
- [WebGPURenderer](https://pixijs.download/release/docs/rendering.WebGPURenderer.html.md)
- [CanvasRenderer](https://pixijs.download/release/docs/rendering.CanvasRenderer.html.md)
- [Application](https://pixijs.download/release/docs/app.Application.html.md)
- [DOMAdapter](https://pixijs.download/release/docs/environment.DOMAdapter.html.md)
@@ -0,0 +1,216 @@
# Render Loop
Every PixiJS frame runs a fixed sequence of ticker callbacks in priority order, with `app.render()` registered at `UPDATE_PRIORITY.LOW` — scene graph update and GPU draw happen _inside_ that one callback. The `Application`'s `TickerPlugin` drives this loop automatically. Understanding the priority order and when to render yourself is key for integrating game logic, physics, and custom frame pacing.
## Frame lifecycle
Each frame, the `Ticker` measures elapsed time, clamps it with `minFPS`/`maxFPS`, then calls every listener registered with `ticker.add()` in priority order. `app.render()` is itself one of those listeners, registered at `UPDATE_PRIORITY.LOW`. When it runs, it walks the display list from `app.stage`, recalculates world transforms (position/rotation/scale propagated parent-to-child), fires each object's `onRender` hook, culls off-screen objects if culling is enabled, then batches draw calls and issues GPU commands.
```
requestAnimationFrame
│
[Ticker._tick()]
│
├─ Compute elapsed time (minFPS/maxFPS clamp)
└─ Call listeners in priority order
├─ INTERACTION / HIGH / NORMAL listeners
├─ LOW: app.render()
│ ├─ Traverse display list
│ ├─ Update world transforms
│ │ └─ object.onRender() (per-object during traversal)
│ ├─ Cull display objects (if enabled)
│ ├─ Upload data to GPU
│ └─ Draw
└─ UTILITY listeners (post-render)
```
Rendering is **retained mode**: objects persist across frames unless you explicitly remove them.
## Quick Start
```ts
app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
});
app.ticker.add(
(ticker) => {
updatePhysics(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
```
Callbacks receive a `Ticker` instance. Use `ticker.deltaTime` (dimensionless, ~1.0 at 60fps) for simple multipliers; use `ticker.deltaMS` (milliseconds) for time-based calculations.
## Core Patterns
### Priority order
The ticker runs registered callbacks in descending priority. The `TickerPlugin` registers `app.render()` at `UPDATE_PRIORITY.LOW`, so callbacks at `NORMAL`, `HIGH`, or `INTERACTION` run before the render.
```
UPDATE_PRIORITY.INTERACTION = 50 // pointer events
UPDATE_PRIORITY.HIGH = 25 // physics, input sampling
UPDATE_PRIORITY.NORMAL = 0 // gameplay (default)
UPDATE_PRIORITY.LOW = -25 // app.render() registered here
UPDATE_PRIORITY.UTILITY = -50 // post-render cleanup
```
```ts
import { UPDATE_PRIORITY } from "pixi.js";
app.ticker.add(
(ticker) => {
handleInput(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
app.ticker.add((ticker) => {
updateAnimations(ticker.deltaTime);
});
```
### Time units
| Property | Type | Scaled by speed? | Capped by minFPS? |
| ----------- | ----------------------------- | ---------------- | ----------------- |
| `deltaTime` | dimensionless (~1.0 at 60fps) | yes | yes |
| `deltaMS` | milliseconds | yes | yes |
| `elapsedMS` | milliseconds | no | no |
Use `deltaTime` as a frame-rate multiplier for simple per-frame logic; use `deltaMS` for pixels-per-second or other time-based math; use `elapsedMS` only for profiling (raw, uncapped, unscaled).
### Manual rendering
```ts
await app.init({ autoStart: false, width: 800, height: 600 });
function frame(time: number) {
updateGameState();
app.renderer.render(app.stage);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
`autoStart: false` disables the `TickerPlugin`'s automatic render registration. You control when the scene draws, letting you integrate with a custom loop, an external animation library, or a fixed-timestep game clock.
### Stop and start
```ts
app.stop(); // pause the ticker and rendering
app.start(); // resume
```
Useful for a pause menu or when the user switches away from the tab. The ticker is automatically paused on page blur when `sharedTicker: false` (default).
### Per-object update via `onRender`
```ts
const sprite = new Sprite(texture);
sprite.onRender = () => {
sprite.rotation += 0.01;
};
app.stage.addChild(sprite);
```
`onRender` is called during scene graph traversal, just before the object is drawn. It's a per-object hook; an alternative to a global ticker callback when the logic is tied to a specific display object.
### Frame rate capping
```ts
app.ticker.maxFPS = 30; // run at 30fps
app.ticker.minFPS = 10; // cap deltaTime at 10fps worth if frames drop
```
`maxFPS` enforces a ceiling by skipping updates. `minFPS` caps `deltaTime` so large frame drops don't produce enormous deltas that break physics. Defaults: no `maxFPS`, `minFPS: 10`.
## Common Mistakes
### [CRITICAL] Treating the ticker callback arg as a number
Wrong:
```ts
app.ticker.add((dt) => {
sprite.rotation += dt; // dt is the Ticker instance, not a number
});
```
Correct:
```ts
app.ticker.add((ticker) => {
sprite.rotation += ticker.deltaTime;
});
```
v8 passes the `Ticker` instance to the callback, not a delta. Old v7 code that used `(dt) => sprite.x += dt` compiles but produces `NaN` because `dt` is an object.
### [HIGH] Using `updateTransform` for per-frame logic
Wrong:
```ts
class MySprite extends Sprite {
updateTransform() {
super.updateTransform();
this.rotation += 0.01;
}
}
```
Correct:
```ts
class MySprite extends Sprite {
constructor() {
super();
this.onRender = () => {
this.rotation += 0.01;
};
}
}
```
`updateTransform` was removed in v8. Use `onRender` for per-object per-frame logic.
### [MEDIUM] Assuming ticker callbacks run after render
Wrong:
```ts
app.ticker.add(() => {
readPixelsFromCanvas(); // empty; render hasn't happened yet this frame
});
```
Correct:
```ts
app.ticker.add(
() => {
readPixelsFromCanvas();
},
undefined,
UPDATE_PRIORITY.UTILITY,
);
```
Callbacks added at the default priority (`NORMAL = 0`) run _before_ the render call (at `LOW = -25`). Use `UTILITY = -50` for post-render work like pixel readbacks or DOM sync.
## API Reference
- [Ticker](https://pixijs.download/release/docs/ticker.Ticker.html.md)
- [TickerPlugin](https://pixijs.download/release/docs/app.TickerPlugin.html.md)
- [UPDATE_PRIORITY](https://pixijs.download/release/docs/ticker.UPDATE_PRIORITY.html.md)
- [Application](https://pixijs.download/release/docs/app.Application.html.md)
@@ -0,0 +1,287 @@
# Renderers: WebGPU, WebGL, and Canvas
PixiJS v8 ships three renderers: `WebGPURenderer` (fastest where available), `WebGLRenderer` (broad compatibility, WebGL2), and `CanvasRenderer` (a last-resort 2D Canvas backend). `autoDetectRenderer` (used internally by `Application.init`) picks the best available backend based on a preference list.
**Status:** `WebGLRenderer` is recommended for production. `WebGPURenderer` is feature-complete but still experimental; browser implementations have inconsistencies. `CanvasRenderer` is a fallback for environments without WebGL/WebGPU and supports a reduced feature set.
## Quick Start
```ts
const app = new Application();
await app.init({
preference: ["webgpu", "webgl"],
width: 800,
height: 600,
background: 0x222233,
antialias: true,
});
document.body.appendChild(app.canvas);
```
`preference` can be a single string (try that first, fall back to default order) or an array (use only these, in this order; others are excluded). Default priority when `preference` is not set: `webgl`, `webgpu`, `canvas`.
## Core Patterns
### Preference forms
```ts
// Single string: try webgpu first, fall back through defaults
await app.init({ preference: "webgpu" });
// Array: only try listed backends in order
await app.init({ preference: ["webgpu", "webgl"] });
// Array acts as a blocklist; anything not listed is excluded
await app.init({ preference: ["webgl"] }); // never uses webgpu or canvas
// Force canvas (legacy-only environments)
await app.init({ preference: ["canvas"] });
```
A string form falls through to defaults if the preferred backend isn't available. An array form excludes any backend not in the list, even if the preferred one fails.
### Per-renderer options
```ts
await app.init({
width: 800,
height: 600,
webgpu: { antialias: true, powerPreference: "high-performance" },
webgl: { antialias: true, premultipliedAlpha: false },
canvasOptions: { backgroundAlpha: 0 },
});
```
Common options live at the top level; renderer-specific options go in `webgpu`, `webgl`, or `canvasOptions`. Only the options for the selected renderer apply; the others are discarded.
### Systems and pipes
Each renderer is composed of a fixed set of `System`s (lifecycle services: textures, buffers, state, events, filters, masks) and a set of `RenderPipe`s (per-renderable instruction builders: sprite, graphics, mesh, particle, text, tiling-sprite).
- `Systems` run once per renderer lifecycle and manage GPU state.
- `RenderPipes` run every frame, one per renderable type. They batch instructions for their object class and flush them to the GPU.
Writing a custom renderable means implementing a `RenderPipe`, a `BatchableX` class, and registering both via the extensions system. See `pixijs-custom-rendering`.
### Lazy-loading backend-specific systems and pipes
Systems and pipes that only one backend needs can stay out of the main bundle. Register a renderer loader (`ExtensionType.WebGLLoader`, `ExtensionType.WebGPULoader`, or `ExtensionType.CanvasLoader`) whose `load()` dynamic-imports the module that registers them. During `init`, the renderer awaits every loader for its own backend after the environment extensions load and before it creates its systems and pipes; loaders for other backends never run.
```ts
import { extensions, ExtensionType } from "pixi.js";
extensions.add({
extension: { type: ExtensionType.WebGLLoader, name: "my-plugin" },
load: () => import("./gl/register"), // registers WebGL systems and pipes on import
});
```
Loader names are unique per backend; a second loader with the same name is ignored. Loaders run concurrently; registered systems and pipes are ordered by their own `priority`, not by loader completion. `skipExtensionImports: true` skips loaders too, so custom builds import backend modules directly.
### Direct renderer construction
```ts
import { WebGLRenderer } from "pixi.js";
const renderer = new WebGLRenderer();
await renderer.init({ width: 800, height: 600 });
```
Most apps use `Application.init` or `autoDetectRenderer()`, but you can instantiate a specific renderer directly when the target environment is known (tests, tooling, editor integrations).
### `renderer.render()` options
The `.render()` method accepts either a `Container` or an options object:
```ts
// shorthand: just render the stage
renderer.render(app.stage);
// options form: control clearing, transform, or a render target
renderer.render({
container: app.stage,
clear: true,
transform: new Matrix(),
});
// render into a mip level, array layer, cube face or 3D slice of a texture
renderer.render({
container: myContainer,
target: renderTexture,
mipLevel: 1,
layer: 0,
});
// store the capture in screen orientation (for 3D UVs)
renderer.render({ container: scene3d, target: renderTexture, flipY: true });
```
`container` is the scene root to draw. `target` is a separate destination (e.g. a `RenderTexture`). `mipLevel > 0` is useful for custom LOD systems or manual mipmap generation. `flipY` defaults to `false`; set it to store a texture render un-flipped, with winding adjusted so back-face culling still works. `layer` selects an array layer, a cube face, or a depth slice of a 3D `TextureSource` (`depth`); pass the source itself as `target`.
### Render targets
```ts
import { CLEAR, RenderTarget, Texture, TextureSource } from "pixi.js";
const depthSource = new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" });
const target = new RenderTarget({
colorAttachments: [{ texture: new TextureSource({ width: 512, height: 512 }), loadOp: "clear" }],
depthStencilAttachment: { texture: depthSource, depthLoadOp: "clear" },
});
renderer.render({ container, target });
// bind directly from custom render code; always use the options object
renderer.renderTarget.push({ target, clear: CLEAR.COLOR, mipLevel: 0 });
renderer.renderTarget.pop();
const saved = renderer.renderTarget.getBindState();
renderer.renderTarget.bind(saved); // replays without clearing
// copy the depth attachment into another depth-format texture (WebGL2 and WebGPU)
const depthCopy = new Texture({
source: new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" }),
});
renderer.renderTarget.copyDepthTexture(target, depthCopy, { x: 0, y: 0 }, { width: 512, height: 512 });
```
- `RenderTarget` takes WebGPU-style `colorAttachments`/`depthStencilAttachment` or the older `colorTextures`/`depth`/`stencil`/`depthStencilTexture` options. `colorTextures: 0` with `depth: true` makes a depth-only target.
- Positional `bind(target, clear, ...)` and `push(...)` are deprecated since 8.20.0. `pop()` throws when the stack is empty.
- `copyDepthTexture` needs WebGL2 or WebGPU and a depth-format destination. The next render into the destination target must clear color only (`clear: CLEAR.COLOR`), or the copied depth is lost.
- Destroy a target you constructed with `target.destroy()`; the renderer releases the GPU objects it built for it.
### Resizing, texture generation, and interop
```ts
renderer.resize(window.innerWidth, window.innerHeight);
const texture = renderer.generateTexture(displayObject);
// Mixing PixiJS with Three.js (or any other WebGL/WebGPU library)
threeRenderer.resetState();
threeRenderer.render(scene, camera);
pixiRenderer.resetState();
pixiRenderer.render({ container: stage });
```
Call `resetState()` before each library renders. Both libraries leave GPU state (bound textures, blend modes, active shaders) that conflicts with the other; without `resetState()`, objects can disappear or blend incorrectly.
### Destroying a renderer
```ts
renderer.destroy();
```
Releases GPU resources, systems, pipes, and event listeners. A destroyed renderer cannot be used for further rendering.
### Manual rendering
```ts
await app.init({ autoStart: false, width: 800, height: 600 });
function frame() {
app.renderer.render(app.stage);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
Disable the automatic ticker plugin with `autoStart: false`, then call `app.renderer.render(app.stage)` yourself. Useful for integrating with an external game loop.
### Renderer selection at runtime
```ts
console.log(app.renderer.name); // 'webgl', 'webgpu', or 'canvas'
```
After `init`, `app.renderer` is the concrete class. Use `app.renderer.name` (a string) to branch on backend; `app.renderer.type` exists but is a numeric id meant for internal dispatch — prefer `name` in user code.
### Supports check
```ts
if (await isWebGPUSupported()) {
// ok to prefer webgpu
}
if (isWebGLSupported()) {
// ok to prefer webgl
}
// after init, WebGPU-only capability flags
if (renderer.name === "webgpu") {
renderer.device.extensions.transientAttachment; // GPUTextureUsage.TRANSIENT_ATTACHMENT available
renderer.limits.supportsOverrideConstants; // pipeline constants vs. source-baked overrides
}
```
Both helpers are exported from `pixi.js`. Useful if you want to tell the user which backend is about to be used before calling `app.init`.
### Context and device loss
```ts
// both renderers recover on their own; only render bundles need re-recording
if (!renderer.encoder.isBundleValid(bundle)) {
bundle = record();
}
```
The WebGL renderer restores itself after `webglcontextrestored`. The WebGPU renderer requests a new device when the browser reports `GPUDevice.lost` and rebuilds its GPU resources on the next render. A device you pass through the WebGPU `gpu` option is neither restored nor destroyed by PixiJS. A render bundle recorded on a lost device fails `isBundleValid` and must be re-recorded.
## Common Mistakes
### [HIGH] Expecting WebGPU everywhere
Wrong:
```ts
await app.init({ preference: ["webgpu"] });
```
Correct:
```ts
await app.init({ preference: ["webgpu", "webgl"] });
```
WebGPU is not yet available on all browsers. An array-form preference of only `['webgpu']` will fail init on unsupported browsers (no fallback). Always include `'webgl'` as a fallback unless you've verified WebGPU support upstream.
### [MEDIUM] Assuming CanvasRenderer supports everything
CanvasRenderer does not support filters, masks beyond basic clipping, compressed textures, or custom shaders. It's intended as a last-resort for environments that can't run WebGL. If you need full feature parity, target WebGL or WebGPU.
### [MEDIUM] Calling render before init
Wrong:
```ts
const app = new Application();
app.renderer.render(app.stage);
await app.init();
```
Correct:
```ts
const app = new Application();
await app.init();
app.renderer.render(app.stage);
```
`app.renderer` is populated only after `init()` resolves. Any access before that is `undefined`.
## API Reference
- [autoDetectRenderer](https://pixijs.download/release/docs/rendering.autoDetectRenderer.html.md)
- [AbstractRenderer](https://pixijs.download/release/docs/rendering.AbstractRenderer.html.md)
- [WebGLRenderer](https://pixijs.download/release/docs/rendering.WebGLRenderer.html.md)
- [WebGPURenderer](https://pixijs.download/release/docs/rendering.WebGPURenderer.html.md)
- [CanvasRenderer](https://pixijs.download/release/docs/rendering.CanvasRenderer.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [RenderTargetSystem](https://pixijs.download/release/docs/rendering.RenderTargetSystem.html.md)
+276
View File
@@ -0,0 +1,276 @@
---
name: pixijs-create
description: "Use this skill when scaffolding a new PixiJS v8 project with the create-pixi CLI or adding PixiJS to an existing project. Covers npm/yarn/pnpm/bun create commands, interactive vs non-interactive flows, bundler vs creation template categories, available template presets (bundler-vite, bundler-webpack, bundler-esbuild, bundler-import-map, creation-web, framework-react, extension-default), Node version requirements, `npm install pixi.js` for existing projects, TypeScript 5/6/7 tsconfig setup (moduleResolution, @webgpu/types, @types/web), post-scaffold dev flow, and the Vite top-level-await production-build gotcha. Triggers on: create pixi.js, npm create, npm install pixi.js, scaffold, template, bundler-vite, bundler-webpack, creation-web, framework-react, new project, existing project, getting started, quick start, TypeScript, tsconfig, moduleResolution, @webgpu/types, @types/web, Cannot find name GPUTextureUsage."
license: MIT
---
`create pixi.js` is the official CLI for scaffolding a new PixiJS v8 project. Run it with any package manager (`npm`, `yarn`, `pnpm`, `bun`) and pick a template from the interactive menu, or pass `--template` to skip prompts. It writes a self-contained project folder; you then `cd` in, install dependencies, and run the dev script.
## Quick Start
Scaffold a new project with interactive prompts:
```bash
npm create pixi.js@latest
```
Or skip prompts by passing a project name and template:
```bash
npm create pixi.js@latest my-game -- --template bundler-vite
```
Then:
```bash
cd my-game
npm install
npm run dev
```
Requires Node.js 18+ or 20+. Some templates (notably `creation-web` and `framework-react`) may require a newer Node version; the package manager will warn if so.
### Adding PixiJS to an existing project
If you already have a bundler, framework, or project set up, skip the CLI and install the package directly:
```bash
npm install pixi.js
```
Then import from `pixi.js` and construct an `Application` as shown in `pixijs-application`. The CLI templates are a convenience for new projects; they don't add anything to the library that `npm install pixi.js` can't give you.
**Related skills:** `pixijs-application` (how the scaffolded `new Application()` + `app.init()` entry point works), `pixijs-core-concepts` (renderers and the render loop), `pixijs-scene-core-concepts` (scene graph fundamentals for the first things you'll add to the stage), `pixijs-assets` (loading textures, fonts, and bundles the template expects you to drop into `public/` or `src/assets/`).
## Core Patterns
### Choose a package manager
The command is the same shape for every package manager:
```bash
npm create pixi.js@latest
yarn create pixi.js
pnpm create pixi.js
bun create pixi.js
```
Under npm 7+ you must pass a `--` before CLI flags so npm doesn't consume them:
```bash
npm create pixi.js@latest my-game -- --template bundler-vite
```
Yarn, pnpm, and bun don't need the extra separator:
```bash
yarn create pixi.js my-game --template bundler-vite
pnpm create pixi.js my-game --template bundler-vite
bun create pixi.js my-game --template bundler-vite
```
Use `.` as the project name to scaffold into the current directory.
### Interactive flow
Running with no arguments walks through prompts:
1. Project name (defaults to `pixi-project`).
2. Framework / template category.
3. Variant (TypeScript vs JavaScript where applicable).
4. Whether to install dependencies immediately (some runners).
At the end, the CLI prints the `cd` + install + dev commands for the manager you invoked it with.
### Non-interactive flow
Pass a project name and `--template` to skip all prompts. This is the form you want for scripts, CI, and quickstart docs:
```bash
npm create pixi.js@latest my-game -- --template bundler-vite
```
### Available template presets
Templates fall into two categories:
- **Bundler templates** (`bundler-*`): generic PixiJS setup wired up with your bundler of choice. Use one of these when you want to pick your own structure.
- **Creation templates** (`creation-*`): platform-tailored starters with extras already wired in (AssetPack, sound, UI, scene routing). Use one of these when you want batteries included.
- **Framework templates** (`framework-*`): PixiJS embedded inside a host framework like React.
- **Extension templates** (`extension-*`): scaffolding for building a reusable PixiJS package.
For most new projects, `bundler-vite` is the recommended starting point.
| Template | What you get |
| -------------------- | ------------------------------------------------------------------------------------------------------------ |
| `bundler-vite` | Vite + TypeScript PixiJS project. The default first-stop template. |
| `bundler-vite-js` | Vite + plain JavaScript. |
| `bundler-webpack` | Webpack + TypeScript. |
| `bundler-webpack-js` | Webpack + plain JavaScript. |
| `bundler-esbuild` | esbuild + TypeScript. |
| `bundler-esbuild-js` | esbuild + plain JavaScript. |
| `bundler-import-map` | No-bundler setup using a browser import map (good for learning / demos). |
| `creation-web` | PixiJS Creation Engine web template with scene-based game scaffolding, AssetPack, sound, and UI integration. |
| `framework-react` | React + TypeScript + PixiJS via the `@pixi/react` package. |
| `framework-react-js` | React + plain JavaScript + PixiJS. |
| `extension-default` | Starter for building a reusable PixiJS extension/package. |
The live list is maintained in the `create-pixi` repo; run `npm create pixi.js@latest` without arguments to see the current menu if you need to confirm.
### Post-scaffold flow
Every template ships with the same three-step onboarding:
```bash
cd my-game
npm install
npm run dev
```
`npm run dev` starts the local dev server on the default port (Vite 5173, webpack 8080, etc.; the template's README has the exact number). Changes to `src/` hot-reload without reloading the whole page.
Other scripts every template exposes (names may vary slightly by preset):
- `npm run build`: produce a production build in `dist/`.
- `npm run preview` / `npm run serve`: serve the production build locally.
- `npm run lint`: run the template's configured linter if it ships one.
### Scaffolding into an existing directory
Use `.` as the project name to write into the current working directory. The CLI refuses to run if non-empty and conflicting files exist unless you confirm the prompt.
```bash
mkdir my-game
cd my-game
npm create pixi.js@latest . -- --template bundler-vite
```
### TypeScript setup
PixiJS supports WebGPU, so its type declarations depend on the WebGPU types. Where those come from depends on your TypeScript version.
- **TypeScript 5:** no WebGPU types are built in, so PixiJS adds `@webgpu/types` for you. No additional setup required.
- **TypeScript 6 and 7:** the WebGPU types are built into the `"dom"` library, but some releases leave parts out, such as `GPUTextureUsage`. Use `@types/web`, which has the full set, in place of `"dom"`. Remove `@webgpu/types` from `types` if it's there, since it conflicts with the built-in types.
```bash
npm install --save-dev @types/web
```
```json
{
"compilerOptions": {
"lib": ["esnext"],
"types": ["@types/web"]
}
}
```
## Next steps
After `npm run dev` starts, the template opens on a blank or bunny-sprite scene. The usual progression is:
1. Read `pixijs-application` to understand how the template's entry point constructs `new Application()` and calls `await app.init(...)`, how `app.stage` / `app.renderer` / `app.canvas` hang together, and how the ResizePlugin and TickerPlugin behave by default.
2. Read `pixijs-core-concepts` for the renderer and render-loop mental model.
3. Read `pixijs-scene-core-concepts` before adding your first non-trivial scene so you know the container-vs-leaf rule upfront.
4. Drop in textures via `pixijs-assets` once you're ready to load real art.
## Common Mistakes
### [HIGH] Missing `--` separator on npm 7+
Wrong:
```bash
npm create pixi.js@latest my-game --template bundler-vite
```
Correct:
```bash
npm create pixi.js@latest my-game -- --template bundler-vite
```
npm 7+ consumes flags after the package spec unless you pass `--` to forward them. Without the separator, the CLI ignores `--template` and drops back to the interactive prompt. Yarn, pnpm, and bun don't need the separator.
### [MEDIUM] Running with an old Node version
PixiJS requires Node 18+ or 20+. Some templates (framework-react, creation-web) expect a newer Node for their tooling. Upgrade Node before re-running the CLI if you see an "engines" warning from your package manager.
### [MEDIUM] Top-level `await app.init()` broken in Vite production builds
On Vite versions `<=6.0.6`, top-level `await` works in dev but breaks in production builds, so a `bundler-vite` project that does this at module scope will fail after `npm run build`:
```ts
const app = new Application();
await app.init({ resizeTo: window }); // broken at module top level in prod
```
Wrap the init in an async IIFE instead:
```ts
(async () => {
const app = new Application();
await app.init({ resizeTo: window });
document.body.appendChild(app.canvas);
})();
```
Upgrading Vite past 6.0.6 also resolves it, but the IIFE pattern is safe on every version and matches the PixiJS quick-start guide.
### [HIGH] Keeping `@webgpu/types` in `types` on TypeScript 6 or 7
Wrong:
```json
{
"compilerOptions": {
"types": ["@webgpu/types"]
}
}
```
Correct: remove the `"@webgpu/types"` entry and keep any others.
TypeScript 6 and 7 declare the WebGPU types in their built-in `"dom"` library, so `@webgpu/types` declares them a second time. With `skipLibCheck: false` that produces dozens of conflicting-declaration errors inside `lib.dom.d.ts` and `@webgpu/types`. Keep it on TypeScript 5 only, where PixiJS loads it for you anyway.
### [MEDIUM] `Cannot find name 'GPUTextureUsage'` on TypeScript 6 or 7
Up to TypeScript 6.0.3 and 7.0.2, the built-in `"dom"` library has no WebGPU flag constants (`GPUBufferUsage`, `GPUColorWrite`, `GPUMapMode`, `GPUShaderStage`, `GPUTextureUsage`), so raw WebGPU code that uses them fails with `TS2552`. Adding `@webgpu/types` back only compiles with `skipLibCheck: true`, because it conflicts with the built-in types. Install `@types/web` 0.0.352 or later, drop `"dom"` from `lib`, and add `"@types/web"` to `types` alongside any existing entries, as shown in [TypeScript setup](#typescript-setup).
### [MEDIUM] `moduleResolution: "node"` breaks subpath imports
Wrong:
```json
{
"compilerOptions": {
"moduleResolution": "node"
}
}
```
Correct:
```json
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler"
}
}
```
`"node"` (also called `"node10"`) ignores the `exports` field in the PixiJS `package.json`, so `import 'pixi.js/advanced-blend-modes'` and other subpath imports don't resolve. TypeScript 6 reports `TS2882` for them and deprecates the setting (`TS5107`); TypeScript 7 removes it (`TS5108`). Use `"bundler"` if you use a bundler, or `"nodenext"` otherwise.
## API Reference
- [create-pixi on GitHub](https://github.com/pixijs/create-pixi)
- [create-pixi documentation site](https://pixijs.io/create-pixi/)
- [Application](https://pixijs.download/release/docs/app.Application.html.md): the class the generated entry point instantiates.
- [TypeScript guide](https://pixijs.download/release/docs/core-concepts-8.html.md): setup for TypeScript 5, 6, and 7.
@@ -0,0 +1,405 @@
---
name: pixijs-custom-rendering
description: "Use this skill when writing custom shaders, uniforms, filters, batchers, or low-level draw code in PixiJS v8. Covers Shader.from({gl, gpu, resources}), GlProgram/GpuProgram, UniformGroup with typed uniforms (f32, vec2, mat4x4), UBO mode, textures as resources, TextureView for depth sampling, 3D and array textures (depth, arrayLayerCount, sampler3D, texture_3d), WebGPU storage textures (storage: true), WGSL override constants, custom bind group layouts (gpuLayout), partial buffer updates (Buffer.update), Geometry.vertexCount/indexCount, TexturePool scratch textures, State winding and culling (clockwiseFrontFace, cullMode), WebGPU render bundles, custom Filter via Filter.from, GLSL ES 3.0 conventions (finalColor), uBackTexture sampling, pixi.js/unsafe-eval for strict CSP, custom Batcher and InstructionPipe.destroyInstructionSet via extensions. Triggers on: Shader, GLSL, WGSL, uniform, custom shader, blendRequired, ShaderOverrides, bind group layout, depth texture, 3D texture, sampler3D, texture_3d, storage texture, getSize, indexCount, TexturePool, getOptimalTexture, destroyInstructionSet, beginBundle, executeBundle, RenderBundle."
license: MIT
---
Custom shaders bind GLSL and WGSL programs to scene objects via `Shader.from({ gl, gpu, resources })`. Uniforms live in typed `UniformGroup`s, textures are passed as separate resources, and the same shader can target both WebGL and WebGPU.
## Quick Start
```ts
const uniforms = new UniformGroup({
uTime: { value: 0, type: "f32" },
});
const shader = Shader.from({
gl: { vertex: vertexSrc, fragment: fragmentSrc },
resources: { uniforms },
});
const geometry = new MeshGeometry({
positions: new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
});
const mesh = new Mesh({ geometry, shader });
app.stage.addChild(mesh);
app.ticker.add(() => {
shader.resources.uniforms.uniforms.uTime = performance.now() / 1000;
});
```
**Related skills:** `pixijs-filters` (built-in filters), `pixijs-scene-mesh` (custom geometry), `pixijs-performance` (batch optimization), `pixijs-migration-v8` (shader API migration from v7).
## Core Patterns
### Dual-renderer shader (WebGL + WebGPU)
```ts
import { Shader, GlProgram, GpuProgram, UniformGroup } from "pixi.js";
const glVertex = `...`; // GLSL vertex (write `#version 300 es` yourself if you want WebGL2/GLSL ES 3.0)
const glFragment = `...`; // GLSL fragment
const wgslSource = `...`; // WGSL combined
const shader = Shader.from({
gl: { vertex: glVertex, fragment: glFragment },
gpu: {
// entryPoint names are arbitrary; they must match the @vertex / @fragment
// function names in your WGSL source. PixiJS ships examples using
// 'mainVert' / 'mainFrag' but `main` is equally valid.
vertex: { entryPoint: "mainVert", source: wgslSource },
fragment: { entryPoint: "mainFrag", source: wgslSource },
},
resources: {
myUniforms: new UniformGroup({
uColor: { value: new Float32Array([1, 0, 0, 1]), type: "vec4<f32>" },
uMatrix: { value: new Float32Array(16), type: "mat4x4<f32>" },
}),
},
});
```
If only `gl` is provided, the shader works with WebGL only. If only `gpu` is provided, it works with WebGPU only. The `compatibleRenderers` bitmask is set automatically.
`GlProgram` does **not** auto-inject `#version 300 es`. If you write `#version 300 es` yourself, PixiJS preserves it and treats the shader as GLSL ES 3.0; otherwise it injects WebGL1 compat macros (`#define in varying`, `#define texture texture2D`) and runs the shader as WebGL1-style GLSL. `GlProgram` always injects a default precision (`highp` vertex, `mediump` fragment) and the program name. It also declares `highp` for sampler types GLSL ES 3.0 gives no default (`usampler2D`, `isampler2D`, `sampler2DArray`, `sampler3D`, and others), so you don't need a precision line for them; one you write yourself is kept. `sampler2D` and `samplerCube` keep their `lowp` default. For GLSL ES 3.0, use `in`/`out` instead of `attribute`/`varying`, `texture()` instead of `texture2D()`, and an `out vec4` instead of `gl_FragColor`.
### Textures as resources
Textures are resources, not uniforms. Pass the texture's `source` and `style` separately:
```ts
import { Shader, UniformGroup, Texture, Assets } from "pixi.js";
const texture = await Assets.load("myImage.png");
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
resources: {
uTexture: texture.source,
uSampler: texture.source.style,
myUniforms: new UniformGroup({
uAlpha: { value: 1.0, type: "f32" },
}),
},
});
// Swap texture at runtime
shader.resources.uTexture = otherTexture.source;
```
Resources are a flat key-value map. The key must match the uniform/binding name in the shader source.
Resources can also be plain objects (auto-wrapped into `UniformGroup`):
```ts
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
resources: {
myUniforms: {
uTime: { value: 0, type: "f32" },
},
},
});
```
### UBO mode (Uniform Buffer Objects)
UBO mode packs uniforms into a single GPU buffer. Required for WebGPU; optional (WebGL2+) for WebGL.
```ts
import { UniformGroup } from "pixi.js";
const ubo = new UniformGroup(
{
uProjection: { value: new Float32Array(16), type: "mat4x4<f32>" },
uAlpha: { value: 1.0, type: "f32" },
},
{ ubo: true, isStatic: true },
);
// Must call update() manually when isStatic is true
ubo.uniforms.uAlpha = 0.5;
ubo.update();
```
UBO rules:
- Only `f32` and `i32` based types are supported (no `u32`). Matrices are float-only.
- Samplers/textures cannot go in a UBO.
- The UniformGroup name in resources must exactly match the UBO block name in the shader.
- Structure and order must exactly match the shader layout.
- UBO sync uses `new Function` under the hood. In strict-CSP environments (no `unsafe-eval`), import `pixi.js/unsafe-eval` once at startup to swap in the fallback sync path; without it, UBO-backed shaders (and therefore WebGPU) will throw on first use.
### Custom filter
`Filter.from({ gl, resources })` is the shorthand. Pass only a fragment shader; PixiJS supplies a default vertex shader that handles output frame positioning.
```ts
import { Filter } from "pixi.js";
const filter = Filter.from({
gl: {
fragment: `
in vec2 vTextureCoord;
out vec4 finalColor;
uniform sampler2D uTexture;
uniform float uStrength;
void main(void) {
vec4 color = texture(uTexture, vTextureCoord);
finalColor = mix(color, vec4(1.0 - color.rgb, color.a), uStrength);
}
`,
},
resources: {
filterUniforms: {
uStrength: { value: 0.5, type: "f32" },
},
},
});
filter.resources.filterUniforms.uniforms.uStrength = 1.0;
```
For a custom vertex shader, use `new Filter({ glProgram: new GlProgram({ vertex, fragment }), resources })`.
#### Filter shader conventions (GLSL ES 3.0)
- `in vec2 vTextureCoord;` instead of `varying vec2 vTextureCoord;`
- `out vec4 finalColor;` instead of `gl_FragColor`
- `texture(uTexture, uv)` instead of `texture2D(uTexture, uv)`
- The default vertex shader exposes `uInputSize`, `uOutputFrame`, `uOutputTexture` and helpers `filterVertexPosition()` / `filterTextureCoord()`
#### Sampling the render target behind the filter
Set `blendRequired: true` and sample `uBackTexture` in the fragment shader. PixiJS copies the destination pixels into that uniform before running the filter:
```ts
const blendFilter = Filter.from({
gl: { fragment: blendFragSrc },
resources: { uniforms: { uAmount: { value: 0.5, type: "f32" } } },
blendRequired: true,
});
```
Only enable `blendRequired` when you need it; it forces an extra GPU copy every frame.
### Updating uniforms at runtime
```ts
// Access the UniformGroup via resources
shader.resources.myUniforms.uniforms.uTime = performance.now() / 1000;
// For isStatic UBOs, call update() after changing values
shader.resources.myUniforms.update();
```
### Advanced GPU features
See [references/advanced-gpu.md](references/advanced-gpu.md) for full samples of:
- **Partial buffer and texture uploads**: `buffer.update(sizeInBytes, offsetInBytes)` uploads only the changed byte range; `bufferImageSource.update(startTexel, endTexel)` uploads only a texel range of a data texture.
- **Vertex and index counts, winding, culling**: `geometry.vertexCount` (replaces the deprecated `getSize()`), `geometry.indexCount` to draw a prefix of a shared index buffer, `state.clockwiseFrontFace` and `cullMode`.
- **WGSL override constants** (WebGPU): `Shader.from({ gpu, resources, overrides: { STEPS: 8 } })`; each distinct set compiles its own pipeline.
- **Custom bind group layouts** (WebGPU): generate the default with `generateGpuLayoutGroups(extractStructAndGroups(source))`, edit it, pass it as `gpuLayout`.
- **Depth sampling with `TextureView`** (WebGPU): bind `new TextureView(depth, { aspect: "depth-only" })` as a resource while the target's depth attachment is `depthReadOnly`.
- **Integer textures**: `BufferImageSource` with `rgba32uint` etc., `usampler2D`/`texelFetch` and `texture_2d<u32>`/`textureLoad`, `scaleMode: "nearest"`.
- **3D and array textures**: `depth` or `arrayLayerCount` on a `TextureSource`/`BufferImageSource`, sampled with `sampler3D`/`texture_3d<f32>` or `sampler2DArray`/`texture_2d_array<f32>`; they upload whole, and `renderer.render({ container, target: source, layer })` draws into one slice or layer.
- **Storage textures** (WebGPU): `storage: true` on a `TextureSource`, then `renderer.texture.getGpuSource(source).createView()` to write it from your own compute pass.
- **Render bundles** (WebGPU): record draws once with `encoder.beginBundle()` / `endBundle()` and replay with `executeBundle()` while `isBundleValid()` holds.
- **Pooled scratch textures**: `TexturePool.getOptimalTexture({ width, height, resolution, antialias })` and `returnTexture()`.
### Uniform type reference
See [references/uniform-types.md](references/uniform-types.md) for the complete table of supported types, their WGSL/GLSL equivalents, and value formats.
### Custom Batcher (extension-based)
The `Batcher` abstract class enables custom batching for specialized rendering. Subclass it and register via extensions:
```ts
import { Batcher, extensions, ExtensionType } from "pixi.js";
import type {
BatcherOptions,
BatchableMeshElement,
BatchableQuadElement,
Geometry,
Shader,
} from "pixi.js";
class MyBatcher extends Batcher {
public static extension = {
type: [ExtensionType.Batcher],
name: "my-batcher",
};
public name = "my-batcher";
protected vertexSize = 6; // floats per vertex
public geometry: Geometry;
public shader: Shader;
constructor(options: BatcherOptions) {
super(options);
// Initialize geometry and shader
}
public packAttributes(
element: BatchableMeshElement,
float32View: Float32Array,
uint32View: Uint32Array,
index: number,
textureId: number,
): void {
// Pack mesh vertex attributes into the batch buffer
}
public packQuadAttributes(
element: BatchableQuadElement,
float32View: Float32Array,
uint32View: Uint32Array,
index: number,
textureId: number,
): void {
// Pack quad vertex attributes into the batch buffer
}
}
extensions.add(MyBatcher);
```
Elements reference the batcher by `batcherName`. The `BatchableElement` interface requires: `batcherName`, `texture`, `blendMode`, `indexSize`, `attributeSize`, `topology`, and `packAsQuad`.
A custom `InstructionPipe` that caches state per `InstructionSet` (the way `BatcherPipe` keeps its batchers) should implement `destroyInstructionSet(instructionSet)`. The renderer calls it when the owning render group is destroyed, so the cached GPU objects are released with it instead of leaking.
```ts
public destroyInstructionSet(instructionSet: InstructionSet): void {
this._cache[instructionSet.uid]?.destroy();
delete this._cache[instructionSet.uid];
}
```
## Common Mistakes
### [CRITICAL] Old Shader.from(vertex, fragment, uniforms) constructor
Wrong:
```ts
const shader = Shader.from(vertex, fragment, { uTime: 1 });
```
Correct:
```ts
const shader = Shader.from({
gl: { vertex, fragment },
resources: {
uniforms: new UniformGroup({
uTime: { value: 1, type: "f32" },
}),
},
});
```
v8 requires an options object with `gl`/`gpu` programs and `resources`. The positional API was removed.
### [CRITICAL] UniformGroup without type annotation
Wrong:
```ts
new UniformGroup({ uTime: 1 });
```
Correct:
```ts
new UniformGroup({ uTime: { value: 1, type: "f32" } });
```
Every uniform requires an explicit `{ value, type }` pair. Omitting the type causes a runtime error: "Uniform type undefined is not supported."
### [HIGH] UBO with unsupported types or wrong structure
UBO mode supports `f32` and `i32` based types (scalars and vectors). `u32` is not in the supported `UniformGroup` type list and will throw. Matrices are float-only (`mat*<f32>`). Samplers cannot be placed in UBOs.
The struct name and field order must exactly match the shader's UBO declaration. Mismatches produce garbled rendering with no error.
### [HIGH] Putting textures in UniformGroup
Wrong:
```ts
new UniformGroup({
uTexture: { value: texture, type: "f32" },
});
```
Correct:
```ts
const shader = Shader.from({
gl: { vertex, fragment },
resources: {
uTexture: texture.source,
uSampler: texture.source.style,
myUniforms: new UniformGroup({
uAlpha: { value: 1.0, type: "f32" },
}),
},
});
```
Textures are resources, not uniforms. Pass `texture.source` (TextureSource) and `texture.source.style` (TextureStyle) as top-level resource entries.
### [HIGH] Replaying a render bundle against a different render target
Wrong:
```ts
const bundle = encoder.endBundle();
// later, on every frame, regardless of what is bound
encoder.executeBundle(bundle);
```
Correct:
```ts
if (!bundle || !encoder.isBundleValid(bundle)) {
bundle = record();
}
encoder.executeBundle(bundle);
```
A bundle bakes the attachments and winding of the pass it was recorded in, and the device it was recorded on. Replaying it under a different target either fails WebGPU validation for the whole frame or silently renders inside out; replaying it after a device loss is rejected outright.
### [MEDIUM] Reading Geometry.getSize()
`geometry.getSize()` is deprecated since 8.20.0 and logs a warning. Use `geometry.vertexCount`, which is cached and only recomputed when buffers or attributes change.
## API Reference
- [Shader](https://pixijs.download/release/docs/rendering.Shader.html.md)
- [GlProgram](https://pixijs.download/release/docs/rendering.GlProgram.html.md)
- [GpuProgram](https://pixijs.download/release/docs/rendering.GpuProgram.html.md)
- [UniformGroup](https://pixijs.download/release/docs/rendering.UniformGroup.html.md)
- [Filter](https://pixijs.download/release/docs/filters.Filter.html.md)
- [Batcher](https://pixijs.download/release/docs/rendering.Batcher.html.md)
- [BatcherPipe](https://pixijs.download/release/docs/rendering.BatcherPipe.html.md)
- [ShaderOverrides](https://pixijs.download/release/docs/rendering.ShaderOverrides.html.md)
- [TextureView](https://pixijs.download/release/docs/rendering.TextureView.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [GpuEncoderSystem](https://pixijs.download/release/docs/rendering.GpuEncoderSystem.html.md)
- [RenderBundle](https://pixijs.download/release/docs/rendering.RenderBundle.html.md)
- [Geometry](https://pixijs.download/release/docs/rendering.Geometry.html.md)
- [State](https://pixijs.download/release/docs/rendering.State.html.md)
@@ -0,0 +1,244 @@
# Advanced GPU features
Lower-level rendering APIs for custom draw code. Items marked WebGPU only are ignored or unavailable on the WebGL renderer; branch on `renderer.name === "webgpu"` before relying on them.
## Partial buffer updates
```ts
import { Buffer, BufferUsage } from "pixi.js";
const buffer = new Buffer({
data: new Float32Array(4096),
usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,
});
buffer.data.set(newVertices, 256);
buffer.update(newVertices.byteLength, 256 * 4); // size and offset in bytes
```
`update()` with no arguments re-uploads the whole buffer. Pass a byte size and byte offset to upload only the range you changed. Works on WebGL and WebGPU.
## Partial texture uploads
```ts
import { BufferImageSource } from "pixi.js";
const data = new Float32Array(4096 * 64 * 4); // rgba32float: 4 floats per texel
const source = new BufferImageSource({ resource: data, width: 4096, height: 64 });
data.fill(1, 100 * 4, 116 * 4); // change texels 100 to 115
source.update(100, 116); // upload only those 16 texels
```
Texel `i` sits at `x = i % width`, `y = floor(i / width)`, and `end` is exclusive. The range applies to that call only, so track the lowest and highest changed texel yourself and call `update` once per frame. `update()` with no arguments uploads the whole texture. Works on WebGL and WebGPU. A 3D texture (`depth`) or 2D array (`arrayLayerCount`) always uploads whole, so call `update()` with no range.
## Vertex count, index count, winding, and culling
```ts
const count = geometry.vertexCount; // cached, from the first non-instanced attribute
// several geometries share one index buffer sized for the biggest batch;
// each draws only the prefix it currently uses
const quads = new Geometry({
attributes: { aPosition: positions },
indexBuffer: sharedIndices,
indexCount: liveQuads * 6,
});
quads.indexCount = 12; // read at draw time; no re-upload
const state = new State();
state.culling = true;
state.clockwiseFrontFace = true; // or state.cullMode = "front"
```
`geometry.getSize()` is deprecated since 8.20.0; read `vertexCount` instead. `indexCount` of `0` (the default) draws the whole index buffer; any other value draws that many indices. A `size` passed to `encoder.draw()` still wins. `clockwiseFrontFace` selects which winding counts as front-facing on both renderers. When rendering into a texture PixiJS inverts the winding to match the flipped projection; call `renderer.renderTarget.isFrontFaceInverted()` if your own code needs the resolved orientation, or `isFrontFaceInverted(target, flipY)` to ask about a `RenderTarget` before binding it (`renderer.renderTarget.getRenderTarget(texture)` returns one for a texture).
## WGSL override constants (WebGPU only)
```ts
const source = /* wgsl */ `
override BLUR_STEPS: u32 = 4u;
// ...
`;
const shader = Shader.from({
gpu: {
vertex: { source, entryPoint: "vsMain" },
fragment: { source, entryPoint: "fsMain" },
},
resources: { uniforms },
overrides: { BLUR_STEPS: 8 },
});
```
`overrides` takes a plain `Record<string, number>` or a `ShaderOverrides` instance. Values are fixed when the shader is created and become part of the pipeline cache key, so every distinct set compiles its own pipeline. To change a value, create a new shader. On browsers without pipeline constants (Safari) PixiJS substitutes the values into the WGSL source; `renderer.limits.supportsOverrideConstants` tells you which path is active. WebGL ignores `overrides` entirely.
## Custom bind group layout (WebGPU only)
```ts
import { GpuProgram, extractStructAndGroups, generateGpuLayoutGroups } from "pixi.js";
const gpuLayout = generateGpuLayoutGroups(extractStructAndGroups(source));
// narrow one texture binding to the fragment stage
gpuLayout[0][1].visibility = GPUShaderStage.FRAGMENT;
const program = new GpuProgram({
vertex: { source, entryPoint: "vsMain" },
fragment: { source, entryPoint: "fsMain" },
gpuLayout,
});
```
`generateGpuLayoutGroups` is the same generator `GpuProgram` runs when `gpuLayout` is omitted, and it marks every binding visible to both stages. Generate the default, edit the entries you care about, and pass the whole array back rather than hand-writing the layout.
## Sampling a depth texture with TextureView (WebGPU only)
```ts
import { RenderTarget, Shader, State, TextureSource, TextureView } from "pixi.js";
const depth = new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" });
const color = new TextureSource({ width: 512, height: 512 });
// pass 1: write depth
const writeTarget = new RenderTarget({
colorAttachments: [{ texture: color, loadOp: "clear", clearValue: [0, 0, 0, 1] }],
depthStencilAttachment: { texture: depth, depthLoadOp: "clear", depthClearValue: 1 },
});
// pass 2: keep the same depth attached read-only while sampling it
const readTarget = new RenderTarget({
colorAttachments: [{ texture: color, loadOp: "load" }],
depthStencilAttachment: { texture: depth, depthReadOnly: true },
});
const shader = Shader.from({
gpu: { vertex: { source, entryPoint: "vsMain" }, fragment: { source, entryPoint: "fsMain" } },
resources: { uDepthTexture: new TextureView(depth, { aspect: "depth-only" }) },
});
```
Declare `@group(0) @binding(1) var uDepthTexture: texture_depth_2d;` in WGSL and read it with `textureLoad`. Use a `State` with `depthMask = false` in the read pass. A `TextureView` is a bind resource like a `TextureSource`; on WebGL it binds the underlying source and the descriptor is ignored.
## Integer textures
```ts
import { BufferImageSource, Shader } from "pixi.js";
const ids = new BufferImageSource({
resource: new Uint32Array([1, 2, 3, 4]), // picks rgba32uint
width: 1,
height: 1,
scaleMode: "nearest",
});
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
gpu: { vertex: { source, entryPoint: "vsMain" }, fragment: { source, entryPoint: "fsMain" } },
resources: { uIds: ids },
});
```
Integer formats (`*uint`, `*sint`) hold exact integers. Use them where a float texture would lose bits, since small integers are denormal floats and GPUs may flush them to zero. They can't be filtered, so set `scaleMode: "nearest"`. `BufferImageSource` infers `rgba32uint` from a `Uint32Array` and `rgba16uint` from a `Uint16Array`; pass `format: "rgba32sint"` (or another signed format) explicitly for signed data. It defaults integer formats to `alphaMode: "no-premultiply-alpha"` because integer data can't be premultiplied on upload.
In GLSL ES 3.0, declare `uniform usampler2D uIds;` (or `isampler2D`) and read it with `texelFetch(uIds, ivec2(x, y), 0)`. GLSL ES 3.0 gives integer samplers no default precision, so PixiJS declares `highp` for them and you don't need a precision line. A precision line you write yourself is kept. In WGSL, declare `@group(0) @binding(1) var uIds: texture_2d<u32>;` (or `<i32>`) and read it with `textureLoad(uIds, vec2<i32>(x, y), 0)`; the generated bind group layout takes its `sampleType` from the `<u32>` / `<i32>` suffix. PixiJS can't render into integer textures yet.
## 3D and array textures
```ts
import { BufferImageSource } from "pixi.js";
const size = 64;
const noise = new BufferImageSource({
resource: new Uint8Array(size * size * size * 4), // slice after slice, row-major
width: size,
height: size,
depth: size, // or arrayLayerCount: n for a 2D array
format: "rgba8unorm",
});
```
`depth` on a `TextureSource` or `BufferImageSource` makes a `"3d"` texture, and `arrayLayerCount > 1` makes a `"2d-array"` texture. A texture can't have both, and TypeScript rejects options that set both. Pass `viewDimension` only when the size doesn't decide it, such as `"cube"` for 6 layers. `dimensions` is deprecated; leave it out. These textures need WebGL2 or WebGPU; WebGL1 has no 3D or array textures.
The buffer holds the slices (or layers) one after another, each in row-major order, so texel `(x, y, z)` sits at index `x + y * width + z * width * height`. `resolution` doesn't scale `depth`. A 3D or array `BufferImageSource` defaults to `alphaMode: "no-premultiply-alpha"` and always uploads whole, so `update()` takes no range.
In GLSL ES 3.0, declare `uniform sampler3D` or `uniform sampler2DArray`. In WGSL, declare `texture_3d<f32>` or `texture_2d_array<f32>`. PixiJS adds the precision line for `sampler3D` and `sampler2DArray`, as for integer samplers above.
`rgba32float`, the default for a `Float32Array`, needs an optional feature for linear filtering that PixiJS doesn't request on WebGPU. Use `scaleMode: "nearest"` with it, or pick `rgba8unorm`, `r8unorm` or `rgba16float` for smooth sampling.
To draw into one slice or layer, pass the source itself as `target` and pick the slice with `layer`: `renderer.render({ container, target: noise, layer: z, clear: true })`. `layer` selects an array layer, a cube face, or a 3D depth slice. `RenderTexture.create` doesn't take `depth`, so use the `TextureSource` directly. `renderer.renderTarget.push({ target, layer })` takes `layer` too.
## Storage textures (WebGPU only)
```ts
import { TextureSource } from "pixi.js";
const volume = new TextureSource({ width: 64, height: 64, depth: 64, format: "rgba8unorm", storage: true });
// bind this view to a texture_storage_3d<rgba8unorm, write> in your own compute pass
const view = renderer.texture.getGpuSource(volume).createView();
```
`storage: true` adds `GPUTextureUsage.STORAGE_BINDING`, so your own compute pass can write the texture through `renderer.texture.getGpuSource(source).createView()`. PixiJS still samples it like any other texture. WebGL ignores the option.
Every device accepts `rgba8unorm`, `rgba16float`, `r32float`, `rg32float`, `rgba32float` and the matching integer formats as storage textures. `bgra8unorm` needs the `bgra8unorm-storage` feature, and formats such as `r8unorm` or `r16float` need `texture-formats-tier1`. PixiJS enables both features when the GPU has them. WebGPU rejects any other format when the texture is created.
`autoGenerateMipmaps` on a 3D texture uses `gl.generateMipmap` on WebGL. WebGPU writes the mips with a compute shader, so the texture needs `storage: true` and the `rgba8unorm` or `rgba16float` format.
## Render bundles (WebGPU only)
```ts
import { RenderContainer } from "pixi.js";
import type { RenderBundle, WebGPURenderer } from "pixi.js";
let bundle: RenderBundle | null = null;
const props = new RenderContainer({
render: (renderer) => {
const encoder = (renderer as WebGPURenderer).encoder;
if (!bundle || !encoder.isBundleValid(bundle)) {
encoder.beginBundle("static-props");
encoder.draw({ geometry, shader, state });
bundle = encoder.endBundle();
}
encoder.executeBundle(bundle);
},
});
```
A bundle records draw calls once and replays them on later frames. It bakes the render target it was recorded in (formats, sample count, winding) and the device, so `isBundleValid` returns `false` after the target changes (a filter wrapping the container, `flipY` flipping) or after a device loss. Re-record when it does; otherwise WebGPU rejects the frame or draws inside out. Pass an array to `executeBundle` to replay several bundles in one call. The optional label names the bundle in GPU captures.
## Pooled scratch textures
```ts
import { TexturePool } from "pixi.js";
const scratch = TexturePool.getOptimalTexture({
width: bounds.width,
height: bounds.height,
resolution: renderer.resolution,
antialias: true,
scaleMode: "nearest",
});
const { width, height } = TexturePool.getOptimalSize(bounds.width, bounds.height, renderer.resolution);
TexturePool.returnTexture(scratch);
```
`getOptimalTexture` takes one request object: `width` and `height` are the minimum frame size; `resolution`, `antialias`, `autoGenerateMipmaps`, `format`, and `scaleMode` are optional, and each combination has its own bucket, so ask for a float or depth format directly instead of restyling a returned texture. Each axis is rounded up to the next power of two or the renderer's screen size, whichever is smaller. `getOptimalSize` reports that backing size without taking a texture, and `getSameSizeTexture(texture)` matches an existing texture's frame and resolution. The positional `getOptimalTexture(width, height, resolution, antialias)` form, `TexturePool.textureStyle`, and `enableFullScreen` are deprecated since 8.21.0.
## API Reference
- [TexturePool](https://pixijs.download/release/docs/rendering.TexturePool.html.md)
- [Buffer](https://pixijs.download/release/docs/rendering.Buffer.html.md)
- [Geometry](https://pixijs.download/release/docs/rendering.Geometry.html.md)
- [State](https://pixijs.download/release/docs/rendering.State.html.md)
- [ShaderOverrides](https://pixijs.download/release/docs/rendering.ShaderOverrides.html.md)
- [GpuProgram](https://pixijs.download/release/docs/rendering.GpuProgram.html.md)
- [TextureView](https://pixijs.download/release/docs/rendering.TextureView.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [GpuEncoderSystem](https://pixijs.download/release/docs/rendering.GpuEncoderSystem.html.md)
- [RenderBundle](https://pixijs.download/release/docs/rendering.RenderBundle.html.md)
@@ -0,0 +1,95 @@
# Uniform Types Reference
All supported PixiJS v8 uniform types for use with `UniformGroup`. These type strings are passed in the `type` field of each uniform definition.
## Type Table
| PixiJS type | WGSL equivalent | GLSL equivalent | JS value |
| ------------- | --------------- | --------------- | ----------------------------- |
| `f32` | `f32` | `float` | `number` |
| `i32` | `i32` | `int` | `number` |
| `vec2<f32>` | `vec2<f32>` | `vec2` | `Float32Array(2)` or `[x, y]` |
| `vec3<f32>` | `vec3<f32>` | `vec3` | `Float32Array(3)` |
| `vec4<f32>` | `vec4<f32>` | `vec4` | `Float32Array(4)` |
| `vec2<i32>` | `vec2<i32>` | `ivec2` | `Int32Array(2)` |
| `vec3<i32>` | `vec3<i32>` | `ivec3` | `Int32Array(3)` |
| `vec4<i32>` | `vec4<i32>` | `ivec4` | `Int32Array(4)` |
| `mat2x2<f32>` | `mat2x2<f32>` | `mat2` | `Float32Array(4)` |
| `mat3x3<f32>` | `mat3x3<f32>` | `mat3` | `Float32Array(9)` or `Matrix` |
| `mat4x4<f32>` | `mat4x4<f32>` | `mat4` | `Float32Array(16)` |
| `mat3x2<f32>` | `mat3x2<f32>` | `mat3x2` | `Float32Array(6)` |
| `mat4x2<f32>` | `mat4x2<f32>` | `mat4x2` | `Float32Array(8)` |
| `mat2x3<f32>` | `mat2x3<f32>` | `mat2x3` | `Float32Array(6)` |
| `mat4x3<f32>` | `mat4x3<f32>` | `mat4x3` | `Float32Array(12)` |
| `mat2x4<f32>` | `mat2x4<f32>` | `mat2x4` | `Float32Array(8)` |
| `mat3x4<f32>` | `mat3x4<f32>` | `mat3x4` | `Float32Array(12)` |
## Array Uniforms
For arrays of a type, use the `size` property instead of array syntax in the type:
```ts
import { UniformGroup } from "pixi.js";
// Array of 10 vec4 values
const uniforms = new UniformGroup({
uColors: { value: new Float32Array(40), type: "vec4<f32>", size: 10 },
});
```
Using `array<vec4<f32>, 10>` in the type field will throw an error directing you to use the `size` property instead.
## Usage Examples
### Scalars
```ts
import { UniformGroup } from "pixi.js";
const uniforms = new UniformGroup({
uTime: { value: 0, type: "f32" },
uIndex: { value: 0, type: "i32" },
});
uniforms.uniforms.uTime = 1.5;
uniforms.uniforms.uIndex = 3;
```
### Vectors
```ts
import { UniformGroup } from "pixi.js";
const uniforms = new UniformGroup({
uPosition: { value: new Float32Array([100, 200]), type: "vec2<f32>" },
uDirection: { value: new Float32Array([0, 1, 0]), type: "vec3<f32>" },
uColor: { value: new Float32Array([1, 0, 0, 1]), type: "vec4<f32>" },
uGridSize: { value: new Int32Array([16, 16]), type: "vec2<i32>" },
});
```
### Matrices
```ts
import { UniformGroup, Matrix } from "pixi.js";
const uniforms = new UniformGroup({
uTransform: { value: new Matrix(), type: "mat3x3<f32>" },
uProjection: { value: new Float32Array(16), type: "mat4x4<f32>" },
uRotation: { value: new Float32Array(4), type: "mat2x2<f32>" },
});
```
PixiJS `Matrix` (2D affine transform) maps to `mat3x3<f32>`. For 3D projection matrices, use a raw `Float32Array(16)` with `mat4x4<f32>`.
## UBO Constraints
When using `{ ubo: true }` on a UniformGroup:
- `f32` and `i32` based types are supported (scalars and vectors)
- Matrices are float-only (`mat*<f32>`)
- `u32` is not in the supported `UniformGroup` type list
- Samplers and textures cannot be placed in UBOs
- Field names and order must exactly match the shader's uniform block declaration
- The resource key in the shader must match the UBO block name
+243
View File
@@ -0,0 +1,243 @@
---
name: pixijs-environments
description: "Use this skill when running PixiJS v8 outside a standard browser: Web Workers, OffscreenCanvas, Node/SSR, or CSP-restricted contexts. Covers DOMAdapter.set, BrowserAdapter, WebWorkerAdapter, custom Adapter interface, pixi.js/unsafe-eval for strict CSP. Triggers on: DOMAdapter, BrowserAdapter, WebWorkerAdapter, Web Worker, OffscreenCanvas, Node, headless, SSR, CSP, unsafe-eval, Adapter."
license: MIT
---
`DOMAdapter` abstracts every piece of DOM access PixiJS does (canvas creation, Image loading, fetch, XML parsing) so the library can run in non-browser contexts. Call `DOMAdapter.set(...)` before `app.init()` to swap in a different adapter.
## Quick Start
```ts
// worker.ts — OffscreenCanvas posted from main thread
DOMAdapter.set(WebWorkerAdapter);
self.onmessage = async (event) => {
const app = new Application();
await app.init({
canvas: event.data.canvas,
width: 800,
height: 600,
});
};
```
For CSP contexts that block `unsafe-eval`, import the polyfill before any renderer init:
```ts
import "pixi.js/unsafe-eval";
```
**Related skills:** `pixijs-application` (standard browser init), `pixijs-migration-v8` (settings removal, adapter changes).
## Core Patterns
### Web Worker with OffscreenCanvas
Transfer an OffscreenCanvas from the main thread, then initialize PixiJS in the worker:
```ts
// main.ts
const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.ts", { type: "module" });
worker.postMessage({ canvas: offscreen }, [offscreen]);
```
```ts
// worker.ts
import { Application, DOMAdapter, WebWorkerAdapter } from "pixi.js";
DOMAdapter.set(WebWorkerAdapter);
self.onmessage = async (event) => {
const app = new Application();
await app.init({
canvas: event.data.canvas,
width: 800,
height: 600,
});
};
```
`DOMAdapter.set(WebWorkerAdapter)` must happen before `new Application()`. The WebWorkerAdapter uses `OffscreenCanvas` instead of `document.createElement('canvas')` and `@xmldom/xmldom` for XML parsing.
Features that do **not** work inside a Web Worker (no DOM access):
- `DOMContainer` — there is no real DOM node to overlay.
- `AccessibilitySystem` — depends on live DOM focus and screen reader hooks.
- `FontFace` loading via the Font Loading API — use pre-converted bitmap fonts (`BitmapFont.install` or `.fnt` assets) instead.
### Environment-specific subpath imports
Instead of importing `pixi.js`, you can pull in a curated bundle for each environment:
```ts
import "pixi.js/browser"; // accessibility, dom, events, spritesheet, rendering, filters
import "pixi.js/webworker"; // spritesheet, rendering, filters (no DOM-only modules)
```
`pixi.js/webworker` deliberately omits `accessibility`, `dom`, and `events` because they require the DOM. Use these subpath entries when you want static, synchronous module registration instead of relying on `loadEnvironmentExtensions` to dynamic-import the right set at renderer init.
### loadEnvironmentExtensions
```ts
import { loadEnvironmentExtensions } from "pixi.js";
await loadEnvironmentExtensions(false); // false = load defaults; true = skip
```
`loadEnvironmentExtensions(skip)` replaces the deprecated `autoDetectEnvironment` helper (since 8.1.6). Pass `true` to opt out of auto-loading the default browser extensions when you are bootstrapping a custom environment. `autoDetectEnvironment(add)` still exists as a shim that forwards to `loadEnvironmentExtensions(!add)`.
### CSP-compliant setup
PixiJS uses `new Function()` internally for shader compilation and uniform syncing. In Content Security Policy environments that block `unsafe-eval`, import the polyfill:
```ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
```
The `pixi.js/unsafe-eval` import replaces eval-based code generation with static polyfills for shader sync, UBO sync, uniform sync, and particle buffer updates. The import must come before any PixiJS renderer initialization.
**Tension note:** The name `pixi.js/unsafe-eval` is counterintuitive. It does not enable unsafe eval; it removes the need for it. The name refers to the CSP directive it works around.
### Custom adapter
For non-standard environments (Node.js, headless testing, SSR), implement the full Adapter interface:
```ts
import { DOMAdapter } from "pixi.js";
import type { Adapter } from "pixi.js";
import { createCanvas, Image } from "canvas";
import { DOMParser } from "@xmldom/xmldom";
const HeadlessAdapter: Adapter = {
createCanvas: (width, height) => createCanvas(width ?? 0, height ?? 0),
createImage: () => new Image(),
getCanvasRenderingContext2D: () => CanvasRenderingContext2D,
getWebGLRenderingContext: () => WebGLRenderingContext,
getNavigator: () => ({ userAgent: "HeadlessAdapter", gpu: null }),
getBaseUrl: () => "file://",
getFontFaceSet: () => null,
fetch: (url, options) => fetch(url, options),
parseXML: (xml) => new DOMParser().parseFromString(xml, "text/xml"),
};
DOMAdapter.set(HeadlessAdapter);
```
The Adapter interface requires these methods: `createCanvas`, `createImage`, `getCanvasRenderingContext2D`, `getWebGLRenderingContext`, `getNavigator`, `getBaseUrl`, `getFontFaceSet`, `fetch`, `parseXML`.
### Checking the current adapter
```ts
import { DOMAdapter } from "pixi.js";
const adapter = DOMAdapter.get();
const canvas = adapter.createCanvas(256, 256);
const img = adapter.createImage();
```
`DOMAdapter.get()` returns whatever adapter is currently set. Use this for any DOM access within PixiJS-adjacent code instead of calling `document` or `Image` directly.
## Common Mistakes
### [CRITICAL] Not setting adapter before app.init()
Wrong:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
DOMAdapter.set(WebWorkerAdapter); // too late; adapter already read during init
```
Correct:
```ts
DOMAdapter.set(WebWorkerAdapter);
const app = new Application();
await app.init({ width: 800, height: 600 });
```
`DOMAdapter.set()` must be called before `app.init()` in non-browser environments. PixiJS reads the adapter during `app.init()` when the renderer is created. `new Application()` itself only creates the stage Container and does not read the adapter.
### [HIGH] Using document or Image directly
Wrong:
```ts
const img = new Image();
img.src = "texture.png";
```
Correct:
```ts
import { DOMAdapter } from "pixi.js";
const img = DOMAdapter.get().createImage();
img.src = "texture.png";
```
All DOM access in PixiJS goes through DOMAdapter. Direct use of `document`, `Image`, or other browser globals breaks Web Worker and SSR compatibility.
### [HIGH] CSP unsafe-eval import name confusion
Wrong:
```ts
// CSP environment, omitting the import
import { Application } from "pixi.js";
// Throws: "Current environment does not allow unsafe-eval,
// please use pixi.js/unsafe-eval module to enable support."
```
Correct:
```ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";
```
The `pixi.js/unsafe-eval` import removes the need for `eval()` / `new Function()` in shader compilation. Despite the name suggesting it enables unsafe eval, it does the opposite: it installs static polyfills so PixiJS works under strict CSP.
PixiJS detects CSP blocking at renderer init and throws the error above. The browser may also log its own CSP violation before PixiJS reports; both point to the same fix.
### [HIGH] Using old settings.ADAPTER pattern
Wrong:
```ts
import { settings, WebWorkerAdapter } from "pixi.js";
settings.ADAPTER = WebWorkerAdapter;
```
Correct:
```ts
import { DOMAdapter, WebWorkerAdapter } from "pixi.js";
DOMAdapter.set(WebWorkerAdapter);
```
The `settings` object was removed in v8. All adapter configuration uses `DOMAdapter.set()`.
## API Reference
- [DOMAdapter](https://pixijs.download/release/docs/environment.DOMAdapter.html.md)
- [BrowserAdapter](https://pixijs.download/release/docs/environment.BrowserAdapter.html.md)
- [WebWorkerAdapter](https://pixijs.download/release/docs/environment.WebWorkerAdapter.html.md)
- [autoDetectEnvironment](https://pixijs.download/release/docs/environment.autoDetectEnvironment.html.md)
- [loadEnvironmentExtensions](https://pixijs.download/release/docs/environment.loadEnvironmentExtensions.html.md)
+387
View File
@@ -0,0 +1,387 @@
---
name: pixijs-events
description: "Use this skill when handling pointer, mouse, touch, or wheel input in PixiJS v8. Covers eventMode (none, passive, auto, static, dynamic), FederatedEvent types, propagation and capture phase, hitArea, interactiveChildren, cursor and cursorStyles, global move events for drag, eventFeatures config. Triggers on: eventMode, FederatedPointerEvent, pointerdown, click, tap, globalpointermove, drag, hitArea, cursor, stopPropagation, persistentDeviceId, contextmenu, rightclick."
license: MIT
---
PixiJS's federated event system mirrors DOM events on the scene graph. Set `container.eventMode = 'static'` to opt an object in, then listen with `.on()`, `addEventListener()`, or `onEventName` property handlers. Move events fire only over the listening object; use `globalpointermove` for drag.
## Quick Start
```ts
const button = new Sprite(await Assets.load("button.png"));
button.eventMode = "static";
button.cursor = "pointer";
app.stage.addChild(button);
button.on("pointertap", (event) => {
console.log("clicked at", event.global.x, event.global.y);
});
let dragging = false;
button.on("pointerdown", () => {
dragging = true;
});
button.on("pointerup", () => {
dragging = false;
});
button.on("pointerupoutside", () => {
dragging = false;
});
button.on("globalpointermove", (event) => {
if (dragging) button.parent.toLocal(event.global, undefined, button.position);
});
```
**Related skills:** `pixijs-accessibility` (screen reader + keyboard), `pixijs-scene-dom-container` (HTML overlays), `pixijs-performance` (event-heavy scenes).
## Core Patterns
### eventMode values
```ts
import { Sprite } from "pixi.js";
const sprite = new Sprite();
// No interaction at all; children also ignored
sprite.eventMode = "none";
// Default. Self not interactive; interactive children still work
sprite.eventMode = "passive";
// Hit tested only when a parent is interactive
sprite.eventMode = "auto";
// Standard interaction: receives pointer/mouse/touch events
sprite.eventMode = "static";
// Like static, but also fires synthetic events from the ticker
// when the pointer is stationary (for animated objects under cursor)
sprite.eventMode = "dynamic";
```
Use `'static'` for buttons, UI elements, and drag targets. Use `'dynamic'` only for objects that move under a stationary cursor and need continuous hover updates.
Use `isInteractive()` to check whether an object can receive events:
```ts
sprite.eventMode = "static";
sprite.isInteractive(); // true
sprite.eventMode = "passive";
sprite.isInteractive(); // false
```
### Event types
Pointer events (recommended for cross-device compatibility): `pointerdown`, `pointerup`, `pointerupoutside`, `pointermove`, `pointerover`, `pointerout`, `pointerenter`, `pointerleave`, `pointertap`, `pointercancel`.
Mouse events: `mousedown`, `mouseup`, `mouseupoutside`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `click`, `rightdown`, `rightup`, `rightupoutside`, `rightclick`, `contextmenu`, `wheel`. PixiJS doesn't block the browser's context menu; call `event.preventDefault()` in a `contextmenu` listener to keep it closed. Canceling `rightdown`, `rightup`, or `rightclick` doesn't keep it closed. On macOS, ctrl + click also fires `contextmenu`, and the browser can report it as a left click.
Touch events: `touchstart`, `touchend`, `touchendoutside`, `touchmove`, `touchcancel`, `tap`. Each touch carries `altKey`, `ctrlKey`, `metaKey`, and `shiftKey` copied from the native `TouchEvent`, so modifier keys work the same as with mouse or pointer events.
Global move events: `globalpointermove`, `globalmousemove`, `globaltouchmove`. These fire on every pointer movement regardless of whether the pointer is over the listening object.
Container lifecycle events (no `eventMode` required): `added`, `removed`, `destroyed`, `childAdded`, `childRemoved`, `visibleChanged`.
### Listening styles
```ts
import { Sprite } from "pixi.js";
const sprite = new Sprite();
sprite.eventMode = "static";
// EventEmitter style (recommended)
const handler = (e) => console.log("clicked");
sprite.on("pointerdown", handler);
sprite.once("pointerdown", handler); // one-time
sprite.off("pointerdown", handler);
// DOM style
sprite.addEventListener(
"click",
(event) => {
console.log("Clicked!", event.detail);
},
{ once: true },
);
// Property-based handlers
sprite.onclick = (event) => {
console.log("Clicked!", event.detail);
};
```
### Pointer events and propagation
```ts
import { Sprite, Container } from "pixi.js";
const parent = new Container();
parent.eventMode = "static";
const child = new Sprite();
child.eventMode = "static";
parent.addChild(child);
child.on("pointerdown", (event) => {
console.log("child pressed");
event.stopPropagation(); // prevent parent from receiving this event
});
parent.on("pointerdown", () => {
console.log("parent pressed (only if child did not stop propagation)");
});
```
### Capture phase events
All events support capture phase by appending `capture` to the event name (e.g., `pointerdowncapture`, `clickcapture`). Capture listeners fire during the capturing phase, before the event reaches its target.
```ts
container.addEventListener(
"pointerdown",
(event) => {
event.stopImmediatePropagation(); // blocks event from reaching children
},
{ capture: true },
);
```
### Hit testing
When a pointer event fires, PixiJS walks the display tree to find the top-most interactive element under the pointer. The traversal follows these rules:
- `eventMode = 'none'` on a container skips that element and its entire subtree.
- `interactiveChildren = false` on a container skips its children (the container itself can still be tested).
- A `hitArea` overrides bounds-based testing; only the shape is checked.
- Objects that are not visible, not renderable, or not measurable are skipped.
Set a custom `hitArea` to override bounds-based testing. This also speeds up hit tests on large or complex objects by reducing the geometry checked:
```ts
import { Sprite, Rectangle, Circle, Polygon } from "pixi.js";
const sprite = new Sprite();
sprite.eventMode = "static";
// Rectangular hit area
sprite.hitArea = new Rectangle(0, 0, 100, 50);
// Circular hit area
sprite.hitArea = new Circle(50, 50, 40);
// Polygon hit area
sprite.hitArea = new Polygon([0, 0, 100, 0, 50, 100]);
// Custom hit test via contains()
sprite.hitArea = {
contains(x: number, y: number): boolean {
return x >= 0 && x <= 100 && y >= 0 && y <= 100;
},
};
```
### Global move events and drag
```ts
import { Sprite, FederatedPointerEvent } from "pixi.js";
const sprite = new Sprite();
sprite.eventMode = "static";
sprite.cursor = "grab";
let dragging = false;
sprite.on("pointerdown", (event: FederatedPointerEvent) => {
dragging = true;
sprite.cursor = "grabbing";
});
// globalpointermove fires even when pointer leaves the object
sprite.on("globalpointermove", (event: FederatedPointerEvent) => {
if (dragging) {
sprite.position.set(event.global.x, event.global.y);
}
});
sprite.on("pointerup", () => {
dragging = false;
sprite.cursor = "grab";
});
sprite.on("pointerupoutside", () => {
dragging = false;
sprite.cursor = "grab";
});
```
### Cursor styles
Basic usage sets the `cursor` property per-object. For reusable cursors, register named styles on the event system:
```ts
app.renderer.events.cursorStyles.default = "url('bunny.png'), auto";
app.renderer.events.cursorStyles.hover = "url('bunny_saturated.png'), auto";
sprite.eventMode = "static";
sprite.cursor = "hover"; // uses the registered 'hover' style
```
Cursor styles can be strings (CSS cursor values), objects (applied as CSS styles), or functions (called with the mode string).
### Event properties
`FederatedPointerEvent` carries rich input data; the more useful fields are:
```ts
sprite.on("pointerdown", (event: FederatedPointerEvent) => {
event.global; // scene-space Point where the event happened
event.client; // CSS-pixel Point relative to the viewport
event.offset; // Point w.r.t. target Container in world space (not supported at the moment)
event.target; // the Container that received the event
event.currentTarget; // the Container whose listener is running
event.pointerType; // 'mouse' | 'pen' | 'touch'
event.pointerId; // unique id for multi-touch tracking
event.isPrimary; // first pointer in a multi-pointer gesture
event.persistentDeviceId; // always 0; present for DOM PointerEvent type compatibility
event.pressure; // 0-1 pen/touch pressure
event.button; // 0 left, 1 middle, 2 right
event.buttons; // bitmask of held buttons
event.altKey; // modifier key state
event.ctrlKey;
event.shiftKey;
event.metaKey;
event.nativeEvent; // the underlying DOM PointerEvent / MouseEvent / Touch
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
});
```
`FederatedWheelEvent` adds `deltaX`, `deltaY`, `deltaZ`, and `deltaMode`. Wheel events fire on the same hit-tested object as pointer events.
### Event features
Toggle event categories globally for performance:
```ts
await app.init({
eventFeatures: {
move: true, // pointer/mouse/touch move events
globalMove: true, // global move events (globalpointermove, etc.)
click: true, // click/tap/press and contextmenu events
wheel: true, // mouse wheel events
},
});
// or configure after init
app.renderer.events.features.globalMove = false;
```
### Performance tips
- Set `eventMode = 'none'` on non-interactive subtrees to skip hit testing entirely.
- Set `interactiveChildren = false` on containers where only the container itself needs interaction.
- Use `hitArea` on large or complex objects to replace bounds-based hit testing with a cheap shape check.
- Prefer `'static'` for stationary elements; reserve `'dynamic'` for objects that move or animate under a stationary pointer.
- Disable unused event features via `eventFeatures` (e.g., `globalMove: false`) to cut per-frame work.
## Common Mistakes
### [HIGH] Default eventMode is passive
Wrong:
```ts
const sprite = new Sprite(texture);
sprite.on("pointerdown", () => {
console.log("clicked");
});
```
Correct:
```ts
const sprite = new Sprite(texture);
sprite.eventMode = "static";
sprite.on("pointerdown", () => {
console.log("clicked");
});
```
The default `eventMode` is `'passive'`, which means the object itself receives no events. You must explicitly set `eventMode` to `'static'` or `'dynamic'` before any listener will fire.
### [HIGH] buttonMode removed; use cursor
Wrong:
```ts
sprite.interactive = true;
sprite.buttonMode = true;
```
Correct:
```ts
sprite.eventMode = "static";
sprite.cursor = "pointer";
```
`buttonMode` was removed in v8. Use `cursor = 'pointer'` to show a hand cursor on hover. `interactive = true` still works as an alias for `eventMode = 'static'`, but `eventMode` is preferred.
### [HIGH] Move events only fire over the object in v8
Wrong:
```ts
sprite.eventMode = "static";
sprite.on("pointermove", (event) => {
// expects to fire everywhere; only fires inside sprite bounds
updateDrag(event.global.x, event.global.y);
});
```
Correct:
```ts
sprite.eventMode = "static";
sprite.on("globalpointermove", (event) => {
// fires everywhere, even outside sprite bounds
updateDrag(event.global.x, event.global.y);
});
```
In v8, `pointermove`, `mousemove`, and `touchmove` only fire when the pointer is over the display object. In v7 they fired on any canvas move. For drag operations or global tracking, use `globalpointermove`, `globalmousemove`, or `globaltouchmove`.
### [MEDIUM] Cursor does not inherit from parent
Setting `cursor` on a parent container has no effect on its children. Only the direct hit target's `cursor` value is applied.
```ts
// This does NOT make children show a pointer cursor
parent.cursor = "pointer";
// Each interactive child needs its own cursor
child.eventMode = "static";
child.cursor = "pointer";
```
If you want a uniform cursor for all children, set `cursor` on each interactive child individually, or set `hitArea` on the parent and make children non-interactive.
## API Reference
- [EventSystem](https://pixijs.download/release/docs/events.EventSystem.html.md)
- [FederatedEvent](https://pixijs.download/release/docs/events.FederatedEvent.html.md)
- [FederatedPointerEvent](https://pixijs.download/release/docs/events.FederatedPointerEvent.html.md)
- [FederatedMouseEvent](https://pixijs.download/release/docs/events.FederatedMouseEvent.html.md)
- [FederatedWheelEvent](https://pixijs.download/release/docs/events.FederatedWheelEvent.html.md)
- [EventBoundary](https://pixijs.download/release/docs/events.EventBoundary.html.md)
+300
View File
@@ -0,0 +1,300 @@
---
name: pixijs-filters
description: "Use this skill when applying visual effects to PixiJS v8 containers via the filter pipeline. Covers built-in filters (AlphaFilter, BlurFilter, ColorMatrixFilter, DisplacementFilter, NoiseFilter), custom Filter.from() with GLSL/WGSL, options (resolution, padding, antialias, blendRequired), filterArea optimization, pixi-filters community package. Triggers on: filters, BlurFilter, ColorMatrixFilter, DisplacementFilter, NoiseFilter, Filter.from, GLSL filter, pixi-filters, filterArea."
license: MIT
---
Attach visual effects by assigning one filter (or an array for chaining) to `container.filters`. Built-in filters cover blur, color matrix, displacement, alpha, and noise; custom filters wrap a GLSL/WGSL fragment shader via `Filter.from(...)`.
## Quick Start
```ts
const sprite = new Sprite(await Assets.load("hero.png"));
app.stage.addChild(sprite);
const blur = new BlurFilter({ strength: 4, quality: 4 });
const colorMatrix = new ColorMatrixFilter();
colorMatrix.brightness(1.2, false);
sprite.filters = [blur, colorMatrix];
const container = new Container();
container.filters = [new BlurFilter({ strength: 2 })];
container.filterArea = new Rectangle(0, 0, 800, 600);
app.stage.addChild(container);
```
**Related skills:** `pixijs-custom-rendering` (shader internals, uniform types), `pixijs-blend-modes` (composing with filters), `pixijs-performance` (filter tuning, filterArea).
## Core Patterns
### Built-in filters
```ts
import {
AlphaFilter,
BlurFilter,
ColorMatrixFilter,
DisplacementFilter,
NoiseFilter,
Assets,
Sprite,
} from "pixi.js";
// Alpha (uniform transparency without per-child layering)
const alpha = new AlphaFilter({ alpha: 0.5 });
// Blur — strength/quality are uniform; strengthX/strengthY split axes;
// kernelSize must be odd (5, 7, 9, ... 15); repeatEdgePixels avoids transparent edges
const blur = new BlurFilter({
strength: 4,
quality: 4,
kernelSize: 5,
repeatEdgePixels: false,
});
// Color matrix — brightness is one of many presets. Others: tint, hue,
// contrast, saturate, desaturate, greyscale/grayscale, blackAndWhite,
// negative, sepia, technicolor, polaroid, kodachrome, browni, vintage,
// colorTone, night, predator, lsd, reset. Direct access via
// `colorMatrix.matrix` (20-element array) and `colorMatrix.alpha` (blend
// between original and transformed).
const colorMatrix = new ColorMatrixFilter();
colorMatrix.brightness(1.5, false);
colorMatrix.contrast(0.5, true); // multiply stacks on top of existing matrix
colorMatrix.alpha = 0.7; // blend at 70% strength
// Displacement — scale is a number or PointData
const displacementTexture = await Assets.load("displacement_map.png");
const displacementSprite = new Sprite(displacementTexture);
const displacement = new DisplacementFilter({
sprite: displacementSprite,
scale: { x: 20, y: 10 },
});
// Noise — seed is an arbitrary number that determines the noise pattern; same seed reproduces the same pattern
const noise = new NoiseFilter({ noise: 0.5, seed: Math.random() });
sprite.filters = [blur, colorMatrix];
```
### Custom filter with Filter.from()
The simplest way to create a custom filter. Only a fragment shader is needed; PixiJS provides a default vertex shader.
```ts
import { Filter } from "pixi.js";
const filter = Filter.from({
gl: {
fragment: `
in vec2 vTextureCoord;
out vec4 finalColor;
uniform sampler2D uTexture;
uniform float uTime;
void main() {
vec2 uv = vTextureCoord;
uv.x += sin(uv.y * 10.0 + uTime) * 0.02;
finalColor = texture(uTexture, uv);
}
`,
},
resources: {
timeUniforms: {
uTime: { value: 0, type: "f32" },
},
},
});
sprite.filters = filter;
app.ticker.add((ticker) => {
filter.resources.timeUniforms.uniforms.uTime += 0.04 * ticker.deltaTime;
});
```
For more control, construct `GlProgram`/`GpuProgram` objects directly:
```ts
import { Filter, GlProgram } from "pixi.js";
const glProgram = GlProgram.from({ fragment: fragmentSrc, vertex: vertexSrc });
const filter = new Filter({
glProgram,
resources: {
timeUniforms: {
uTime: { value: 0, type: "f32" },
},
},
});
```
Key points:
- Use `out vec4 finalColor` in fragment shaders, not `gl_FragColor` (GLSL ES 3.0).
- Use `texture()` to sample, not `texture2D`.
- `glProgram` for WebGL, `gpuProgram` for WebGPU. Omitting one skips that renderer.
- Textures go in `resources`, not uniforms. The filter system auto-provides `uTexture` (the input).
- Access uniform values via `filter.resources.{groupName}.uniforms.{name}`.
### Filter options
```ts
import { Filter, GlProgram, Rectangle } from "pixi.js";
const filter = new Filter({
glProgram: GlProgram.from({ fragment }),
resources: {},
resolution: 0.5, // default 1. Lower = faster, blurrier. 'inherit' matches the render target resolution
padding: 10, // default 0. Extra pixels for effects that extend bounds
antialias: "off", // default 'off'. 'on' | 'off' | 'inherit'
blendMode: "normal", // default 'normal'
blendRequired: false, // default false. true if shader samples uBackTexture
clipToViewport: true, // default true
});
// Optimization: set known bounds to avoid per-frame measurement
container.filterArea = new Rectangle(0, 0, 800, 600);
// Toggle without rebuilding the filter array
filter.enabled = false;
// Share one filter instance across many display objects
sprite1.filters = [filter];
sprite2.filters = [filter];
```
### Community filters (pixi-filters)
```ts
import { AdjustmentFilter } from "pixi-filters/adjustment";
import { GlowFilter } from "pixi-filters/glow";
sprite.filters = [
new AdjustmentFilter({ brightness: 1.2, contrast: 1.1 }),
new GlowFilter({ distance: 15, outerStrength: 2 }),
];
```
For v8, community filters use `pixi-filters/{name}` imports, not the old `@pixi/filter-*` packages.
### Advanced blend modes
Advanced blend modes (`color-burn`, `overlay`, `hard-light`, etc.) are powered by the filter system and must be imported before use. They also require `useBackBuffer: true` on WebGL; see the `pixijs-blend-modes` skill for the full list.
```ts
import "pixi.js/advanced-blend-modes";
await app.init({ useBackBuffer: true });
sprite.blendMode = "color-burn";
```
Advanced blend modes are filter-based, so they inherit `Filter.defaultOptions`, whose `resolution` defaults to `1`. On high-DPI render targets this can make a blend mode look clipped, scaled, or only partially applied. Set `Filter.defaultOptions.resolution = 'inherit'` before creating the affected objects to render at the render target resolution, at higher memory and runtime cost:
```ts
import { Filter } from "pixi.js";
import "pixi.js/advanced-blend-modes";
Filter.defaultOptions.resolution = "inherit";
sprite.blendMode = "overlay";
```
## Common Mistakes
### [CRITICAL] Using old Filter constructor (vertex, fragment, uniforms)
Wrong:
```ts
import { Filter } from "pixi.js";
const filter = new Filter(vertex, fragment, { uTime: 0 });
```
Correct:
```ts
import { Filter, GlProgram } from "pixi.js";
const filter = new Filter({
glProgram: GlProgram.from({ fragment, vertex }),
resources: {
timeUniforms: { uTime: { value: 0, type: "f32" } },
},
});
```
v8 uses an options object. Shaders must be wrapped in `GlProgram.from()` or `GpuProgram.from()`. Uniforms are grouped in `resources` with explicit types. Textures are resources, not uniforms.
### [HIGH] Using @pixi/filter-\* packages for v8
Wrong:
```ts
import { AdjustmentFilter } from "@pixi/filter-adjustment";
```
Correct:
```ts
import { AdjustmentFilter } from "pixi-filters/adjustment";
```
`@pixi/filter-*` packages are v7 only. For v8, the community filters package restructured to `pixi-filters/{name}`.
### [HIGH] Using too many filters without containerizing
Each filter application requires a framebuffer switch, bounds measurement, and render-to-texture pass. One filter on a parent container is much cheaper than the same filter on each child.
Wrong:
```ts
for (const child of container.children) {
child.filters = [new BlurFilter({ strength: 4 })];
}
```
Correct:
```ts
container.filters = [new BlurFilter({ strength: 4 })];
```
### [HIGH] Using a blendRequired filter without useBackBuffer on WebGL
Custom filters and most advanced community filters that set `blendRequired: true` sample the back buffer. On WebGL that only works if the renderer was initialized with `useBackBuffer: true`; otherwise PixiJS logs a warning and the filter silently falls back:
```ts
await app.init({ useBackBuffer: true });
```
WebGPU enables the back buffer unconditionally, so this only affects WebGL.
### [MEDIUM] Not setting filterArea for known-size containers
Without `filterArea`, PixiJS measures the container bounds every frame via `getGlobalBounds()`, which recursively walks all children. For containers with known dimensions, set `filterArea` to avoid this cost:
```ts
import { Rectangle } from "pixi.js";
container.filterArea = new Rectangle(0, 0, 800, 600);
container.filters = [someFilter];
```
## API Reference
- [Filter](https://pixijs.download/release/docs/filters.Filter.html.md)
- [AlphaFilter](https://pixijs.download/release/docs/filters.AlphaFilter.html.md)
- [BlurFilter](https://pixijs.download/release/docs/filters.BlurFilter.html.md)
- [BlurFilterPass](https://pixijs.download/release/docs/filters.BlurFilterPass.html.md)
- [ColorMatrixFilter](https://pixijs.download/release/docs/filters.ColorMatrixFilter.html.md)
- [DisplacementFilter](https://pixijs.download/release/docs/filters.DisplacementFilter.html.md)
- [NoiseFilter](https://pixijs.download/release/docs/filters.NoiseFilter.html.md)
- [FilterSystem](https://pixijs.download/release/docs/rendering.FilterSystem.html.md)
+228
View File
@@ -0,0 +1,228 @@
---
name: pixijs-html-source
description: "Use this skill when rendering live HTML/DOM elements (or frozen snapshots of them) as PixiJS v8 textures via the EXPERIMENTAL HTML-in-Canvas browser APIs. Covers the pixi.js/html-source import, feature detection with canvas.requestPaint, HTMLSource for a live, repainting, still-interactive element (autoLayout/autoUpdate/autoRequestPaint, requestPaint, isReady, HTMLSource.defaultOptions, the direct-child-of-canvas + layoutsubtree requirement), ElementImageSource for an immutable captureElementImage() snapshot (autoClose, ready immediately), using the source on a Sprite/Texture/Mesh, fallback-only auto-detection via Texture.from at priority -10, uploader error messages, and destroy/cleanup. Triggers on: HTMLSource, ElementImageSource, ElementImage, HTML in canvas, render DOM to texture, render HTML to texture, texElementImage2D, copyElementImageToTexture, HTMLSourceOptions, ElementImageSourceOptions, HTMLSourceCanvas."
license: MIT
---
`HTMLSource` and `ElementImageSource` turn a DOM element into a `TextureSource` you can use anywhere a normal texture works: on a `Sprite`, as a `Texture` frame, or mapped onto a `Mesh`. `HTMLSource` mirrors a live element's pixels into the GPU (the element stays editable and clickable in the browser); `ElementImageSource` wraps an immutable snapshot that never repaints. Both live in `pixi.js/html-source`; importing from that path registers their extensions.
> These sources rely on the experimental HTML-in-Canvas browser proposal and are marked EXPERIMENTAL in PixiJS v8. The browser API must be enabled or the texture uploader throws on first render; feature-detect with `canvas.requestPaint` before relying on it. The API may change between minor releases.
Assumes familiarity with `pixijs-scene-sprite` and textures. These are texture *sources*, not display objects: wrap them in a `Sprite` (or `Texture`/`Mesh`) to put them on screen. Not available in Web Workers; a worker has no DOM to capture.
## Quick Start
```ts
import { Application, Sprite } from "pixi.js";
import { HTMLSource } from "pixi.js/html-source";
const app = new Application();
await app.init({ resizeTo: window });
document.body.appendChild(app.canvas);
// The element must be a direct child of the Pixi canvas.
const form = document.createElement("form");
form.innerHTML = '<input value="still editable" />';
app.canvas.appendChild(form);
// Render the live form as a sprite. It stays interactive in the browser.
const source = new HTMLSource({ resource: form });
const sprite = Sprite.from(source);
sprite.anchor.set(0.5);
sprite.position.set(app.screen.width / 2, app.screen.height / 2);
app.stage.addChild(sprite);
```
**Related skills:** `pixijs-scene-sprite` (display the texture), `pixijs-scene-mesh` (map onto geometry, `PerspectiveMesh`), `pixijs-scene-dom-container` (the opposite: overlay HTML *above* the canvas, outside the GPU pipeline), `pixijs-assets` (texture sources vs the loader/cache), `pixijs-environments` (no DOM in Web Workers).
## Constructor options
Both sources extend `TextureSource`, so all `TextureSourceOptions` (`resolution`, `scaleMode`, `addressMode`, `label`, etc.) are valid. `resource` is required on each.
`HTMLSourceOptions` (live element):
| Option | Type | Default | Description |
| ------------------ | ------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `resource` | `Element` | — | Required. The live DOM element to render. Must be a direct child of the owning canvas, or the constructor throws. |
| `canvas` | `HTMLSourceCanvas` | — | The canvas that owns the element's layout subtree. Inferred from `resource.parentElement` when the element is a direct canvas child; pass it when inference is not possible. |
| `autoLayout` | `boolean` | `true` | Set the `layoutsubtree` attribute on the owning canvas. The browser only lays out and paints canvas children when it is present. Set `false` if you write `<canvas layoutsubtree>` yourself. |
| `autoUpdate` | `boolean` | `true` | Listen for the canvas `paint` event and re-upload when the element repaints. Set `false` for a static, captured-once texture. |
| `autoRequestPaint` | `boolean` | `true` | Request one initial paint after construction. Set `false` and call `source.requestPaint()` yourself each frame for continuous animation. |
`ElementImageSourceOptions` (immutable snapshot):
| Option | Type | Default | Description |
| ------------ | -------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `resource` | `ElementImage` | — | Required. A snapshot from `canvas.captureElementImage(element)`. |
| `autoClose` | `boolean` | `false` | Call `snapshot.close()` when the source is destroyed. Leave `false` when the snapshot is shared with other sources, or you risk a use-after-free. |
Change the defaults for every `HTMLSource` through the static `HTMLSource.defaultOptions` object, for example `HTMLSource.defaultOptions.autoUpdate = false`.
## Core Patterns
### Setup and the side-effect import
```ts
import "pixi.js/html-source";
import { HTMLSource, ElementImageSource } from "pixi.js/html-source";
```
`pixi.js/html-source` calls `extensions.add(...)` to register `HTMLSource`, `ElementImageSource`, and their WebGL/WebGPU uploaders. Without it, the renderer has no `'html'` uploader and these sources never render. The classes are exported from `pixi.js/html-source`, not `pixi.js`.
Importing a named export from `pixi.js/html-source` also triggers the side effect, so a bare `import 'pixi.js/html-source'` is only needed when you don't import anything else from that path.
### Feature detection and browser support
The HTML-in-Canvas API is gated behind a browser flag. Feature-detect before relying on it:
```ts
import type { HTMLSourceCanvas } from "pixi.js/html-source";
const canvas = app.canvas as HTMLSourceCanvas;
if (canvas.requestPaint) {
// HTML-in-Canvas is available.
}
```
Cast `app.canvas` to `HTMLSourceCanvas` for the typed `requestPaint` and `captureElementImage` members. `source.requestPaint()` returns `false` when the browser lacks the API; the texture uploader throws on first render when it is disabled.
When the API is missing the first upload throws `[HTMLSource] WebGLRenderingContext.texElementImage2D is not available...` on WebGL or `[HTMLSource] GPUQueue.copyElementImageToTexture is not available...` on WebGPU.
### Live element with HTMLSource
```ts
const form = document.createElement("form");
app.canvas.appendChild(form); // direct child of the canvas
const source = new HTMLSource({ resource: form });
const sprite = Sprite.from(source);
```
The element must be a direct child of the renderer's `<canvas>`; the source infers the owning canvas from `resource.parentElement` (or pass `canvas`). With the defaults, it sets `layoutsubtree` on the canvas, listens for the canvas `paint` event, and requests one initial paint. `source.isReady` is `false` until that first paint lands, then `true`. It is `true` immediately when `autoUpdate` is `false`. `resourceWidth`/`resourceHeight` report the element's real-pixel size (`offsetWidth`/`offsetHeight`).
### Continuous animation with requestPaint
```ts
const source = new HTMLSource({ resource: clock, autoRequestPaint: false });
const sprite = Sprite.from(source);
app.ticker.add(() => {
clock.textContent = new Date().toLocaleTimeString();
source.requestPaint(); // re-snapshot the DOM this frame
});
```
The browser only repaints canvas children on demand. For an element whose content changes every frame, set `autoRequestPaint: false` and call `source.requestPaint()` in your own ticker to drive repaints on your schedule.
### Immutable snapshot with ElementImageSource
```ts
import { ElementImageSource } from "pixi.js/html-source";
import type { HTMLSourceCanvas } from "pixi.js/html-source";
const canvas = app.canvas as HTMLSourceCanvas;
const snapshot = canvas.captureElementImage!(element);
const source = new ElementImageSource({ resource: snapshot, autoClose: true });
const sprite = Sprite.from(source);
```
`captureElementImage()` freezes an element's current pixels into an immutable `ElementImage`. There is no owning canvas, no `paint` listener, and no repaint lifecycle, so the source is ready the moment it is constructed. Reach for it when you need a frozen copy that outlives its element or is transferred around (transitions, "shatter" or trail effects). Release the snapshot with `snapshot.close()` when done, or pass `autoClose: true` to let the source close it on `destroy()`.
### Using the source on a sprite, texture, or mesh
Both sources are normal `TextureSource`s. Wrap them with `Sprite.from(source)` / `Texture.from(source)`, frame or slice them into sub-textures, or map them onto a mesh:
```ts
import { Rectangle, Texture } from "pixi.js";
// A 64x64 slice of the rendered element.
const chunk = new Texture({
source,
frame: new Rectangle(0, 0, 64, 64),
});
// Mapped onto geometry (e.g. a perspective warp).
const mesh = new PerspectiveMesh({ texture: Texture.from(source) /* ... */ });
```
### Auto-detection and priority
```ts
// Resolves to an HTMLSource (element) or ElementImageSource (snapshot) only as a last resort.
const sprite = Sprite.from(elementAlreadyInTheCanvas);
```
A generic HTML element or an `ElementImage` passed to `Texture.from`/`Sprite.from` resolves to these sources at the lowest texture-source priority (`-10`), so they only claim a resource no other built-in source handles. Image, video, and canvas elements are deliberately rejected; they have dedicated, faster sources. Construct the source explicitly when you need options (`autoUpdate`, `autoClose`) or non-HTML elements such as SVG.
## Common Mistakes
### [HIGH] Importing from pixi.js instead of pixi.js/html-source
Wrong:
```ts
import { HTMLSource } from "pixi.js"; // not exported from the core entry
```
Correct:
```ts
import { HTMLSource } from "pixi.js/html-source";
```
`HTMLSource`, `ElementImageSource`, and the `'html'` uploaders live only in `pixi.js/html-source`. Importing anything from that path registers the extensions; the module is marked side-effectful, so bundlers keep the registration even when you only import a class.
### [HIGH] Assuming the browser API is enabled
The HTML-in-Canvas proposal is not shipped by default. If the API is disabled, the uploader throws on first render. Feature-detect first:
```ts
const canvas = app.canvas as HTMLSourceCanvas;
if (!canvas.requestPaint) {
// Fall back to a static image, DOMContainer overlay, or a message.
}
```
### [MEDIUM] Element not a direct child of the canvas
```ts
document.body.appendChild(form); // wrong parent
const source = new HTMLSource({ resource: form }); // throws
```
`HTMLSource` requires the element to be a direct child of the owning canvas (`app.canvas.appendChild(form)`) and throws otherwise. Append the element to the canvas before constructing the source, or pass the `canvas` option.
### [MEDIUM] Expecting a live element to update without requestPaint
A non-animating element updates automatically on browser `paint` events (`autoUpdate: true`). Content that changes every frame will not re-upload unless something triggers a paint; drive it with `source.requestPaint()` each frame (with `autoRequestPaint: false`).
### [MEDIUM] Closing an ElementImage still in use
```ts
const source = new ElementImageSource({ resource: snapshot, autoClose: true });
const other = new ElementImageSource({ resource: snapshot }); // shares the snapshot
source.destroy(); // closes the snapshot — `other` is now a use-after-free
```
Only set `autoClose: true` when the source owns the snapshot exclusively. For a shared snapshot, leave `autoClose` off and call `snapshot.close()` once, after the last source is destroyed.
## Cleanup
```ts
source.destroy();
```
`HTMLSource.destroy()` detaches the canvas `paint` listener and nulls its canvas reference. `ElementImageSource.destroy()` closes the snapshot when `autoClose` was set; otherwise call `snapshot.close()` yourself to release the memory.
## API Reference
- [HTMLSource](https://pixijs.download/release/docs/rendering.HTMLSource.html.md)
- [HTMLSourceOptions](https://pixijs.download/release/docs/rendering.HTMLSourceOptions.html.md)
- [ElementImageSource](https://pixijs.download/release/docs/rendering.ElementImageSource.html.md)
- [ElementImageSourceOptions](https://pixijs.download/release/docs/rendering.ElementImageSourceOptions.html.md)
- [HTMLSourceCanvas](https://pixijs.download/release/docs/rendering.HTMLSourceCanvas.html.md)
- [ElementImage](https://pixijs.download/release/docs/rendering.ElementImage.html.md)
+489
View File
@@ -0,0 +1,489 @@
---
name: pixijs-math
description: "Use this skill when working with coordinates, vectors, matrices, shapes, hit testing, or layout rectangles in PixiJS v8. Covers Point/ObservablePoint, Matrix (2D affine, decompose (including mirrored/negative-scale matrices), apply, applyInverse), shapes (Rectangle, Circle, Ellipse, Polygon, RoundedRectangle, Triangle), Rectangle layout helpers (pad, fit, enlarge, ceil, scale, getBounds), strokeContains hit tests, Polygon isClockwise/containsPolygon, toGlobal/toLocal, PointData/PointLike/Size types, DEG_TO_RAD, and pixi.js/math-extras vector and intersection helpers. Triggers on: Point, ObservablePoint, Matrix, Rectangle, Circle, Polygon, Triangle, RoundedRectangle, toGlobal, toLocal, hitArea, strokeContains, pad, fit, enlarge, ceil, getBounds, containsRect, intersects, isClockwise, math-extras, lineIntersection, segmentIntersection, DEG_TO_RAD, PointData, decompose, mirror, flip, negative scale, setFromMatrix."
license: MIT
---
PixiJS exposes lightweight math primitives (Point, Matrix, shape classes) used throughout the library for transforms, hit testing, and coordinate conversion. Import `pixi.js/math-extras` to add vector operations (add, dot, magnitude, reflect) and Rectangle intersection/union helpers.
## Quick Start
```ts
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
app.stage.addChild(parent);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
const globalPt = child.toGlobal(new Point(0, 0));
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
const world = m.apply(new Point(10, 20));
const hitArea = new Rectangle(0, 0, 200, 100);
console.log(hitArea.contains(50, 50));
```
**Related skills:** `pixijs-scene-container` (transform properties), `pixijs-events` (hitArea usage), `pixijs-scene-core-concepts` (culling with Rectangle).
## Core Patterns
### Point and ObservablePoint
Point is a simple {x, y} value type. ObservablePoint fires a callback when x or y changes; it is used internally by Container's position, scale, pivot, origin, and skew.
```ts
import { Point } from "pixi.js";
const p = new Point(10, 20);
p.set(30, 40); // set both
p.set(50); // x=50, y=50
const clone = p.clone();
console.log(p.equals(clone)); // true
p.copyFrom({ x: 1, y: 2 }); // accepts any PointData
// Point.shared: temporary point, reset to (0,0) on each access
const temp = Point.shared;
temp.set(100, 200);
// do not store a reference to Point.shared
```
Container properties like `position`, `scale`, `pivot`, `origin`, and `skew` are ObservablePoints. Setting `.x` or `.y` on them triggers transform recalculation automatically.
```ts
import { Container } from "pixi.js";
const obj = new Container();
obj.position.set(100, 200); // triggers observer -> marks transform dirty
obj.position.x = 150; // also triggers observer
```
### Matrix (2D affine transform)
Matrix represents a 3x3 affine transform: `| a c tx | b d ty | 0 0 1 |`. It supports translate, scale, rotate, append, prepend, invert, and decompose.
```ts
import { Matrix, Point } from "pixi.js";
// Build a transform
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
// Transform a point (local -> parent space)
const local = new Point(10, 20);
const world = m.apply(local);
// Inverse transform (parent -> local space)
const backToLocal = m.applyInverse(world);
// Combine matrices
const a = new Matrix().translate(50, 0);
const b = new Matrix().rotate(Math.PI / 2);
a.append(b); // a = a * b
// Decompose into position/scale/rotation/skew
const transform = {
position: new Point(),
scale: new Point(),
pivot: new Point(),
skew: new Point(),
rotation: 0,
};
m.decompose(transform);
console.log(transform.rotation); // ~0.785 (PI/4)
// A mirrored matrix (one axis flipped, axes still perpendicular) decomposes into
// rotation + negative scale.x with zero skew. scale.y is never negative: a y-axis
// flip comes back as scale.x = -1 plus a half turn. Either way the parts rebuild the matrix.
const mirrored = new Matrix().rotate(Math.PI / 6).scale(-1, 1);
mirrored.decompose(transform);
transform.scale.x; // -1
transform.skew.x; // 0
// Shared temporary matrix (reset on each access)
const temp = Matrix.shared;
// IDENTITY is read-only reference
const isDefault = m.equals(Matrix.IDENTITY);
```
### Coordinate transforms via Container
Containers provide `toGlobal`, `toLocal`, and `getGlobalPosition` for coordinate conversion.
```ts
import { Container, Point } from "pixi.js";
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
// Local point in child's space -> global (world) space
const globalPt = child.toGlobal(new Point(0, 0));
// globalPt = { x: 200, y: 200 } (100 + 50*2, 100 + 50*2)
// Global point -> child's local space
const localPt = child.toLocal(new Point(200, 200));
// localPt = { x: 0, y: 0 }
// Convert between two containers
const other = new Container();
other.position.set(300, 300);
const ptInOther = child.toLocal(new Point(10, 10), other);
```
### Shapes and hit testing
Rectangle, Circle, Ellipse, Polygon, RoundedRectangle, and Triangle all implement `contains(x, y)` for point-in-shape tests, plus `getBounds(out?)` and `strokeContains(x, y, width, alignment?)` (`Triangle` ignores `alignment` and always tests a centered stroke). They can be used as `hitArea` on containers for custom interaction regions.
```ts
import { Rectangle, Circle, Ellipse, Polygon, Container } from "pixi.js";
const rect = new Rectangle(0, 0, 200, 100);
rect.contains(50, 50); // true
rect.contains(300, 50); // false
rect.left; // 0
rect.right; // 200
rect.top; // 0
rect.bottom; // 100
rect.isEmpty(); // false (Rectangle.EMPTY returns a fresh empty rect)
// Native Rectangle-to-Rectangle methods (no math-extras needed)
const other = new Rectangle(50, 50, 100, 100);
rect.containsRect(other); // true if `other` is fully inside `rect`
rect.containsRect(new Rectangle(100, 0, 100, 100)); // true: a flush right edge counts
rect.containsRect(rect.clone()); // true: identical rects contain each other
rect.intersects(other); // boolean: do they overlap at all?
rect.intersects(other, matrix); // overlap after transforming `other`
// Stroke hit testing (alignment: 1 = inner, 0.5 = centered, 0 = outer)
rect.strokeContains(0, 50, 4); // true if (0,50) lies on a 4px centered stroke
const circle = new Circle(100, 100, 50);
circle.strokeContains(150, 100, 4, 1); // inner-aligned stroke check
// A stroke that reaches past the shape's centre covers the whole interior; there is no hole
new Ellipse(0, 0, 10, 10).strokeContains(0, 0, 40, 1); // true
// getBounds works on every shape (returns a Rectangle, accepts an out param)
const bounds = circle.getBounds();
const reused = new Rectangle();
new Polygon([0, 0, 100, 0, 50, 100]).getBounds(reused);
// Use as hit area for interaction
const button = new Container();
button.hitArea = new Rectangle(0, 0, 200, 50);
button.eventMode = "static";
button.on("pointerdown", () => {
/* clicked */
});
```
Do not confuse native `Rectangle.intersects(other)` (returns `boolean`) with math-extras `intersection(other)` (returns a `Rectangle` describing the overlap area).
### Rectangle layout helpers
Rectangle ships with mutating helpers used heavily in UI/layout, bounds aggregation, and pixel snapping. All return `this` for chaining.
```ts
import { Rectangle } from "pixi.js";
const r = new Rectangle(10, 10, 100, 50);
r.pad(5); // grow on all sides: x=5, y=5, w=110, h=60
r.pad(10, 4); // separate horizontal/vertical padding
r.scale(2); // multiply x, y, width, height by 2
// fit shrinks `this` to lie inside another rect (clipping)
const viewport = new Rectangle(0, 0, 200, 200);
new Rectangle(150, 150, 200, 200).fit(viewport); // -> 150, 150, 50, 50
// enlarge expands `this` to include another rect (bounds aggregation)
const total = new Rectangle();
items.forEach((item) =>
total.enlarge(new Rectangle().copyFromBounds(item.getBounds())),
);
// ceil snaps to a pixel grid (resolution: 1 = whole pixels, 2 = half pixels)
new Rectangle(10.2, 10.6, 100.8, 100.4).ceil();
// copy a Container/Mesh bounds object straight into a Rectangle
new Rectangle().copyFromBounds(container.getBounds());
```
### Polygon
Polygon accepts four constructor formats: a flat number array, an array of point-like objects, or either passed as spread arguments.
```ts
import { Polygon, Point } from "pixi.js";
new Polygon([0, 0, 100, 0, 50, 100]); // flat numbers
new Polygon([new Point(0, 0), new Point(100, 0), new Point(50, 100)]); // PointData[]
new Polygon(0, 0, 100, 0, 50, 100); // spread numbers
new Polygon(new Point(0, 0), new Point(100, 0), new Point(50, 100)); // spread points
const poly = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
poly.points; // [0, 0, 100, 0, 100, 100, 0, 100] (mutable flat array)
poly.closePath; // true by default; false produces an open path
poly.startX; // 0 - first vertex
poly.lastX; // 0 - last vertex (lastY for y)
poly.isClockwise(); // shoelace winding test (useful for SVG hole detection)
// Polygon-in-polygon containment for hole detection
const outer = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
const hole = new Polygon([25, 25, 75, 25, 75, 75, 25, 75]);
outer.containsPolygon(hole); // true
// Stroke hit test follows the drawn stroke: alignment 1 = inside, 0.5 = centered,
// 0 = outside, independent of winding order
outer.strokeContains(-5, 50, 20); // true (centered stroke extends 10px outward)
outer.strokeContains(-5, 50, 20, 1); // false (inner stroke stays inside)
outer.strokeContains(5, 50, 20, 0); // false (outer stroke stays outside)
```
### Constants
```ts
import { DEG_TO_RAD, RAD_TO_DEG, PI_2 } from "pixi.js";
const angle = 45 * DEG_TO_RAD; // 0.785...
const degrees = angle * RAD_TO_DEG; // 45
const fullCircle = PI_2; // Math.PI * 2
```
### Types
- `PointData` - minimal `{x, y}` interface accepted by most APIs. Use it when typing parameters that only need to read coordinates.
- `PointLike` - extends `PointData` with `set()`, `copyFrom()`, `copyTo()`, `equals()`. Implemented by both `Point` and `ObservablePoint`.
- `Size` - `{ width, height }` interface used by renderer/canvas APIs.
- `SHAPE_PRIMITIVE` - string literal union: `'rectangle' | 'circle' | 'ellipse' | 'polygon' | 'roundedRectangle' | 'triangle'`. Every shape exposes `type` so you can branch without `instanceof`.
```ts
import type { PointData } from "pixi.js";
function distance(a: PointData, b: PointData): number {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
```
### math-extras (side-effect import)
`import 'pixi.js/math-extras'` adds methods to Point, ObservablePoint, and Rectangle via prototype extension. Not included in the default bundle.
```ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";
```
#### Point / ObservablePoint vector methods
All methods accept an optional `out` parameter to avoid allocations. Without `out`, a new Point is returned.
```ts
const a = new Point(3, 4);
const b = new Point(1, 2);
// Arithmetic
const sum = a.add(b); // Point(4, 6)
const diff = a.subtract(b); // Point(2, 2)
const prod = a.multiply(b); // Point(3, 8) - component-wise
const scaled = a.multiplyScalar(2); // Point(6, 8)
// Dot and cross product
const dot = a.dot(b); // 11
const cross = a.cross(b); // 2 (z-component of 3D cross)
// Length
const len = a.magnitude(); // 5
const lenSq = a.magnitudeSquared(); // 25 (faster for comparisons)
// Normalize to unit vector
const unit = a.normalize(); // Point(0.6, 0.8)
// Projection and reflection
const proj = a.project(b); // project a onto b
const refl = a.reflect(new Point(0, 1)); // reflect across normal
// Rotation
const rotated = a.rotate(Math.PI / 2); // rotate 90 degrees
// Reuse existing point to avoid allocation
const out = new Point();
a.add(b, out); // result written to out
```
#### Rectangle extended methods
`containsRect` and `intersects` are native `Rectangle` methods (see above). math-extras adds `equals`, `intersection` (returns the overlap rect), and `union`:
```ts
import "pixi.js/math-extras";
import { Rectangle } from "pixi.js";
const r1 = new Rectangle(0, 0, 100, 100);
const r2 = new Rectangle(50, 50, 100, 100);
r1.equals(r2); // false
const overlap = r1.intersection(r2); // Rectangle(50, 50, 50, 50)
const envelope = r1.union(r2); // Rectangle(0, 0, 150, 150)
// Optional out parameter
const out = new Rectangle();
r1.intersection(r2, out);
```
#### Geometry utility functions
These functions are exported from `pixi.js/math-extras`, not the main `pixi.js` entry.
```ts
import {
floatEqual,
lineIntersection,
segmentIntersection,
} from "pixi.js/math-extras";
import { Point } from "pixi.js";
// Epsilon-based float comparison (default epsilon: Number.EPSILON)
floatEqual(0.1 + 0.2, 0.3, 1e-10); // true with reasonable epsilon
floatEqual(1.0, 1.001, 0.01); // true (custom epsilon)
// Unbounded line intersection (returns {x: NaN, y: NaN} if parallel)
const hit = lineIntersection(
new Point(0, 0),
new Point(10, 10), // line A
new Point(10, 0),
new Point(0, 10), // line B
); // Point(5, 5)
if (isNaN(hit.x)) {
/* lines are parallel */
}
// Bounded segment intersection (returns {x: NaN, y: NaN} if segments don't cross)
const segHit = segmentIntersection(
new Point(0, 0),
new Point(10, 10),
new Point(10, 0),
new Point(0, 10),
); // Point(5, 5)
if (isNaN(segHit.x)) {
/* segments don't intersect */
}
```
## Common Mistakes
### HIGH: Importing from @pixi/math
Wrong:
```ts
import { Point } from "@pixi/math";
```
Correct:
```ts
import { Point } from "pixi.js";
```
v8 uses a single `pixi.js` package. All sub-packages like `@pixi/math`, `@pixi/core`, etc. were removed.
### MEDIUM: Mutating ObservablePoint without triggering observer
Wrong:
```ts
// Replacing the reference loses observation
let pos = container.position;
pos = new Point(100, 200); // container.position unchanged
```
Correct:
```ts
// Mutate in place to trigger the observer
container.position.set(100, 200);
// or
container.position.x = 100;
container.position.y = 200;
// or copy from another point
container.position.copyFrom(new Point(100, 200));
```
Container's position, scale, pivot, origin, and skew are ObservablePoints. Setting `.x` or `.y` on them triggers the container's transform update. Reassigning the variable reference does not modify the container. Always mutate the existing ObservablePoint via `.set()`, `.copyFrom()`, or direct property assignment on the original object.
### MEDIUM: Not importing math-extras for extended methods
Wrong:
```ts
import { Point } from "pixi.js";
const p = new Point(1, 2);
p.add(new Point(3, 4)); // TypeError: p.add is not a function
```
Correct:
```ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";
const p = new Point(1, 2);
const sum = p.add(new Point(3, 4)); // works
```
Extended math utilities (add, subtract, multiply, magnitude, normalize, dot, cross, etc. on Point; intersection methods on shapes) require an explicit `import 'pixi.js/math-extras'`. These are not included in the default bundle.
### MEDIUM: Storing references to shared/temporary objects
Wrong:
```ts
const myPoint = Point.shared;
myPoint.set(100, 200);
// ... later ...
console.log(myPoint.x); // 0 (reset on next access)
```
Correct:
```ts
const myPoint = new Point();
myPoint.copyFrom(Point.shared.set(100, 200));
// or just
const myPoint = new Point(100, 200);
```
`Point.shared` and `Matrix.shared` are reset to zero/identity every time they are accessed. They exist for one-off calculations within a single expression. Never store a reference to them.
## API Reference
- [Point](https://pixijs.download/release/docs/maths.Point.html.md)
- [ObservablePoint](https://pixijs.download/release/docs/maths.ObservablePoint.html.md)
- [Matrix](https://pixijs.download/release/docs/maths.Matrix.html.md)
- [Rectangle](https://pixijs.download/release/docs/maths.Rectangle.html.md)
- [Circle](https://pixijs.download/release/docs/maths.Circle.html.md)
- [Ellipse](https://pixijs.download/release/docs/maths.Ellipse.html.md)
- [Polygon](https://pixijs.download/release/docs/maths.Polygon.html.md)
- [RoundedRectangle](https://pixijs.download/release/docs/maths.RoundedRectangle.html.md)
- [Triangle](https://pixijs.download/release/docs/maths.Triangle.html.md)
- [DEG_TO_RAD](https://pixijs.download/release/docs/maths.DEG_TO_RAD.html.md)
+415
View File
@@ -0,0 +1,415 @@
---
name: pixijs-migration-v8
description: "Use this skill when upgrading to PixiJS v8 from v7 or diagnosing broken v7 code after an upgrade. Covers async app.init, single pixi.js package (deprecated @pixi/* sub-packages), Graphics shape-then-fill, BaseTexture → TextureSource, shader/uniform rework, ParticleContainer+Particle, constructor options objects, DisplayObject removal, settings/utils removal, Ticker signature, events rewrite. Triggers on: migrate v7, v8 breaking changes, @pixi/ import, DisplayObject, beginFill, endFill, cacheAsBitmap, BaseTexture, deprecated."
license: MIT
---
This skill is a breaking-change checklist for bringing a v7 codebase up to v8. Work top-down through the categories; the list maps each v7 pattern to its v8 replacement.
## Quick Start
Install the single package, then port in this order: imports → Application init → Graphics → Text → events → shaders/filters → cleanup.
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
const g = new Graphics()
.rect(0, 0, 100, 100)
.fill({ color: 0xff0000 })
.stroke({ width: 2, color: 0x000000 });
app.stage.addChild(g);
```
**Related skills:** `pixijs-application` (async init), `pixijs-scene-graphics` (new fill/stroke API), `pixijs-custom-rendering` (shader rework), `pixijs-scene-text` (Text constructor changes), `pixijs-performance` (destroy patterns).
## Migration Checklist: v7 to v8
Work through each category. Each item shows the expected v8 pattern and the v7 pattern that must be replaced.
### Initialization
**Async app.init()** -- Expected:
```ts
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
```
Fail: passing options to `new Application({...})` and using synchronously.
**app.canvas replaces app.view** -- `app.view` emits a deprecation warning.
**Application type parameter** -- Expected: `new Application<Renderer<HTMLCanvasElement>>()`. Fail: `new Application<HTMLCanvasElement>()`.
### Imports
**Single package** -- Expected:
```ts
import { Sprite, Application, Assets, Graphics } from "pixi.js";
```
Fail: importing from any of the deprecated v7 core `@pixi/*` sub-packages (see list below). Supplemental packages like `@pixi/sound` are still valid and should continue to be used.
Deprecated `@pixi/*` packages (never use, any version):
`@pixi/accessibility`, `@pixi/app`, `@pixi/assets`, `@pixi/compressed-textures`, `@pixi/core`, `@pixi/display`, `@pixi/events`, `@pixi/extensions`, `@pixi/extract`, `@pixi/filter-alpha`, `@pixi/filter-blur`, `@pixi/filter-color-matrix`, `@pixi/filter-displacement`, `@pixi/filter-fxaa`, `@pixi/filter-noise`, `@pixi/graphics`, `@pixi/mesh`, `@pixi/mesh-extras`, `@pixi/mixin-cache-as-bitmap`, `@pixi/mixin-get-child-by-name`, `@pixi/mixin-get-global-position`, `@pixi/particle-container`, `@pixi/prepare`, `@pixi/sprite`, `@pixi/sprite-animated`, `@pixi/sprite-tiling`, `@pixi/spritesheet`, `@pixi/text`, `@pixi/text-bitmap`, `@pixi/text-html`.
**Custom builds** -- Set `skipExtensionImports: true` and import only needed extensions:
```ts
import "pixi.js/graphics";
import "pixi.js/text";
import "pixi.js/events";
import { Application } from "pixi.js";
await app.init({ skipExtensionImports: true });
```
Note: `manageImports: false` is still accepted but `@deprecated since 8.1.6`; prefer `skipExtensionImports: true`.
**Extensions not auto-imported** (require explicit import even with default auto-imports enabled):
`pixi.js/advanced-blend-modes`, `pixi.js/unsafe-eval`, `pixi.js/prepare`, `pixi.js/math-extras`, `pixi.js/dds`, `pixi.js/ktx`, `pixi.js/ktx2`, `pixi.js/basis`.
**Community filters** -- Expected: `import { AdjustmentFilter } from 'pixi-filters/adjustment'`. Fail: `@pixi/filter-adjustment`.
### Graphics API
**Shape-then-fill** -- Expected:
```ts
const g = new Graphics().rect(50, 50, 100, 100).fill(0xff0000);
```
Fail: `beginFill(0xff0000).drawRect(50, 50, 100, 100).endFill()`.
**Renamed shape methods:**
| v7 | v8 |
| -------------------- | ------------- |
| `drawRect` | `rect` |
| `drawCircle` | `circle` |
| `drawEllipse` | `ellipse` |
| `drawPolygon` | `poly` |
| `drawRoundedRect` | `roundRect` |
| `drawStar` | `star` |
| `drawRegularPolygon` | `regularPoly` |
| `drawRoundedPolygon` | `roundPoly` |
| `drawRoundedShape` | `roundShape` |
| `drawChamferRect` | `chamferRect` |
| `drawFilletRect` | `filletRect` |
**Fill replaces beginFill/beginTextureFill** -- Expected:
```ts
graphics
.rect(0, 0, 100, 100)
.fill({ texture: Texture.WHITE, alpha: 0.5, color: 0xff0000 });
```
Fail: `beginFill(color, alpha)` or `beginTextureFill({ texture, alpha, color })`.
**Stroke replaces lineStyle** -- Expected:
```ts
graphics.rect(0, 0, 100, 100).fill("blue").stroke({ width: 2, color: "white" });
```
Fail: `lineStyle(2, 'white')` or `lineTextureStyle({ texture, width, color })`.
**Holes use cut()** -- Expected:
```ts
graphics.rect(0, 0, 100, 100).fill(0x00ff00).circle(50, 50, 20).cut();
```
Fail: `beginHole()` / `endHole()`.
**GraphicsContext replaces GraphicsGeometry** -- Expected:
```ts
const context = new GraphicsContext().rect(0, 0, 100, 100).fill(0xff0000);
const g1 = new Graphics(context);
const g2 = new Graphics(context);
```
Fail: `new Graphics(graphics.geometry)`.
### Text
**Options object constructor** -- Expected:
```ts
const text = new Text({ text: "Hello", style: { fontSize: 24 } });
const bmp = new BitmapText({ text: "Hello", style: { fontFamily: "MyFont" } });
const html = new HTMLText({ text: "<b>Hello</b>", style: { fontSize: 24 } });
```
Fail: `new Text('Hello', { fontSize: 24 })` (positional args).
**Bitmap font loading** -- Must `import 'pixi.js/text-bitmap'` before `Assets.load('font.fnt')`.
### Sprites / Mesh
**Texture.from no longer loads URLs** -- Must call `await Assets.load('image.png')` first, then `Texture.from('image.png')`.
**NineSliceSprite replaces NineSlicePlane** -- Expected:
```ts
const ns = new NineSliceSprite({
texture,
leftWidth: 10,
topHeight: 10,
rightWidth: 10,
bottomHeight: 10,
});
```
**Mesh renames:** `SimpleMesh` -> `MeshSimple`, `SimplePlane` -> `MeshPlane`, `SimpleRope` -> `MeshRope`. All use options objects.
**MeshGeometry options** -- Expected:
```ts
const geom = new MeshGeometry({
positions: vertices,
uvs,
indices,
topology: "triangle-list",
});
```
Fail: `new MeshGeometry(vertices, uvs, indices)`.
**ParticleContainer uses Particle** -- Expected:
```ts
const container = new ParticleContainer({
boundsArea: new Rectangle(0, 0, 800, 600),
});
const particle = new Particle(texture);
container.addParticle(particle);
```
Fail: `container.addChild(new Sprite(texture))`.
### Events
**eventMode replaces interactive** -- Expected:
```ts
sprite.eventMode = "static";
sprite.cursor = "pointer";
sprite.on("pointertap", () => {
/* handle */
});
```
Legacy: `sprite.interactive = true;` (still works as an alias for `eventMode = 'static'`, but prefer the explicit form).
Default `eventMode` is `'passive'` (no events). Must set `'static'` or `'dynamic'` explicitly.
**Ticker callback** -- Expected:
```ts
app.ticker.add((ticker) => {
bunny.rotation += ticker.deltaTime;
});
```
Broken: `app.ticker.add((dt) => { bunny.rotation += dt; })` -- compiles but `dt` is a `Ticker` object, not a number. Coerces to `NaN`, silently corrupting rotation.
**updateTransform removed** -- Use `this.onRender = this._onRender.bind(this)` in constructor instead.
### Shaders
**Shader.from uses options** -- Expected:
```ts
const shader = Shader.from({
gl: { vertex: vertexSrc, fragment: fragmentSrc },
resources: {
myUniforms: new UniformGroup({ uTime: { value: 0, type: "f32" } }),
},
});
```
Fail: `Shader.from(vertex, fragment, uniforms)`.
**Filter constructor** -- Expected:
```ts
const filter = new Filter({
glProgram: GlProgram.from({ fragment, vertex }),
resources: { filterUniforms: { uTime: { value: 0, type: "f32" } } },
});
```
Fail: `new Filter(vertex, fragment, { uTime: 0 })`.
**Uniforms require type** -- `new UniformGroup({ uTime: { value: 1, type: 'f32' } })`. Fail: `new UniformGroup({ uTime: 1 })`.
**Textures are resources, not uniforms** -- Pass as top-level resource entries (`texture.source`, `texture.style`), not inside UniformGroup.
### Textures
**Sprite no longer auto-detects texture UV changes** -- If you modify a texture's frame after creation, call `texture.update()` to recalculate UVs, then call `sprite.onViewUpdate()` to refresh the sprite. Both calls are required in this order. Updating source data (e.g. video textures) is still automatic.
```ts
texture.frame.width = texture.frame.width / 2;
texture.update(); // recalculate texture UVs first
sprite.onViewUpdate(); // then refresh the sprite's display
```
**Mipmaps** -- `BaseTexture.mipmap` renamed to `autoGenerateMipmaps`. For RenderTextures, you must manually update mipmaps:
```ts
const rt = RenderTexture.create({
width: 100,
height: 100,
autoGenerateMipmaps: true,
});
renderer.render({ target: rt, container: scene });
rt.source.updateMipmaps();
```
### Adapters
**DOMAdapter replaces settings.ADAPTER** -- Expected:
```ts
import { DOMAdapter, WebWorkerAdapter } from "pixi.js";
DOMAdapter.set(WebWorkerAdapter);
DOMAdapter.get().createCanvas();
```
Fail: `settings.ADAPTER = WebWorkerAdapter; settings.ADAPTER.createCanvas();`.
Built-in adapters: `BrowserAdapter` (default), `WebWorkerAdapter` (for web workers).
### Other
**DisplayObject removed** -- `Container` is the base class. `class MyObj extends DisplayObject` fails.
**Leaf nodes cannot have children** -- `Sprite`, `Graphics`, `Mesh`, `Text` are leaf nodes. Wrap in `Container`.
**Renamed properties** (old names still exist as deprecated aliases with warnings):
- `container.name` -> `container.label`
- `container.cacheAsBitmap = true` -> `container.cacheAsTexture(true)`
**getBounds() return type changed:** `getBounds()` now returns a `Bounds` object, not a `Rectangle`. `Bounds` has `.x`, `.y`, `.width`, `.height` getters, so basic usage works. Use `.rectangle` when you need a `Rectangle` instance (e.g., for `.contains()`).
**settings object removed** -- Use `AbstractRenderer.defaultOptions.resolution = 1` and `DOMAdapter.set(BrowserAdapter)`.
**utils namespace removed** -- `import { isMobile } from 'pixi.js'` instead of `utils.isMobile`.
**Text parser renames:**
- `TextFormat` -> `bitmapFontTextParser`
- `XMLStringFormat` -> `bitmapFontXMLStringParser`
- `XMLFormat` -> `bitmapFontXMLParser`
**Assets.add** -- `Assets.add({ alias: 'bunny', src: 'bunny.png' })`. Fail: `Assets.add('bunny', 'bunny.png')`.
**Enum constants replaced with strings:**
| v7 | v8 |
| ---------------------------- | ------------------ |
| `SCALE_MODES.NEAREST` | `'nearest'` |
| `SCALE_MODES.LINEAR` | `'linear'` |
| `WRAP_MODES.CLAMP` | `'clamp-to-edge'` |
| `WRAP_MODES.REPEAT` | `'repeat'` |
| `WRAP_MODES.MIRRORED_REPEAT` | `'mirror-repeat'` |
| `DRAW_MODES.TRIANGLES` | `'triangle-list'` |
| `DRAW_MODES.TRIANGLE_STRIP` | `'triangle-strip'` |
| `DRAW_MODES.LINES` | `'line-list'` |
| `DRAW_MODES.LINE_STRIP` | `'line-strip'` |
| `DRAW_MODES.POINTS` | `'point-list'` |
**Culling is manual** -- Set `cullable = true`, then call `Culler.shared.cull(container, viewRect)` before render. Or add `CullerPlugin` via `extensions.add(CullerPlugin)`.
## Pre-Migration Summary
- [ ] No deprecated v7 core `@pixi/*` packages in dependencies (supplemental packages like `@pixi/sound` are fine)
- [ ] All core `@pixi/*` imports converted to `pixi.js`
- [ ] All `new Application({...})` converted to `await app.init({...})`
- [ ] All Graphics code uses shape-then-fill pattern
- [ ] All constructors use options objects (Text, Mesh, NineSliceSprite, etc.)
- [ ] Shader/Filter code uses `{gl, resources}` pattern with typed uniforms
- [ ] ParticleContainer code uses `Particle`, not `Sprite`
- [ ] Ticker callbacks access `ticker.deltaTime`, not first param as delta
- [ ] Event handling uses `eventMode` instead of `interactive`
- [ ] `settings` and `utils` references removed
- [ ] `DisplayObject` references replaced with `Container`
- [ ] Texture UV modifications call `sprite.onViewUpdate()` where needed
- [ ] RenderTexture mipmap code calls `source.updateMipmaps()` manually
- [ ] `settings.ADAPTER` replaced with `DOMAdapter.set()`
## Common Mistakes
### [CRITICAL] Importing from deprecated v7 core @pixi/\* sub-packages
Wrong:
```ts
import { Sprite } from "@pixi/sprite";
import { Application } from "@pixi/app";
```
Correct:
```ts
import { Sprite, Application } from "pixi.js";
```
v8 uses a single `pixi.js` package. The v7 core `@pixi/*` sub-packages are deprecated and must not be used (see the full list under Imports above). Supplemental packages like `@pixi/sound` are still valid.
### [CRITICAL] Using DisplayObject as base class
Wrong: `class MyObject extends DisplayObject { ... }`
Correct: `class MyObject extends Container { ... }`
`DisplayObject` was removed in v8. `Container` is the base class for all display objects.
### [HIGH] Using old SCALE_MODES/WRAP_MODES/DRAW_MODES enums
Wrong: `texture.source.scaleMode = SCALE_MODES.NEAREST;`
Correct: `texture.source.scaleMode = 'nearest';`
v8 uses string values. Old enums may work as deprecated aliases but should be replaced.
### [HIGH] Using `interactive = true` instead of `eventMode`
Legacy: `sprite.interactive = true;` (still works as an alias for `eventMode = 'static'`)
Preferred: `sprite.eventMode = 'static';`
Default `eventMode` is `'passive'` (no events). Must set `'static'` (hit-testable, no tick checks) or `'dynamic'` (hit-testable with tick checks) explicitly. `interactive = true` still works without a deprecation warning, but `eventMode` is the canonical v8 API.
### [HIGH] Using utils namespace
Wrong: `import { utils } from 'pixi.js'; utils.isMobile.any();`
Correct: `import { isMobile } from 'pixi.js'; isMobile.any();`
The `utils` namespace was removed. All utility functions are direct imports.
### [HIGH] Expecting texture UV changes to auto-update sprites
Wrong: modifying `texture.frame` and assuming the sprite updates automatically.
Correct: call `sprite.onViewUpdate()` after modifying texture UVs.
Sprites no longer subscribe to texture UV change events for performance. Source data updates (e.g. video) still auto-reflect.
## API Reference
- [v8 Migration Guide](https://pixijs.download/release/docs/migrations.html.md)
- [v7 Migration Guide](https://pixijs.download/release/docs/migrations-1.html.md)
- [Application](https://pixijs.download/release/docs/app.Application.html.md)
- [Graphics](https://pixijs.download/release/docs/scene.Graphics.html.md)
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
+489
View File
@@ -0,0 +1,489 @@
---
name: pixijs-performance
description: "Use this skill when profiling or optimizing a PixiJS v8 app for FPS, draw calls, or GPU memory. Covers destroy patterns (cacheAsTexture(false), releaseGlobalResources), GCSystem and TextureGCSystem, PrepareSystem, object pooling, batching rules, BitmapText for dynamic text, culling (Culler, CullerPlugin, cullable, cullArea), resolution/antialias tradeoffs, low-level wins (transient MSAA render textures, render bundles, partial buffer updates). Triggers on: FPS, jank, draw calls, batching, object pool, GCSystem, PrepareSystem, Culler, cacheAsTexture, memory leak, destroy patterns, render bundle, transient, MSAA, Buffer.update, WebGPU performance, TexturePool, repeatEdgePixels, bind group."
license: MIT
---
Profile before optimizing. PixiJS handles a lot of content well out of the box; browser DevTools Performance + GPU profiling should be your first move. Once you've found the bottleneck, apply the targeted pattern below (destroy, pool, batch, cache, or cull).
## Quick Start
```ts
container.cacheAsTexture(true);
container.updateCacheTexture();
container.cacheAsTexture(false);
container.destroy({ children: true });
import { CullerPlugin, extensions } from "pixi.js";
extensions.add(CullerPlugin);
offscreenContainer.cullable = true;
offscreenContainer.cullArea = new Rectangle(0, 0, 256, 256);
// Tune GC via init options (ms). The `textureGC.*` properties are
// deprecated since 8.15.0 — use these on the Application init instead.
await app.init({ gcMaxUnusedTime: 60_000, gcFrequency: 30_000 });
```
**Related skills:** `pixijs-scene-container` (destroy options), `pixijs-scene-core-concepts` (render groups, layers, culling), `pixijs-scene-text` (BitmapText for dynamic content), `pixijs-assets` (atlasing), `pixijs-custom-rendering` (custom batchers).
## Core Patterns
### Proper destroy with cleanup
```ts
import { Sprite, Assets } from "pixi.js";
const texture = await Assets.load("character.png");
const sprite = new Sprite(texture);
// Destroy sprite only (preserve texture for reuse)
sprite.destroy();
// Destroy sprite AND its texture
sprite.destroy({ children: true, texture: true, textureSource: true });
```
When done with a loaded asset entirely:
```ts
Assets.unload("character.png");
```
This removes it from the cache and unloads the GPU resource.
Objects you build for custom rendering clean up the same way: call `geometry.destroy()` and `renderTarget.destroy()` on the ones you create. Destroying a container also destroys the batchers cached for its render group.
### Application destroy/recreate cycle
```ts
import { Application } from "pixi.js";
// Correct destroy that cleans global pools
app.destroy({ releaseGlobalResources: true });
const newApp = new Application();
await newApp.init({ width: 800, height: 600 });
```
Without `releaseGlobalResources: true`, pooled objects (batches, textures) from the old app leak into the new one, causing flickering and corruption.
### Texture garbage collection
PixiJS auto-collects unused textures and GPU resources (including WebGPU bind groups) via `GCSystem`. Defaults: checks every 30 seconds, removes resources idle for 60 seconds. These are time-based (milliseconds).
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({
gcActive: true,
gcMaxUnusedTime: 120000, // idle time before cleanup in ms (default: 60000)
gcFrequency: 60000, // check interval in ms (default: 30000)
});
```
For manual control:
```ts
texture.source.unload(); // immediate GPU memory release
```
### PrepareSystem for GPU upload
Upload textures and graphics to GPU before rendering to avoid first-frame hitches:
```ts
import "pixi.js/prepare";
import { Application, Assets } from "pixi.js";
const app = new Application();
await app.init();
// Don't render until assets are uploaded
app.stop();
const texture = await Assets.load("large-scene.png");
// Upload to GPU ahead of time
await app.renderer.prepare.upload(app.stage);
// Now rendering won't hitch on first frame
app.start();
```
`prepare.upload()` accepts a Container (uploads all textures, text, and graphics in the subtree) or individual resources.
### cacheAsTexture for performance
`cacheAsTexture()` renders a container's subtree to a single texture, reducing draw calls for complex static content. Internally it creates a render group and caches the result.
**When to use:**
- Many static children (UI panels, decorative backgrounds, complex Graphics)
- Containers with expensive filters (cache the filter result)
- Large subtrees that rarely change
**Tradeoffs:**
- Uses GPU memory for the cached texture (larger containers = more memory)
- Max texture size is GPU-dependent (typically 4096x4096 or larger). No PixiJS property exposes it, so query the backend directly:
- Must call `updateCacheTexture()` after modifying children
- Combining with masks is fragile (see the masking skill)
```ts
import type { WebGLRenderer, WebGPURenderer } from "pixi.js";
// Available after renderer/app init on both backends
const maxTextureSize = renderer.name === "webgpu"
? (renderer as WebGPURenderer).gpu.device.limits.maxTextureDimension2D
: (renderer as WebGLRenderer).gl.getParameter(WebGL2RenderingContext.MAX_TEXTURE_SIZE);
```
```ts
import { Container, Sprite } from "pixi.js";
const panel = new Container();
// ... add many static children ...
panel.cacheAsTexture(true);
// With options
panel.cacheAsTexture({ resolution: 2, antialias: true });
// Refresh after changes
panel.updateCacheTexture();
// MUST disable before destroying (see Common Mistakes below)
panel.cacheAsTexture(false);
panel.destroy();
```
**Avoid:** toggling on/off repeatedly (constant re-caching negates benefits), caching sparse containers (negligible gain), caching containers larger than 4096x4096.
### Object recycling
Reuse objects by changing their properties instead of destroy/recreate:
```ts
import { Sprite, Container, Texture } from "pixi.js";
class BulletPool {
private _pool: Sprite[] = [];
private _container: Container;
constructor(container: Container) {
this._container = container;
}
public get(texture: Texture): Sprite {
let bullet = this._pool.pop();
if (!bullet) {
bullet = new Sprite(texture);
this._container.addChild(bullet);
}
bullet.texture = texture;
bullet.position.set(0, 0);
bullet.rotation = 0;
bullet.scale.set(1);
bullet.alpha = 1;
bullet.tint = 0xffffff;
bullet.blendMode = "normal";
bullet.visible = true;
return bullet;
}
public release(bullet: Sprite): void {
bullet.visible = false;
this._pool.push(bullet);
}
}
```
Destroying and recreating is significantly more expensive than toggling `visible` and updating properties. GPU resources stay allocated; only scene graph visibility changes.
### Batching optimization
PixiJS batches similar consecutive objects into single draw calls. Batch breaks occur on:
- Object type change (Sprite vs Graphics)
- Texture source change (beyond the per-batch texture limit, typically 16)
- Blend mode change
- Topology change
Optimize draw order:
```ts
import { Sprite, Graphics, Container } from "pixi.js";
// 4 draw calls: type alternates
const bad = new Container();
bad.addChild(new Sprite(t1));
bad.addChild(new Graphics().rect(0, 0, 10, 10).fill(0xff0000));
bad.addChild(new Sprite(t2));
bad.addChild(new Graphics().rect(0, 0, 10, 10).fill(0x00ff00));
// 2 draw calls: types grouped
const good = new Container();
good.addChild(new Sprite(t1));
good.addChild(new Sprite(t2));
good.addChild(new Graphics().rect(0, 0, 10, 10).fill(0xff0000));
good.addChild(new Graphics().rect(0, 0, 10, 10).fill(0x00ff00));
```
Same principle applies to blend modes: `screen/normal/screen/normal` = 4 draws; `screen/screen/normal/normal` = 2 draws.
### Spritesheets over individual textures
```ts
import { Assets, Sprite } from "pixi.js";
// Load a spritesheet (single texture atlas)
const sheet = await Assets.load("game-atlas.json");
// All frames share one GPU texture; enables batching
const hero = new Sprite(sheet.textures["hero.png"]);
const enemy = new Sprite(sheet.textures["enemy.png"]);
const coin = new Sprite(sheet.textures["coin.png"]);
```
Individual textures each require their own GPU upload and break batches when the texture limit is exceeded. Spritesheets consolidate many frames into one atlas texture.
Use `@0.5x` filename suffix on half-resolution sheets so PixiJS auto-scales them.
### Text performance
Text and HTMLText re-render to a canvas and re-upload to the GPU on every change. Never update them per frame unconditionally:
```ts
import { BitmapText, Text } from "pixi.js";
// Wrong: re-renders canvas + GPU upload every frame
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
// Correct: use BitmapText for frequently changing content
const scoreText = new BitmapText({
text: "Score: 0",
style: { fontFamily: "Arial", fontSize: 24, fill: 0xffffff },
});
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
```
BitmapText renders from a pre-generated glyph atlas. Updates only reposition quads; no canvas re-render or GPU upload. Use it for scores, timers, counters, and anything that changes frequently.
If you must use canvas Text, guard updates so they only happen when the value changes:
```ts
app.ticker.add(() => {
const next = `Score: ${score}`;
if (scoreText.text !== next) {
scoreText.text = next;
}
});
```
Text resolution matches the renderer resolution by default. Lower it independently via `text.resolution = 1` to reduce GPU memory on high-DPI displays.
### Graphics performance
Graphics objects are fastest when their shape doesn't change (transforms, alpha, and tint are fine). Small Graphics (under ~100 points) are batched like Sprites. Complex Graphics with hundreds of shapes are slow; convert them to textures instead:
```ts
import { Graphics, Sprite } from "pixi.js";
const complex = new Graphics();
// ... draw complex shape ...
// Render once to texture, use as Sprite
const texture = app.renderer.generateTexture(complex);
const sprite = new Sprite(texture);
```
### Culling
PixiJS skips rendering objects outside the visible area when `cullable` is set. Disabled by default because it trades CPU cost (bounds checking) for GPU savings. Culling only runs when the `CullerPlugin` is registered:
```ts
import { extensions, CullerPlugin, Culler, Rectangle } from "pixi.js";
extensions.add(CullerPlugin); // before Application.init
// Enable on objects that may be off-screen
sprite.cullable = true;
// Optional: a pre-computed cull rectangle avoids per-frame bounds calculation.
// Without cullArea, the Culler uses the object's global bounds instead.
sprite.cullArea = new Rectangle(0, 0, 800, 600);
// Skip culling an entire subtree (static UI, always visible)
uiRoot.cullableChildren = false;
// Or cull manually without the plugin:
Culler.shared.cull(app.stage, app.renderer.screen);
```
`cullableChildren` on a container stops the culler from recursing into its descendants; a large win for static UI panels with many children. `Culler.shared.cull(container, rect)` runs the same logic manually for custom render pipelines. Use culling when you're GPU-bound; avoid it when CPU-bound, since the per-object bounds check adds overhead.
### Resolution and antialias tradeoffs
```ts
import { Application } from "pixi.js";
const app = new Application();
// Mobile-friendly: lower resolution, no antialias
await app.init({
resolution: 1,
antialias: false,
backgroundAlpha: 1, // opaque background is faster
});
```
`resolution: 2` quadruples the pixel count. On mobile, this can halve frame rate. Profile to find the right balance.
### Low-level rendering optimizations
```ts
import { RenderTexture } from "pixi.js";
// single-pass antialiased render texture: also discard its MSAA depth/stencil at end of pass
const rt = RenderTexture.create({ width: 1024, height: 1024, antialias: true, transient: true });
// upload only the changed byte range of a large buffer (also works on WebGL)
buffer.update(changedBytes, offsetBytes);
// upload only a texel range of a data texture (end is exclusive)
bufferImageSource.update(100, 116);
```
On a tile-based WebGPU GPU (`renderer.device.extensions.tileBased`: every phone GPU and Apple silicon) the multisample colour buffer of every antialiased target is already discarded instead of written back, and a pass that reopens the target restores it from the resolved image; the buffer may not be allocated at all when `renderer.device.extensions.transientAttachment` is true. `transient: true` additionally discards the multisample depth/stencil buffer, and the colour buffer on other GPUs. Only use it on textures rendered in a single pass and never re-entered with `clear: false` or wrapped by a filter or mask. For static custom draw sequences on WebGPU, record a render bundle once and replay it each frame; see the `pixijs-custom-rendering` skill.
### Stagger bulk texture destruction
```ts
function staggerDestroy(textures: Texture[], perFrame: number = 5): void {
let index = 0;
const ticker = app.ticker;
const destroy = () => {
const end = Math.min(index + perFrame, textures.length);
for (let i = index; i < end; i++) {
textures[i].destroy(true);
}
index = end;
if (index >= textures.length) {
ticker.remove(destroy);
}
};
ticker.add(destroy);
}
```
Destroying many textures in one frame causes a freeze. Spread the cost across frames.
### Filters and masks cost
- Set `container.filterArea = new Rectangle(x, y, w, h)` when you know the bounds. Without it, PixiJS measures bounds every frame.
- Release filter memory: `container.filters = null`.
- Full-screen filter textures are pooled at screen size, but padding (the `BlurFilter` default) pushes the request past the screen and up to the next power of two. Set `repeatEdgePixels: true` on full-screen blurs to keep them screen-sized.
- Mask cost (cheapest to most expensive): axis-aligned Rectangle masks (scissor rect) < Graphics masks (stencil buffer) < Sprite/alpha masks (filter pipeline). Hundreds of masks will slow things down regardless of type; prefer rectangle masks when bounds are axis-aligned.
- Set `interactiveChildren = false` on containers with no interactive children.
- Set `hitArea` on large containers to skip recursive child hit testing.
### Safe destroy order
Remove from scene before destroying:
```ts
parent.removeChild(sprite);
sprite.destroy();
```
Destroying while the render pipeline still holds a reference causes null-pointer crashes. If destruction must happen mid-frame, defer it:
```ts
app.ticker.addOnce(() => {
parent.removeChild(sprite);
sprite.destroy();
});
```
## Common Mistakes
### [CRITICAL] App destroy without releaseGlobalResources
Wrong:
```ts
app.destroy();
const newApp = new Application();
```
Correct:
```ts
app.destroy({ releaseGlobalResources: true });
const newApp = new Application();
```
Without this flag, stale pooled batches and textures from the old app persist in global pools and get reused by the new app, causing flickering and visual corruption.
### [HIGH] Interleaving object types in scene graph
`sprite / graphic / sprite / graphic` = 4 draw calls.
`sprite / sprite / graphic / graphic` = 2 draw calls.
Group same object types together in the child order to minimize batch breaks. Same applies to blend mode ordering.
### [HIGH] Destroying and recreating objects instead of recycling
Destroy/recreate is expensive: it deallocates GPU resources, triggers garbage collection, and requires fresh GPU uploads. Reuse objects by updating `texture`, `position`, `visible`, and other properties. Use an object pool pattern for frequently spawned/despawned entities.
### [HIGH] Loading many individual textures instead of spritesheets
Each separate texture consumes its own GPU memory slot and breaks batching when the per-batch texture limit is reached. Spritesheets consolidate textures into atlases. Also avoid textures exceeding 4096px on either axis, as they fail on some mobile GPUs.
### [HIGH] Updating Text or HTMLText every frame
Each update re-renders the full string to a canvas and uploads to the GPU. At 60fps this creates massive overhead. Use BitmapText for dynamic content (scores, timers, counters). If canvas Text is required, only update when the value actually changes. Source: src/**docs**/concepts/performance-tips.md
### [HIGH] Using complex Graphics instead of textures
Hundreds of complex Graphics objects are slow to render. Small Graphics (under ~100 points) batch efficiently like Sprites, but complex ones do not. Render complex static shapes to a texture with `renderer.generateTexture()` and display as a Sprite. Source: src/**docs**/concepts/performance-tips.md
### [MEDIUM] Not staggering bulk texture destruction
Destroying dozens of textures in a single frame causes a visible freeze. Spread destruction across multiple frames (e.g., 5 per frame via a ticker callback). Source: src/**docs**/concepts/garbage-collection.md
### [MEDIUM] Not using PrepareSystem for large scenes
Without `renderer.prepare.upload()`, textures upload to the GPU on first render, causing frame hitches. For loading screens or scene transitions, upload before displaying. Requires `import 'pixi.js/prepare'` (not included even in the default bundle; always import it explicitly). Source: src/prepare/PrepareSystem.ts
### [MEDIUM] Using high resolution or antialias without profiling
`resolution: 2` quadruples the pixel count. `antialias: true` adds GPU cost. Both degrade performance on mobile devices. Always profile on target hardware before enabling. Source: performance-tips.md
## API Reference
- [GCSystem](https://pixijs.download/release/docs/rendering.GCSystem.html.md)
- [TextureGCSystem](https://pixijs.download/release/docs/rendering.TextureGCSystem.html.md)
- [RenderableGCSystem](https://pixijs.download/release/docs/rendering.RenderableGCSystem.html.md)
- [PrepareSystem](https://pixijs.download/release/docs/rendering.PrepareSystem.html.md)
- [Culler](https://pixijs.download/release/docs/scene.Culler.html.md)
- [CullerPlugin](https://pixijs.download/release/docs/app.CullerPlugin.html.md)
- [Pool](https://pixijs.download/release/docs/utils.Pool.html.md)
@@ -0,0 +1,345 @@
---
name: pixijs-scene-container
description: "Use this skill when grouping, positioning, or transforming display objects in PixiJS v8. Covers Container constructor options (isRenderGroup, sortableChildren, boundsArea), addChild/removeChild/addChildAt/swapChildren/setChildIndex, position/scale/rotation/pivot/skew/alpha/tint, getBounds/getGlobalPosition/toLocal/toGlobal, zIndex sorting, cullable, onRender per-frame callback, destroy. Triggers on: Container, addChild, removeChild, addChildAt, swapChildren, sortableChildren, zIndex, position, scale, rotation, pivot, getBounds, toGlobal, toLocal, onRender, destroy, constructor options, ContainerOptions."
license: MIT
---
`Container` is the general-purpose node of the PixiJS v8 scene graph. It holds children and applies transforms, alpha, tint, and blend mode to its whole subtree. Every display object you make will either be a `Container` you're building a branch on, or a leaf (`Sprite`, `Graphics`, `Text`, `Mesh`) that you nest inside one.
Assumes familiarity with `pixijs-scene-core-concepts`.
## Quick Start
```ts
const group = new Container({
label: "hero-group",
x: 200,
y: 150,
sortableChildren: true,
});
const body = new Sprite(await Assets.load("body.png"));
const head = new Sprite(await Assets.load("head.png"));
head.position.set(0, -40);
head.zIndex = 1;
group.addChild(body, head);
group.pivot.set(group.width / 2, group.height / 2);
group.scale.set(1.5);
app.stage.addChild(group);
```
**Related skills:** `pixijs-scene-core-concepts` (scene graph mental model, masking, layers, render groups), `pixijs-scene-sprite` / `pixijs-scene-graphics` / `pixijs-scene-text` / `pixijs-scene-mesh` (leaf objects that go inside containers), `pixijs-events` (`eventMode`, hit testing), `pixijs-math` (Matrix, toGlobal/toLocal detail), `pixijs-performance` (`cacheAsTexture`, culling, render groups).
## Core Patterns
### Constructor options
```ts
const container = new Container({
label: "world",
x: 100,
y: 50,
scale: 2,
rotation: Math.PI / 4,
alpha: 0.8,
visible: true,
tint: 0xffaa00,
blendMode: "add",
sortableChildren: true,
isRenderGroup: true,
origin: { x: 0, y: 0 },
boundsArea: new Rectangle(0, 0, 1920, 1080),
});
```
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
The `Container` constructor uses `assignWithIgnore` to bulk-copy every field in the options object onto the instance except `children`, `parent`, and `effects`. Any public property of `Container` is a valid constructor option: `cullable`, `cullArea`, `mask`, `filterArea`, `eventMode`, `hitArea`, and so on. The options block above groups the most common ones; see the shared reference above for the full list.
`isRenderGroup: true` promotes the container to its own render group so its transforms are applied on the GPU rather than recomputed per-child on the CPU. Use it on stable sub-trees (large static worlds, UI layers). Don't overuse; most scenes don't need explicit render groups and too many hurts performance. Profile before promoting. See `pixijs-scene-core-concepts/references/scene-management.md`.
`sortableChildren: true` causes children to be re-sorted by `zIndex` at the next render. See `zIndex` below.
`origin` is a first-class v8 transform helper: an `ObservablePoint` that acts as a rotation/scale center **without** moving the container. Where `pivot` shifts the projection of the local origin in parent space (so changing it displaces the object), `origin` leaves position alone and simply rotates/scales around the specified local point. Accepts `PointData`, a single number (applied to both axes), or can be set live via `container.origin.set(x, y)`. Setting both `pivot` and `origin` on the same container produces compounding behavior and is discouraged; pick one.
`boundsArea` forces `getBounds()` to return a fixed rectangle instead of recursively measuring children; it is a performance win for containers with hundreds of cheap, predictable children.
`cullable` and `cullArea` are valid constructor options (the `assignWithIgnore` pass copies them like any other field), but they are documented in `pixijs-performance` because culling setup is a performance concern rather than a scene-graph concern.
### Leaves vs containers
```ts
const parent = new Container();
const sprite = new Sprite(texture);
parent.addChild(sprite);
```
Only `Container` (and subclasses intended to hold children, like `RenderLayer`) should have children. `Sprite`, `Graphics`, `Text`, `Mesh`, `ParticleContainer` particles, and `DOMContainer` content are leaves by convention in PixiJS v8. Wrap them in a `Container` whenever you need to group things: give the container the layout logic and keep the leaves pure visual data. Adding children to a leaf logs a deprecation warning and is scheduled to become a hard error.
### Adding and removing children
```ts
const parent = new Container();
parent.addChild(a, b, c);
parent.addChildAt(d, 0);
parent.swapChildren(a, b);
parent.setChildIndex(c, 0);
parent.removeChild(b);
parent.removeChildAt(0);
parent.removeChildren();
parent.removeChildren(0, 2);
```
`addChild` accepts any number of children and returns the first one. Children render in array order: index 0 is drawn first (behind), the last index is drawn last (in front). `addChildAt` inserts at a specific index; `setChildIndex` moves an existing child; `swapChildren` exchanges two children's positions.
`removeChildren(beginIndex?, endIndex?)` removes a slice and returns the removed array.
Calling `addChildAt` with a child that already belongs to the same container silently moves it to the new index. No `added` / `childAdded` / `removed` / `childRemoved` events fire, because the parent-child relationship didn't change. Events only fire when the child comes from a different parent (or from no parent).
For reparenting that preserves world transform (so the child doesn't visually jump), use `reparentChild` / `reparentChildAt`. For swapping a child in place while copying the old child's local transform, use `replaceChild`.
### Transform properties
```ts
const obj = new Container();
obj.x = 100;
obj.y = 200;
obj.position.set(100, 200);
obj.scale.set(2);
obj.scale = 2;
obj.rotation = Math.PI / 4;
obj.angle = 45;
obj.pivot.set(50, 50);
obj.skew.set(0.1, 0.2);
obj.alpha = 0.5;
obj.tint = 0xff0000;
obj.visible = false;
obj.renderable = false;
```
- `position`, `scale`, `pivot`, `skew` are `ObservablePoint`s. Assigning `scale = 2` is valid and sets both axes.
- `rotation` is radians; `angle` is degrees; they are aliases that stay in sync.
- `pivot` sets the point in local space that maps to `position` in parent space; changing it both moves and rotates the container.
- `alpha` and `tint` multiply down through children. `blendMode` applies to this container's draw instructions.
- `visible = false` skips rendering and transform updates. `renderable = false` skips rendering but still updates transforms (use when you need `getBounds()` or hit-testing without drawing).
### zIndex and sortableChildren
```ts
const world = new Container({ sortableChildren: true });
const ground = new Sprite(groundTexture);
ground.zIndex = 0;
const player = new Sprite(playerTexture);
player.zIndex = 10;
const ui = new Sprite(uiTexture);
ui.zIndex = 100;
world.addChild(ground, player, ui);
```
When `sortableChildren` is `true`, the container re-sorts its children by `zIndex` before the next render. Changing any child's `zIndex` automatically re-marks the parent as needing sort. Sort only what you need to sort; leaving `sortableChildren` off is cheaper. If you want full manual control, call `container.sortChildren()` yourself after changing `zIndex` values.
For render-order control that is decoupled from the hierarchy (children keep their logical parent for transforms but render at a different z), use `RenderLayer`. See `pixijs-scene-core-concepts/references/scene-management.md`.
### Bounds and coordinate conversion
```ts
const bounds = container.getBounds();
console.log(bounds.x, bounds.y, bounds.width, bounds.height);
const rect = container.getBounds().rectangle;
const local = new Point(10, 20);
const world = container.toGlobal(local);
const backToLocal = container.toLocal(world);
const selfPos = container.getGlobalPosition();
```
`getBounds()` returns a `Bounds` object (not a `Rectangle`); it exposes `x`, `y`, `width`, `height`, and a `.rectangle` getter for APIs that need an actual `Rectangle`. The signature is `getBounds(skipUpdate?: boolean, bounds?: Bounds)` — pass `true` as the first arg to skip the forced transform update, and an optional `Bounds` instance as the second arg to avoid allocating a new one.
`toGlobal(point)` converts a point in this container's local space to scene-root space. `toLocal(point, from?)` converts from another container's local space (or global space if `from` is omitted). `getGlobalPosition()` is shorthand for `parent.toGlobal(this._position)`.
### Sizing
```ts
const sprite = new Sprite(texture);
sprite.setSize(200, 100);
const { width, height } = sprite.getSize();
```
`setSize` adjusts `scale` so the container's bounds fit the requested pixel size, in one operation. Setting `.width` and `.height` individually works, but each assignment triggers a separate bounds recomputation; prefer `setSize` when changing both axes.
### Container events
```ts
const parent = new Container();
parent.on("childAdded", (child, container, index) => {
console.log("added at", index, child.label);
});
parent.on("childRemoved", (child, container, index) => {
console.log("removed from", index);
});
const child = new Container();
child.on("added", (newParent) => console.log("entered", newParent.label));
child.on("removed", (oldParent) => console.log("left", oldParent.label));
child.on("visibleChanged", (visible) => console.log("visible:", visible));
child.on("destroyed", (destroyed) => console.log("gone", destroyed.label));
parent.addChild(child);
```
| Event | Fires on | Arguments |
| ---------------- | ------------------------------------- | --------------------------- |
| `childAdded` | the parent receiving the child | `(child, container, index)` |
| `childRemoved` | the parent losing the child | `(child, container, index)` |
| `added` | the child that was attached | `(parent)` |
| `removed` | the child that was detached | `(parent)` |
| `destroyed` | the destroyed container | `(container)` |
| `visibleChanged` | the container whose `visible` flipped | `(visible)` |
These are emitted on the `EventEmitter` side of `Container`; do not confuse them with pointer events from `pixijs-events`.
`destroyed` fires after internal cleanup but before listeners are removed, so by the time your handler runs `position`, `scale`, `pivot`, `origin`, `skew`, and `parent` have already been nulled, and `children` has been emptied (length 0, but the array reference itself is not nulled). Capture any data you need from the container _before_ calling `destroy()`, not inside the handler.
### Per-frame updates with onRender
```ts
const container = new Container();
container.onRender = (renderer) => {
container.rotation += 0.01;
};
container.onRender = null;
```
`onRender` runs every frame while the container is being rendered, and receives the active `Renderer`. Use it for lightweight animation or per-frame updates tied to a specific container. In v7 this pattern was done by overriding `updateTransform`, which no longer runs every frame in v8. Set `onRender = null` to detach the callback.
### Finding and removing from parent
```ts
const player = world.getChildByLabel("player");
const enemies = world.getChildrenByLabel(/enemy-\d+/, true);
const bounds = hud.getLocalBounds();
oldSprite.removeFromParent();
```
- `getChildByLabel(label, deep?)` — first match by string or `RegExp`. Pass `true` for a recursive search.
- `getChildrenByLabel(label, deep?, out?)` — all matches. Accepts an optional reusable output array.
- `getLocalBounds()` — bounds in this container's own coordinate space, ignoring parent transforms. Cheaper than `getBounds()` for self-contained layout math.
- `removeFromParent()` — detaches `this` from its current parent (no-op if already orphaned).
### Destroy
```ts
container.destroy();
container.destroy({
children: true,
texture: true,
textureSource: true,
});
console.log(container.destroyed);
```
By default `destroy()` unlinks this container from its parent and tears down its own state. Pass `{ children: true }` to recursively destroy every descendant; this is the usual call for killing a whole subtree. `texture: true` and `textureSource: true` additionally destroy the GPU resources referenced by leaf children (useful for sprites whose textures you loaded just for them). If `cacheAsTexture` is on, disable it with `container.cacheAsTexture(false)` before destroying.
## Common Mistakes
### [CRITICAL] Adding children to leaf scene objects
Wrong:
```ts
const sprite = new Sprite(texture);
const overlay = new Sprite(overlayTexture);
sprite.addChild(overlay);
```
Correct:
```ts
const group = new Container();
const sprite = new Sprite(texture);
const overlay = new Sprite(overlayTexture);
group.addChild(sprite, overlay);
```
Sprites, Graphics, Text, and Mesh are leaves. Adding children to them logs a deprecation warning now and will be an error in a future version. Always wrap them in a `Container` when you need grouping.
### [HIGH] Expecting getBounds() to return a Rectangle
Wrong:
```ts
const rect = container.getBounds();
rect.contains(x, y); // TypeError: contains is not a function
```
Correct:
```ts
const rect = container.getBounds().rectangle;
rect.contains(x, y);
const bounds = container.getBounds();
console.log(bounds.width, bounds.height);
```
`getBounds()` returns a `Bounds` instance in v8. Its basic getters (`x`, `y`, `width`, `height`) work, but for `Rectangle`-specific methods like `.contains()` or passing to APIs that require a `Rectangle`, read the `.rectangle` property.
### [HIGH] Using cacheAsBitmap instead of cacheAsTexture
Wrong:
```ts
container.cacheAsBitmap = true;
```
Correct:
```ts
container.cacheAsTexture(true);
```
`cacheAsBitmap` (v7 property) was renamed to `cacheAsTexture()` (a method) in v8. Always disable it with `cacheAsTexture(false)` before calling `destroy()`.
### [MEDIUM] Using container.name instead of container.label
`name` was renamed to `label` in v8. The old property still works as a deprecated alias; `getChildByLabel` is the v8 way to look up children by name.
### [MEDIUM] Setting both pivot and origin on the same container
Pivot shifts the projection of the local origin in parent space (moves the object as a side-effect of changing the rotation center). Origin changes the rotation/scale center without displacement. Setting both on the same container produces unexpected compounding; pick one.
## API Reference
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [ContainerOptions](https://pixijs.download/release/docs/scene.ContainerOptions.html.md)
- [ViewContainer](https://pixijs.download/release/docs/scene.ViewContainer.html.md)
- [Bounds](https://pixijs.download/release/docs/rendering.Bounds.html.md)
- [Point](https://pixijs.download/release/docs/maths.Point.html.md)
- [ObservablePoint](https://pixijs.download/release/docs/maths.ObservablePoint.html.md)
- [RenderGroup](https://pixijs.download/release/docs/rendering.RenderGroup.html.md)
@@ -0,0 +1,243 @@
---
name: pixijs-scene-core-concepts
description: "Use this skill when reasoning about the PixiJS v8 scene graph as a whole: how containers, leaves, transforms, and render order fit together. Covers leaf vs container distinction, local/world coordinates, culling, render groups, sortable children, masking, RenderLayer, constructor options shared by every scene node, and which leaf skill covers which display object. Triggers on: scene graph, display list, Container, Sprite, Graphics, Text, Mesh, ParticleContainer, DOMContainer, GifSprite, masking, render group, RenderLayer, world transform, constructor options, ContainerOptions."
license: MIT
---
This skill is the shared mental model referenced by all `pixijs-scene-*` leaves. It explains what the scene graph is in PixiJS v8, how a `Container` differs from a leaf, and where each concept lives. It does not go deep on any single API; it frames the pieces and points to the skill or reference file that does.
## Quick Start
```ts
const world = new Container({ isRenderGroup: true });
app.stage.addChild(world);
const hero = new Container({ label: "hero" });
hero.addChild(new Sprite(bodyTexture));
hero.addChild(new Sprite(faceTexture));
world.addChild(hero);
const mask = new Graphics().rect(0, 0, 800, 600).fill(0xffffff);
world.mask = mask;
world.addChild(mask);
hero.position.set(world.width / 2, world.height / 2);
```
**Related skills:** `pixijs-scene-container` (Container API in detail), the leaf skills (`pixijs-scene-sprite`, `pixijs-scene-graphics`, `pixijs-scene-text`, `pixijs-scene-mesh`, `pixijs-scene-particle-container`, `pixijs-scene-dom-container`, `pixijs-scene-gif`), `pixijs-events` (hit testing traverses the scene graph), `pixijs-performance` (cache, culling, render groups), `pixijs-math` (Matrix, toGlobal/toLocal detail).
## Core Concepts
### What the scene graph is
The PixiJS scene graph is a tree of display objects rooted at `app.stage`. Each node has a parent, a transform (position, scale, rotation, pivot, skew) relative to its parent, and optional visual state (alpha, tint, blendMode, visibility). Each frame the renderer walks the tree, composes transforms and visual state down to world-space, culls what's offscreen, and emits draw calls. The scene graph is both the layout model and the render order: earlier siblings draw behind later siblings.
Every display object in v8 is a `Container` subclass. `DisplayObject` from earlier versions was removed.
### Container vs leaf (CRITICAL)
There are two roles in the tree:
- **Containers**: nodes that hold children. Use a `Container` (or `RenderLayer`) for any node that groups, positions, or transforms other nodes.
- **Leaves**: nodes that draw something and have no children. Use `Sprite`, `Graphics`, `Text`, `Mesh`, `ParticleContainer`'s `Particle`, `DOMContainer`, or `GifSprite` as leaves.
In PixiJS v8, leaves must not have children. Adding children to a `Sprite` / `Graphics` / `Text` / `Mesh` logs a deprecation warning and is scheduled to become a hard error. The rule is: **use `Container` for any node that needs children; do not nest children inside leaf scene objects.** If you need to group a leaf with other leaves, wrap them in a `Container`.
This distinction is why the `pixijs-scene-*` skills are split the way they are: `pixijs-scene-container` covers the grouping node, and each leaf gets its own skill focused on its draw behavior.
### Transforms and coordinate spaces
Every container composes a `localTransform` (a `Matrix`) from its `position`, `scale`, `rotation`, `pivot`, and `skew`. The renderer multiplies parents' local transforms together to produce the `worldTransform` (and `groupTransform` if a render group is in the chain), which maps local points to scene-root space. Use `toGlobal(point)` and `toLocal(point, from?)` to convert between spaces, and `getGlobalPosition()` for this object's world position. Full Matrix detail lives in `pixijs-math`; transform setters and `toLocal`/`toGlobal` live in `pixijs-scene-container`.
### Render order and explicit z-ordering
Children render in array order: index 0 first, last index last. For explicit z-ordering on a single container, set `sortableChildren = true` and assign `zIndex` values to children. For render order that is decoupled from the logical hierarchy (e.g., a character's parent is a game world but its drawing happens on a UI layer), use `RenderLayer`. Deep detail, including when to prefer sortable children vs RenderLayer, is in `references/scene-management.md`.
### Render groups
Flagging a container with `isRenderGroup: true` (or calling `container.enableRenderGroup()`) tells PixiJS to apply its transform on the GPU as a single matrix instead of recomputing every descendant's world transform on the CPU each frame. Use render groups on large, stable sub-trees such as worlds, UI layers, or parallax strips. Deep detail in `references/scene-management.md`.
### Culling
`cullable = true` + a `cullArea: Rectangle` tells the `CullerPlugin` (or any culling pass) to skip rendering objects that fall outside the visible area. `cullableChildren = false` short-circuits recursive culling for a sub-tree whose children are always on screen. Culling is a performance topic; `pixijs-performance` and `references/scene-management.md` cover the trade-offs.
### Masking
Set `container.mask` to another display object to clip its rendering. PixiJS picks the mask type automatically: a `Graphics` or `Container` mask uses a stencil buffer, a `Sprite` mask uses an alpha filter, and a number selects a `ColorMask`. All four mask types (AlphaMask, StencilMask, ScissorMask, ColorMask) are covered in `references/masking.md`.
### Visibility, alpha, tint, and blend mode
`visible = false` skips rendering and transform updates; `renderable = false` skips rendering but still updates transforms (use when hit-testing or bounds queries need to stay live). `alpha` and `tint` multiply down through the sub-tree; `blendMode` controls how this container's draw instructions composite against what is already on the target. See `pixijs-blend-modes` for the full blend-mode list and `pixijs-scene-container` for per-node state.
### Destroy semantics
`container.destroy()` unlinks one node. `container.destroy({ children: true })` recursively destroys the whole sub-tree; always use this for killing a branch. `texture: true` and `textureSource: true` additionally tear down GPU resources owned by leaves. If `cacheAsTexture` is on, disable it before destroying. `pixijs-scene-container` documents the full signature.
### Lifecycle events
Containers emit events for hierarchy and visibility changes: `childAdded` / `childRemoved` on the parent, `added` / `removed` on the child, plus `visibleChanged` and `destroyed` on the container itself. Useful for wiring reactive UI updates or resource bookkeeping. Full details in `references/container-hierarchy.md`.
## Leaf comparison: which skill covers which object
| Leaf | Primary use | Skill |
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| `Sprite` | Draw a single texture at a position (with variants `NineSliceSprite` for resizable UI panels and `TilingSprite` for repeating backgrounds). | `pixijs-scene-sprite` |
| `Text` / `BitmapText` / `HTMLText` / `SplitText` / `SplitBitmapText` | Render text. Canvas-based `Text` for general use, `BitmapText` for high-volume cheap text, `HTMLText` for rich HTML/CSS layout, split variants for per-character animation. | `pixijs-scene-text` |
| `Graphics` | Vector drawing: shapes, lines, paths, fills, strokes. Backed by a `GraphicsContext`. | `pixijs-scene-graphics` |
| `Mesh` / `MeshSimple` / `MeshPlane` / `MeshRope` / `PerspectiveMesh` | Custom geometry with a shader or texture. Use `MeshRope` for textured path-following ribbons and `PerspectiveMesh` for 2D perspective. | `pixijs-scene-mesh` |
| `ParticleContainer` + `Particle` | Thousands of lightweight sprites with a restricted transform set, for high-throughput particle effects. | `pixijs-scene-particle-container` |
| `DOMContainer` | Render an HTML element positioned inside the scene graph (useful for inputs, iframes, accessibility overlays). | `pixijs-scene-dom-container` |
| `GifSprite` | Animated GIF playback as a display object. Requires `pixi.js/gif`. | `pixijs-scene-gif` |
`Container` itself is covered in `pixijs-scene-container` and is the node every leaf lives inside.
## When to use what (quick decisions)
- "I want to group and transform some display objects" → `Container`, see `pixijs-scene-container`.
- "I want to draw a texture" → `Sprite`, see `pixijs-scene-sprite`.
- "I want to draw vector shapes or paths" → `Graphics`, see `pixijs-scene-graphics`.
- "I want to draw text" → `Text` / `BitmapText` / `HTMLText`, see `pixijs-scene-text`.
- "I want thousands of cheap sprites" → `ParticleContainer`, see `pixijs-scene-particle-container`.
- "I want a custom-geometry mesh or a deformed sprite" → `Mesh` or one of its variants, see `pixijs-scene-mesh`.
- "I want to clip a sub-tree" → set `.mask`, see `references/masking.md`.
- "I want a decoupled render order" → `RenderLayer`, see `references/scene-management.md`.
- "I want GPU-level transforms for a big stable sub-tree" → `isRenderGroup: true`, see `references/scene-management.md`.
- "I want to skip offscreen rendering" → `cullable = true` + `CullerPlugin`, see `pixijs-performance`.
## References
- [references/constructor-options.md](references/constructor-options.md): the ~30 fields inherited by every `Container`-derived node (transform, display, hierarchy, sorting, layout, effects, callbacks), with defaults, types, and when line-by-line assignment is appropriate. Shared reference for all leaf skills.
- [references/container-hierarchy.md](references/container-hierarchy.md): add/remove/swap children, reparenting with transform preservation, label navigation, destroy sub-trees.
- [references/transforms.md](references/transforms.md): position, scale, rotation, pivot, origin, skew, toGlobal/toLocal, the three matrices (local/group/world), bounds.
- [references/masking.md](references/masking.md): AlphaMask, StencilMask, ScissorMask, ColorMask, inverse masking, cost comparison.
- [references/layers.md](references/layers.md): `RenderLayer`, attach/detach, sorted layers, layer + logical parent split.
- [references/render-groups.md](references/render-groups.md): `isRenderGroup`, GPU-level transforms, when to use, render-groups vs `cacheAsTexture`.
- [references/scene-management.md](references/scene-management.md): combined view; render groups, `RenderLayer`, culling, zIndex sorting, `boundsArea`.
## Common Mistakes
### [CRITICAL] Adding children to a leaf display object
Wrong:
```ts
const sprite = new Sprite(texture);
sprite.addChild(new Graphics().rect(0, 0, 10, 10).fill(0xff0000));
```
Correct:
```ts
const group = new Container();
group.addChild(new Sprite(texture));
group.addChild(new Graphics().rect(0, 0, 10, 10).fill(0xff0000));
```
In v8 leaves (`Sprite`, `Graphics`, `Text`, `Mesh`, `ParticleContainer`, `DOMContainer`, `GifSprite`) technically extend `Container` but should not hold children. Adding children to a leaf produces undefined rendering behavior. Wrap the leaf in a `Container` when you need grouping.
### [CRITICAL] Referencing DisplayObject
Wrong:
```ts
import { DisplayObject } from "pixi.js"; // no such export in v8
function moveNode(node: DisplayObject) {
node.x += 1;
}
```
Correct:
```ts
import { Container } from "pixi.js";
function moveNode(node: Container) {
node.x += 1;
}
```
`DisplayObject` was removed in v8. Every display object — including `Sprite`, `Graphics`, `Text`, `Mesh` — is a `Container` subclass now. Use `Container` as the base type.
### [HIGH] Forgetting isRenderGroup on large static subtrees
Wrong:
```ts
const world = new Container();
for (let i = 0; i < 5000; i++) {
world.addChild(new Sprite(texture));
}
app.stage.addChild(world);
```
Correct:
```ts
const world = new Container({ isRenderGroup: true });
for (let i = 0; i < 5000; i++) {
world.addChild(new Sprite(texture));
}
app.stage.addChild(world);
```
Without `isRenderGroup: true`, the renderer recomposes every child's transform against its parents every frame. Marking the subtree as a render group caches transforms and draw state until a child changes, which is essential for large or mostly-static trees.
### [HIGH] Treating child.x as world space
Wrong:
```ts
const enemy = new Container();
enemy.x = 500;
world.addChild(enemy);
world.x = 200;
console.log(enemy.x); // 500 (local), not 700 (world)
```
Correct:
```ts
const worldPos = enemy.toGlobal({ x: 0, y: 0 });
console.log(worldPos.x); // 700
```
`Container.x/y/scale/rotation` are LOCAL to the parent. Use `toGlobal(point)` to compute world-space coordinates, or `getGlobalPosition()` for the container's origin in world space. The world transform is not exposed as a simple `x/y` pair.
### [MEDIUM] sortableChildren without zIndex
Wrong:
```ts
const layer = new Container();
layer.sortableChildren = true;
layer.addChild(bg); // no zIndex
layer.addChild(mid); // no zIndex
layer.addChild(fg); // no zIndex
// order is unchanged — all zIndex default to 0
```
Correct:
```ts
const layer = new Container();
layer.sortableChildren = true;
bg.zIndex = 0;
mid.zIndex = 10;
fg.zIndex = 20;
layer.addChild(bg, mid, fg);
```
`sortableChildren` re-sorts children by `zIndex` before rendering, but only takes effect when children actually have distinct `zIndex` values. Setting only the parent flag has no visible effect.
## Tooling
The [PixiJS Devtools Chrome extension](https://chromewebstore.google.com/detail/pixijs-devtools/aamddddknhcagpehecnhphigffljadon) lets you inspect and manipulate a running scene graph in real time. Install it for any non-trivial layout or render-order debugging.
## API Reference
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [ViewContainer](https://pixijs.download/release/docs/scene.ViewContainer.html.md)
- [RenderLayer](https://pixijs.download/release/docs/scene.RenderLayer.html.md)
- [RenderGroup](https://pixijs.download/release/docs/rendering.RenderGroup.html.md)
- [Bounds](https://pixijs.download/release/docs/rendering.Bounds.html.md)
- [Culler](https://pixijs.download/release/docs/scene.Culler.html.md)
- [CullerPlugin](https://pixijs.download/release/docs/app.CullerPlugin.html.md)
@@ -0,0 +1,155 @@
# Constructor options (Container-inherited)
Prefer `new X({ ... })` over line-by-line property assignment when constructing Container-derived scene nodes.
## Before / after
Line-by-line:
```ts
const hero = new Sprite(texture);
hero.x = 100;
hero.y = 200;
hero.anchor.set(0.5);
hero.scale.set(2);
hero.rotation = Math.PI / 4;
hero.alpha = 0.8;
hero.tint = 0xff8800;
hero.label = "hero";
hero.zIndex = 10;
```
Options object:
```ts
const hero = new Sprite({
texture,
x: 100,
y: 200,
anchor: 0.5,
scale: 2,
rotation: Math.PI / 4,
alpha: 0.8,
tint: 0xff8800,
label: "hero",
zIndex: 10,
});
```
## Exceptions (line-by-line is fine here)
- Values calculated after construction — e.g., `sprite.position.set(app.screen.width / 2, app.screen.height / 2)` needs `app` to exist first.
- Properties that change at runtime and the change is the point of the example — e.g., `sprite.tint = damageColor` in a damage-flash demo.
- Objects received from elsewhere — you can't reconstruct them through a constructor options bag.
- `point.set(x, y)` / `scale.set(sx, sy)` for multi-coordinate batches where a single call reads better than two options keys.
For v7 to v8 migration of constructor patterns, see `pixijs-migration-v8`.
## Worked example
```ts
const group = new Container({
// Transform
x: 100,
y: 200,
scale: { x: 2, y: 2 },
rotation: Math.PI / 4,
pivot: { x: 50, y: 50 },
skew: { x: 0, y: 0 },
// Display
alpha: 0.8,
tint: 0xff8800,
blendMode: "add",
visible: true,
renderable: true,
// Hierarchy
label: "world",
children: [background, player],
// Sorting & grouping
isRenderGroup: true,
sortableChildren: true,
zIndex: 10,
// Layout & bounds
boundsArea: new Rectangle(0, 0, 800, 600),
// Effects
filters: [new BlurFilter(2)],
mask: maskGraphics,
// Callbacks
onRender: (renderer) => {
/* per-frame logic */
},
});
```
## Transform
| Option | Type | Default | Description |
| ---------- | --------------------- | ----------------- | ----------------------------------------------------------------------------- |
| `alpha` | `number` | `1` | Opacity multiplied with parent alpha; 0 is fully transparent, 1 fully opaque. |
| `angle` | `number` | `0` | Rotation in degrees. Alias for `rotation` in radians. |
| `origin` | `PointData \| number` | `new Point(0, 0)` | Center of rotation and scaling without moving the node's position. |
| `pivot` | `PointData \| number` | `new Point(0, 0)` | Center of rotation, scaling, and skewing; reprojects position. |
| `position` | `PointData` | `new Point(0, 0)` | Position in parent-local coordinates. |
| `rotation` | `number` | `0` | Rotation in radians. |
| `scale` | `PointData \| number` | `new Point(1, 1)` | Local scale factor along each axis. |
| `skew` | `PointData` | `new Point(0, 0)` | Skew factor in radians along each axis. |
| `x` | `number` | `0` | Alias for `position.x`. |
| `y` | `number` | `0` | Alias for `position.y`. |
## Display
| Option | Type | Default | Description |
| ------------ | ------------- | ---------- | ------------------------------------------------------------------------ |
| `blendMode` | `BLEND_MODES` | `'normal'` | How this node composites against its target. |
| `renderable` | `boolean` | `true` | When false, skips rendering but still updates transforms. |
| `tint` | `ColorSource` | `0xFFFFFF` | Color multiplied into this node's output; `0xFFFFFF` is no tint. |
| `visible` | `boolean` | `true` | When false, skips both rendering and transform updates for this subtree. |
## Hierarchy
| Option | Type | Default | Description |
| ---------- | ----------- | ------- | ----------------------------------------------------------------------- |
| `children` | `C[]` | `[]` | Array of children to `addChild` after construction. |
| `label` | `string` | `null` | Instance label used by `getChildByLabel` / `getChildrenByLabel`. |
| `parent` | `Container` | `null` | Parent container; the new node is added as a child during construction. |
## Sorting & grouping
| Option | Type | Default | Description |
| ------------------ | --------- | ------- | ---------------------------------------------------------------------------------- |
| `isRenderGroup` | `boolean` | `false` | Marks this container as a render group; GPU-level transform for the whole subtree. |
| `sortableChildren` | `boolean` | `false` | Before rendering, re-sorts children by `zIndex`. |
| `zIndex` | `number` | `0` | Sort key used when the parent has `sortableChildren` enabled. |
## Layout & bounds
| Option | Type | Default | Description |
| ------------ | ----------- | ----------- | ------------------------------------------------------------- |
| `boundsArea` | `Rectangle` | `undefined` | Override bounds rectangle; skips recursive child measurement. |
| `height` | `number` | `0` | Requested height in pixels; internally assigns `scale.y`. |
| `width` | `number` | `0` | Requested width in pixels; internally assigns `scale.x`. |
## Effects
| Option | Type | Default | Description |
| --------- | ----------------------------- | ------- | ------------------------------------------------------------------------------- |
| `filters` | `Filter \| readonly Filter[]` | `null` | One filter or an array of filters applied to this subtree (WebGL/WebGPU only). |
| `mask` | `Container \| number \| null` | `null` | Mask display object or mask id; picks stencil/alpha/scissor/color mask by type. |
## Callbacks
| Option | Type | Default | Description |
| ---------- | ---------------------------------------- | ------- | ------------------------------------------------------------------ |
| `onRender` | `((renderer: Renderer) => void) \| null` | `null` | Per-frame callback invoked while this container is being rendered. |
## Advanced options and aliases
- `autoGarbageCollect` (@advanced, from `ViewContainerOptions`): leave at default unless you know why you need otherwise.
- `cacheAsTexture`: typed as a constructor option via `CacheAsTextureMixinConstructor` but is ACTUALLY A METHOD on the instance — `container.cacheAsTexture(true)`. Passing it as an options key is accepted but semantically wrong. Prefer the method.
- `setMask`: typed on `EffectsMixinConstructor` but is also a method, not data. Use `mask: ...` in options or call `setMask(...)` later.
- `interactive`: convenience boolean that maps to `eventMode`; `true` sets `eventMode = 'static'`, `false` sets `eventMode = 'passive'`. See `eventMode` for the full set of modes.
- `effects`: the `Container` constructor explicitly passes `effects: true` to `assignWithIgnore`, so passing this option is silently dropped. Not useful.
## See also
Events (`eventMode`, `hitArea`, `cursor`, `interactive*`, `on*` handlers), accessibility (`accessible*`, `tabIndex`, `accessibleTitle`, etc.), and culling (`cullable`, `cullArea`, `cullableChildren`) are ALSO valid constructor options via mixin extension on `ContainerOptions`. They are documented in their own skills: `pixijs-events`, `pixijs-accessibility`, `pixijs-performance`.
@@ -0,0 +1,232 @@
# Container Hierarchy
The PixiJS scene graph is a tree of `Container` subclasses rooted at `app.stage`. Every node has a single parent, zero or more children, and a local transform. Use this reference for mental model and fine-grained parent/child management; for full Container API (constructor options, lifecycle methods), see the top-level `pixijs-scene-container` skill.
## Quick Start
```ts
const world = new Container({ label: "world" });
app.stage.addChild(world);
const hero = new Container({ label: "hero" });
hero.addChild(new Sprite(bodyTexture));
hero.addChild(new Sprite(weaponTexture));
world.addChild(hero);
const enemies = new Container({ label: "enemies" });
world.addChild(enemies);
enemies.addChild(new Sprite(enemyTexture), new Sprite(enemyTexture));
```
Every display object in v8 is a `Container` subclass. Leaves (Sprite, Graphics, Text, Mesh, ParticleContainer, DOMContainer, GifSprite) have `allowChildren = false` and must not have children. Use a plain `Container` to group leaves.
## Core Patterns
### Add, remove, swap
```ts
// Add (variadic, returns the first added child)
parent.addChild(child1, child2, child3);
// Insert at index
parent.addChildAt(child, 0);
// Remove
parent.removeChild(child);
parent.removeChildAt(0);
parent.removeChildren();
parent.removeChildren(0, 3); // first three
// Swap
parent.swapChildren(childA, childB);
```
`addChild` with an existing parent first removes the child from its old parent (no explicit `removeChild` needed). Returned value is the first added child for chaining.
When `addChildAt` moves a child that is **already** in the same container, the move is silent: no `added` / `removed` / `childAdded` / `childRemoved` events fire, because the parent-child relationship hasn't changed.
### Replacing a child
```ts
parent.replaceChild(oldChild, newChild);
```
`replaceChild` swaps `oldChild` for `newChild` at the same index and copies the old child's local transform (position, rotation, scale, etc.) onto the replacement. Use this when you want a drop-in replacement to inherit the old child's placement without copying fields by hand.
### Child queries
```ts
const count = parent.children.length;
const first = parent.getChildAt(0);
const index = parent.getChildIndex(child);
const hero = parent.getChildByLabel("hero");
const heroDeep = parent.getChildByLabel("weapon", true); // recursive
const enemies = parent.getChildrenByLabel("enemy");
const waves = parent.getChildrenByLabel(/^wave-\d+/);
const buttonsDeep = parent.getChildrenByLabel("button", true);
```
`label` can be a `string` or a `RegExp` (e.g., `parent.getChildByLabel(/^hero-/)`). `getChildByLabel` returns the first match; `getChildrenByLabel` returns every match. Both walk the immediate children and recurse when the second argument is `true`. For more complex queries, iterate `parent.children` manually.
### Iterating children
```ts
for (const child of parent.children) {
child.alpha = 0.5;
}
parent.children.forEach((child, i) => {
child.y = i * 32;
});
```
`children` is a plain array. It's safe to iterate, but mutating it during iteration (via `addChild` / `removeChild`) is not; snapshot first with `[...parent.children]` if you need to modify the list.
### Reparenting with transform preservation
```ts
newParent.reparentChild(child);
newParent.reparentChildAt(child, 0);
newParent.reparentChild(childA, childB, childC);
```
`reparentChild` and `reparentChildAt` move children to a new parent while preserving their **world** transform, so the visuals don't jump. `reparentChild` appends to the end and accepts multiple children; `reparentChildAt` inserts at a specific index and accepts one child.
If you must do this manually (for example, to batch with other transform work), convert through `getGlobalPosition` and `toLocal`:
```ts
const globalPos = child.getGlobalPosition();
newParent.addChild(child);
child.position = newParent.toLocal(globalPos);
```
Plain `addChild` keeps the local transform, which means the visual position changes; `reparentChild` is almost always what you want.
### Destroying sub-trees
```ts
branch.destroy({ children: true });
```
`destroy()` unlinks a single node. `destroy({ children: true })` recursively tears down the entire sub-tree. Always use `{ children: true }` when removing a branch; otherwise you leak the child nodes and their textures.
### Label-based tree navigation
```ts
const panel = new Container({ label: "panel" });
panel.addChild(new Container({ label: "header" }));
panel.addChild(new Container({ label: "body" }));
const header = panel.getChildByLabel("header");
```
Use `label` for debug tooling and light-weight tree navigation. Don't use it for hot-path code; the `getChildByLabel` walk is O(n) per call.
### Lifecycle events
Containers emit events for hierarchy changes, visibility changes, and destruction.
**Parent-side events** fire on the container whose children changed:
```ts
group.on("childAdded", (child, parent, index) => {
/* ... */
});
group.on("childRemoved", (child, parent, index) => {
/* ... */
});
```
**Child-side events** fire on the child itself when its parent changes:
```ts
sprite.on("added", (parent) => {
/* ... */
});
sprite.on("removed", (oldParent) => {
/* ... */
});
```
**Property and lifecycle events:**
```ts
container.on("visibleChanged", (visible) => {
/* ... */
});
container.on("destroyed", (container) => {
/* ... */
});
```
`visibleChanged` fires whenever `container.visible` flips. `destroyed` fires inside `destroy()` after internal cleanup but before listeners are removed. By the time `destroyed` runs, `position`, `scale`, `pivot`, `origin`, `skew`, and `parent` have already been nulled, and `children` has been emptied (length 0, but the array reference itself is not nulled). Capture any container state you need **before** calling `destroy()`, not inside the event handler.
## Common Mistakes
### [CRITICAL] Adding children to a leaf
Wrong:
```ts
sprite.addChild(otherSprite);
```
Correct:
```ts
const group = new Container();
group.addChild(sprite, otherSprite);
```
Sprite, Graphics, Text, Mesh, ParticleContainer, DOMContainer, and GifSprite all set `allowChildren = false`. Adding children logs a deprecation warning and will become a hard error. Use a plain `Container` to group.
### [HIGH] Destroying the parent without `children: true`
Wrong:
```ts
levelContainer.destroy();
```
Correct:
```ts
levelContainer.destroy({ children: true });
```
Plain `destroy()` only removes the parent. Its children become orphans; still in memory, still referencing textures. For a clean teardown, always pass `{ children: true }`, and include `texture: true` / `textureSource: true` when you also want to release GPU memory.
### [MEDIUM] Mutating `children` during iteration
Wrong:
```ts
parent.children.forEach((child) => {
if (shouldRemove(child)) parent.removeChild(child);
});
```
Correct:
```ts
for (const child of [...parent.children]) {
if (shouldRemove(child)) parent.removeChild(child);
}
```
`removeChild` splices the array, shifting indices. Iterating the live array misses elements or processes some twice. Snapshot before iterating.
## API Reference
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [ContainerOptions](https://pixijs.download/release/docs/scene.ContainerOptions.html.md)
- [ContainerChild](https://pixijs.download/release/docs/scene.ContainerChild.html.md)
- [ChildrenHelperMixin](https://pixijs.download/release/docs/scene.ChildrenHelperMixin.html.md)
@@ -0,0 +1,145 @@
# RenderLayer
`RenderLayer` decouples render order from the scene graph hierarchy. Objects keep their logical parent (for transforms) but render at the layer's position in the scene. Use layers to pull specific objects to a specific z-depth without reparenting; the classic "character is parented to the world, but draws on the UI overlay" problem.
## Quick Start
```ts
const bgLayer = new RenderLayer();
const entityLayer = new RenderLayer();
const uiLayer = new RenderLayer();
app.stage.addChild(bgLayer, entityLayer, uiLayer);
const world = new Container();
app.stage.addChild(world);
const player = new Sprite(texture);
world.addChild(player); // logical parent for transforms
entityLayer.attach(player); // render position
```
The player lives in `world` for transform purposes (so moving the world moves the player), but the renderer draws it in the order determined by `entityLayer`'s position in the stage.
## Core Patterns
### attach / detach
```ts
layer.attach(sprite);
layer.attach(sprite1, sprite2, sprite3);
layer.detach(sprite);
layer.detachAll();
```
Use `attach()` / `detach()` for layer membership; not `addChild` / `removeChild`. RenderLayer overrides the scene graph methods to throw errors.
### Sorted layers
```ts
const sortedLayer = new RenderLayer({
sortableChildren: true,
sortFunction: (a, b) => a.position.y - b.position.y,
});
sortedLayer.attach(sprite1, sprite2, sprite3);
```
Set `sortableChildren: true` on the layer (not the object) and optionally pass a custom `sortFunction`. The default sort is by `zIndex`. Common use: y-sort for 2D top-down games so objects draw in depth order based on world y-position.
### Manual sort
```ts
const layer = new RenderLayer({ sortableChildren: false });
layer.attach(sprite1, sprite2, sprite3);
layer.sortRenderLayerChildren();
```
If you turn off automatic sorting, call `sortRenderLayerChildren()` manually when you want the sort to happen. Useful when the sort order changes less often than every frame.
### Layer + logical parent
```ts
const world = new Container();
const hud = new RenderLayer();
app.stage.addChild(world, hud);
const player = new Sprite(playerTexture);
world.addChild(player);
hud.attach(player);
world.x = 100; // player still moves with world
```
The player's transform chain goes through `world`; moving `world.x` moves the player visually. But the renderer places the player's draw call at `hud`'s position in the scene graph, so the player renders on top of everything else.
### Removing from scene graph auto-detaches
```ts
world.removeChild(player);
// player is automatically detached from entityLayer
```
When you remove an object from its scene graph parent (via `removeChild`), the render layer attachment is cleared automatically. Re-adding the object to a scene graph parent does NOT re-attach it; you must call `layer.attach(player)` again.
## Common Mistakes
### [CRITICAL] Using `addChild` on a RenderLayer
Wrong:
```ts
const layer = new RenderLayer();
layer.addChild(sprite);
```
Correct:
```ts
const layer = new RenderLayer();
container.addChild(sprite);
layer.attach(sprite);
```
`RenderLayer` throws on `addChild`. The object still needs a real scene graph parent (via `addChild` on a Container) for transforms; use `layer.attach()` to control render order.
### [HIGH] Layer and attached children in different render groups
Wrong:
```ts
const renderGroup = new Container({ isRenderGroup: true });
const layer = new RenderLayer();
renderGroup.addChild(sprite);
app.stage.addChild(layer);
layer.attach(sprite);
```
Correct:
```ts
const renderGroup = new Container({ isRenderGroup: true });
const layer = new RenderLayer();
renderGroup.addChild(sprite);
renderGroup.addChild(layer);
layer.attach(sprite);
```
A layer and the objects it attaches must be in the same render group. Otherwise the attached child renders without its correct transform composition.
### [MEDIUM] Expecting parent filters to apply to layer children
Filters on an ancestor Container are applied by capturing the container's children into a texture via push/pop. Layer-attached children skip this capture; they're collected separately and drawn at the layer's position. If you need a filter on a layer-attached object, apply the filter directly to the object (not the ancestor).
## API Reference
- [RenderLayer](https://pixijs.download/release/docs/scene.RenderLayer.html.md)
- [RenderLayerOptions](https://pixijs.download/release/docs/scene.RenderLayerOptions.html.md)
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
@@ -0,0 +1,129 @@
# Masking
Clip display objects with PixiJS masks. PixiJS supports four mask types: AlphaMask (sprite-based), StencilMask (Graphics/Container-based via the stencil buffer), ScissorMask (axis-aligned rectangle), and ColorMask (bit-mask on channels).
## Quick Start
```ts
const photoGroup = new Container();
photoGroup.addChild(new Sprite(await Assets.load("photo.png")));
const mask = new Graphics().circle(100, 100, 80).fill(0xffffff);
photoGroup.mask = mask;
photoGroup.addChild(mask);
app.stage.addChild(photoGroup);
```
A mask should live in the scene graph of the masked object's parent (typically as a child of the masked Container) so its transform tracks the masked subtree. Sprites, Text, and other leaves cannot hold the mask as a child (`allowChildren = false`); wrap them in a `Container` as shown above.
Set `container.mask` to a display object. PixiJS automatically selects the mask type based on what you assign.
## Core Patterns
### Mask type selection
PixiJS picks the mask type automatically based on the mask object:
| Mask object | Type used | Cost | Notes |
| --------------------- | ----------- | --------- | ------------------------------- |
| Graphics or Container | StencilMask | Medium | Uses stencil buffer |
| Sprite | AlphaMask | Expensive | Uses filter pipeline internally |
| Number (e.g., `0xF`) | ColorMask | Cheapest | Bitmask on RGBA channels |
Performance hierarchy: ColorMask (cheapest) < StencilMask < AlphaMask (most expensive). Choose the simplest mask that achieves the visual result.
Note: `ScissorMask` exists in the codebase but is not auto-selected by the mask system. Only `AlphaMask`, `StencilMask`, and `ColorMask` are registered as mask effects.
### Stencil mask (Graphics-based)
```ts
const container = new Container();
const mask = new Graphics().roundRect(0, 0, 200, 150, 20).fill(0xffffff);
container.mask = mask;
container.addChild(mask);
```
The mask Graphics should be a child of the masked container (or share the same coordinate space). The fill color doesn't matter; only the shape is used.
### Alpha mask (Sprite-based)
```ts
const maskTexture = await Assets.load("gradient-mask.png");
const maskSprite = new Sprite(maskTexture);
const photoGroup = new Container();
photoGroup.addChild(new Sprite(await Assets.load("photo.png")));
photoGroup.mask = maskSprite;
photoGroup.addChild(maskSprite);
```
Alpha masks use the **red channel** of the sprite texture by default to control visibility. High red value = fully visible, zero red = hidden. This is the most expensive mask type because it uses the filter pipeline internally.
### Mask channel selection
By default, sprite (alpha) masks read the red channel. If your mask texture uses transparency instead (e.g., a PNG with an alpha gradient), switch to the alpha channel via `setMask`:
```ts
const maskSprite = new Sprite(await Assets.load("alpha-gradient.png"));
const photoGroup = new Container();
photoGroup.addChild(new Sprite(await Assets.load("photo.png")));
photoGroup.setMask({ mask: maskSprite, channel: "alpha" });
photoGroup.addChild(maskSprite);
```
Available channels: `'red'` (default), `'alpha'`. This is useful when a single mask texture encodes different shapes in different channels.
### Inverse masking
Use `setMask` with `inverse: true` to show everything outside the mask shape:
```ts
const holeMask = new Graphics().circle(100, 100, 80).fill(0xffffff);
const container = new Container();
container.setMask({ mask: holeMask, inverse: true });
container.addChild(holeMask);
const maskSprite = new Sprite(await Assets.load("mask.png"));
const photoGroup = new Container();
photoGroup.addChild(new Sprite(await Assets.load("photo.png")));
photoGroup.setMask({ mask: maskSprite, inverse: true });
photoGroup.addChild(maskSprite);
```
Both alpha and stencil masks support inverse on WebGL and WebGPU. Canvas2D does not support inverse stencil masks (it logs a warning and ignores the flag).
### Removing a mask
```ts
container.mask = null;
mask.destroy();
// Sprite masks: clear the mask before destroying its texture
photoGroup.mask = null;
maskSprite.destroy({ texture: true, textureSource: true });
```
Always use `container.mask = null` to clear a mask. `setMask({ mask: null })` does not work due to an internal falsy check. Remove the mask reference before destroying the mask, the masked object, or (for sprite masks) the mask's texture. A sprite mask whose texture is destroyed while still assigned renders as empty and, in debug builds, logs `[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture.`
## Common Mistakes
### [HIGH] Using cacheAsTexture with masks
The combination of `cacheAsTexture()` and masks is fragile. In Firefox, it can require a timeout between setting the mask and enabling caching. In other cases it fails silently. Avoid combining them when possible, or test thoroughly across browsers if needed.
### [MEDIUM] Using too many sprite masks
Sprite masks (AlphaMask) use the filter pipeline internally, making them the most expensive mask type. Using many of them simultaneously degrades performance significantly. Prefer stencil masks (Graphics shapes) or scissor masks (axis-aligned rectangles) when the visual result allows it.
Performance cost: Scissor (near zero) < Stencil (one extra draw) < Alpha (full filter pass)
## API Reference
- [AlphaMask](https://pixijs.download/release/docs/rendering.AlphaMask.html.md)
- [StencilMask](https://pixijs.download/release/docs/rendering.StencilMask.html.md)
- [ScissorMask](https://pixijs.download/release/docs/rendering.ScissorMask.html.md)
- [ColorMask](https://pixijs.download/release/docs/rendering.ColorMask.html.md)
- [MaskEffectManager](https://pixijs.download/release/docs/rendering.MaskEffectManager.html.md)
@@ -0,0 +1,140 @@
# Render Groups
A render group is a `Container` whose transform (position, scale, rotation, alpha, tint) is applied on the GPU as a single operation rather than being recalculated per-child on the CPU every frame. Use render groups for large stable sub-trees such as a game world, a HUD, or a parallax strip. Each render group owns its own instruction set and cannot batch with other groups.
## Quick Start
```ts
const world = new Container({ isRenderGroup: true });
const hud = new Container({ isRenderGroup: true });
app.stage.addChild(world, hud);
for (let i = 0; i < 5000; i++) {
const bunny = new Sprite(bunnyTexture);
bunny.x = Math.random() * 2000;
bunny.y = Math.random() * 2000;
world.addChild(bunny);
}
world.x = 100; // applied once on the GPU, not 5000 times on the CPU
```
Flag a container with `isRenderGroup: true` at construction, or call `enableRenderGroup()` at runtime.
## Core Patterns
### Construction options
```ts
const world = new Container({ isRenderGroup: true });
const hud = new Container();
hud.enableRenderGroup();
```
Both forms work. Pre-declare via the options object for static setups; call `enableRenderGroup()` when you want to flip the flag at runtime.
### The three transform levels
When a render group is in the chain, PixiJS composes three matrices:
1. `localTransform`; from the container's own position, scale, rotation, pivot, skew.
2. `groupTransform`; the child's position relative to the render group it belongs to.
3. `worldTransform`; the scene-root-space matrix.
For children inside a render group, the CPU only maintains `localTransform` and `groupTransform`. The GPU applies the group's own `worldTransform` once, then draws all the children. This is the performance win: the per-child CPU matrix math is cut from "one full walk per frame" to "one walk when children move."
### When to use render groups
Good fits:
- Game world with thousands of static entities.
- UI layer that mostly stays put.
- Parallax background strips.
- A menu or HUD overlay that scales or translates as a whole.
Bad fits:
- Small sub-trees (a dozen children). Overhead outweighs the save.
- Constantly-changing structure (children being added / removed per frame).
- Sub-trees that need to batch with other objects outside the group.
### Profile before adding
```ts
// Start without explicit render groups
const world = new Container();
// Measure frames, identify bottleneck
// Add if CPU transform updates dominate
world.enableRenderGroup();
```
Most scenes don't need explicit render groups beyond the auto-created root. The scene root container passed to `renderer.render()` is automatically a render group. Add explicit groups only when profiling shows CPU transform costs dominating.
### Render groups vs cacheAsTexture
```ts
const hud = new Container();
hud.cacheAsTexture({ antialias: true });
const world = new Container({ isRenderGroup: true });
```
- `cacheAsTexture()` rasterizes the sub-tree once to a texture and draws that texture each frame. Best for things that don't change visually.
- `isRenderGroup` keeps normal drawing but moves the group transform work to the GPU. Best for sub-trees whose children animate freely but whose structure is stable.
Render groups are lighter than cacheAsTexture and preserve dynamic children. Use cacheAsTexture only when the sub-tree is genuinely static.
## Common Mistakes
### [MEDIUM] Overusing render groups
Wrong:
```ts
for (const enemy of enemies) {
enemy.enableRenderGroup();
}
```
Each render group has its own instruction set and can't batch with other groups. A scene with many small render groups generates many separate draw buckets, which is slower than a single batched draw. Apply render groups at a coarse level (world, HUD), not per-entity.
### [HIGH] Nesting many render groups
Wrong:
```ts
const world = new Container({ isRenderGroup: true });
const section = new Container({ isRenderGroup: true });
const tile = new Container({ isRenderGroup: true });
world.addChild(section);
section.addChild(tile);
```
Correct:
```ts
const world = new Container({ isRenderGroup: true });
const section = new Container();
const tile = new Container();
world.addChild(section);
section.addChild(tile);
```
Deep nesting of render groups multiplies the instruction set overhead. Pick a single level (usually one per "subsystem") and let the children be normal containers.
### [MEDIUM] Constantly adding/removing from a render group
If the sub-tree structure changes every frame (not just child transforms), the render group's instruction set is rebuilt each time, negating the performance benefit. Render groups help stable structures with animated children; not dynamic structures.
## API Reference
- [RenderGroup](https://pixijs.download/release/docs/rendering.RenderGroup.html.md)
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [ContainerOptions](https://pixijs.download/release/docs/scene.ContainerOptions.html.md)
@@ -0,0 +1,169 @@
# Scene Management: Render Groups, Layers, and Culling
Organize PixiJS scenes with render groups (GPU-level transforms), RenderLayer (decoupled render order), culling (offscreen optimization), zIndex sorting, and boundsArea optimization.
## Quick Start
```ts
const world = new Container({ isRenderGroup: true });
const hud = new Container({ isRenderGroup: true });
app.stage.addChild(world, hud);
const bgLayer = new RenderLayer();
const entityLayer = new RenderLayer();
const uiLayer = new RenderLayer();
app.stage.addChild(bgLayer, entityLayer, uiLayer);
const player = new Sprite(texture);
world.addChild(player);
entityLayer.attach(player);
```
## Core Patterns
### Render groups for GPU-level transforms
A render group is a container whose transform (position, scale, rotation, alpha, tint) is applied on the GPU as a single operation rather than being recalculated per-child on the CPU. The root container passed to `renderer.render()` is automatically a render group.
```ts
const gameWorld = new Container({ isRenderGroup: true });
const uiLayer = new Container({ isRenderGroup: true });
scene.addChild(gameWorld, uiLayer);
gameWorld.x += 10;
const panel = new Container();
panel.enableRenderGroup();
```
Use render groups for large stable sub-trees (the structure stays the same even though children move/rotate). Children inside can still animate freely; "stable" means children are not being constantly added/removed.
The scene has three matrix levels:
1. `localTransform` - based on the container's own position/scale/rotation
2. `groupTransform` - relative to the render group it belongs to
3. `worldTransform` - relative to the scene root
### RenderLayer for decoupled render order
RenderLayer separates render order from scene graph hierarchy. Objects keep their logical parent for transforms but render at the layer's position in the scene.
```ts
const bgLayer = new RenderLayer();
const entityLayer = new RenderLayer();
const uiLayer = new RenderLayer();
app.stage.addChild(bgLayer, entityLayer, uiLayer);
const player = new Sprite(texture);
const world = new Container();
world.addChild(player);
entityLayer.attach(player);
entityLayer.detach(player);
entityLayer.detachAll();
const sortedLayer = new RenderLayer({
sortableChildren: true,
sortFunction: (a, b) => a.position.y - b.position.y,
});
```
Key constraints:
- `addChild()` / `removeChild()` on RenderLayer throws an error. Use `attach()` / `detach()`.
- Objects removed from their scene graph parent via `removeChild()` are automatically detached from their layer.
- Re-adding an object to the scene graph does NOT automatically re-attach it to the layer. You must call `attach()` again.
- Layers and their children must belong to the same render group.
### Culling
Culling skips rendering objects outside the visible area. In v8, culling is manual; it does not happen automatically during render.
```ts
const stage = new Container();
for (let i = 0; i < 1000; i++) {
const sprite = Sprite.from("bunny.png");
sprite.x = Math.random() * 5000;
sprite.y = Math.random() * 5000;
sprite.cullable = true;
stage.addChild(sprite);
}
const view = { x: 0, y: 0, width: 800, height: 600 };
Culler.shared.cull(stage, view);
renderer.render(stage);
```
For automatic culling with Application, register CullerPlugin:
```ts
import { extensions, CullerPlugin } from "pixi.js";
extensions.add(CullerPlugin);
const app = new Application();
await app.init({ width: 800, height: 600 });
```
Set `cullArea` on a container to define a custom cull region instead of computing bounds:
```ts
container.cullArea = new Rectangle(0, 0, 1000, 1000);
container.cullable = true;
```
### zIndex sorting
```ts
const parent = new Container({ sortableChildren: true });
const bg = new Sprite(bgTexture);
bg.zIndex = 0;
const player = new Sprite(playerTexture);
player.zIndex = 10;
const fg = new Sprite(fgTexture);
fg.zIndex = 20;
parent.addChild(fg, bg, player);
```
Setting `zIndex` on a child automatically enables `sortableChildren` on its parent, so the explicit constructor option is only needed when you want sorting enabled before any child sets a zIndex.
### boundsArea optimization
Setting `boundsArea` on a container prevents recursive bounds measurement of all children. Useful for containers with many children whose aggregate bounds are known.
```ts
const particles = new Container();
particles.boundsArea = new Rectangle(0, 0, 800, 600);
```
## Common Mistakes
### MEDIUM: Overusing render groups
Each render group has its own instruction set and cannot batch with other groups. Use render groups at a broad level (game world, HUD), not per-child. Profile before adding them; most scenes do not need any explicit render groups beyond the auto-created root.
### HIGH: Expecting automatic culling
v8 culling is explicit. Setting `cullable=true` only marks the container as eligible. You must call `Culler.shared.cull()` before rendering, or register `CullerPlugin` for automatic culling with Application.
### MEDIUM: Expecting filters on ancestors to apply to layer children
RenderLayer children are rendered outside their parent's filter scope. Filters capture children into a texture via push/pop, but layer-attached children skip their parent's collection and render at the layer's position instead. Apply filters directly to the child when using RenderLayer.
### HIGH: Using addChild on RenderLayer
RenderLayer overrides `addChild`, `removeChild`, and related methods to throw errors. Use `attach()` and `detach()` for layer membership. The object still needs a scene graph parent via `addChild` on a regular Container for transforms.
## API Reference
- [RenderLayer](https://pixijs.download/release/docs/scene.RenderLayer.html.md)
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [Culler](https://pixijs.download/release/docs/scene.Culler.html.md)
- [CullerPlugin](https://pixijs.download/release/docs/app.CullerPlugin.html.md)
- [RenderGroup](https://pixijs.download/release/docs/rendering.RenderGroup.html.md)
@@ -0,0 +1,198 @@
# Transforms and Coordinate Spaces
Every `Container` has a transform: position, scale, rotation, pivot, skew, and origin. These combine into a `localTransform` matrix, which compounds with ancestors to produce the `worldTransform`. Use this reference for coordinate-space conversion and the details of setting vs. animating transforms. For matrix math, see `pixijs-math`.
## Quick Start
```ts
const hero = new Container();
hero.x = 100;
hero.y = 200;
hero.scale.set(2);
hero.rotation = Math.PI / 4;
const worldPoint = hero.toGlobal({ x: 0, y: 0 });
const localPoint = hero.toLocal({ x: 300, y: 300 });
```
Transforms are local to the parent. `toGlobal` and `toLocal` convert between coordinate spaces.
## Core Patterns
### Position, scale, rotation
```ts
container.x = 100;
container.y = 200;
container.position.set(100, 200);
container.scale.set(2); // uniform
container.scale.set(1.5, 0.8); // non-uniform
container.scale.x = 2;
container.rotation = Math.PI / 4; // radians
container.angle = 45; // degrees (convenience)
```
`position`, `scale`, and `pivot` are `ObservablePoint` instances; direct assignment via `x` / `y` works, or call `set(x, y?)`. Setting them triggers the parent's transform update flag.
### Pivot
```ts
sprite.pivot.set(sprite.width / 2, sprite.height / 2);
sprite.x = 200;
sprite.y = 200;
sprite.rotation += 0.01;
```
`pivot` is the point around which rotation and scale apply; in the **container's own local pixel space**. A pivot of `(w/2, h/2)` rotates around the center.
For `Sprite`, prefer `anchor` (normalized 0–1) which only shifts the texture draw origin without offsetting the position. Pivot shifts the position too.
### Origin (new in v8)
```ts
container.origin.set(100, 50);
```
`origin` is an alternative transform origin that shifts the rotation/scale pivot **without offsetting the visual position**. Think of it as "pivot, but without the position shift." Useful when you want to spin a large container around an off-center point while keeping it visually anchored to its `x` / `y`.
### Skew
```ts
container.skew.set(0.1, 0);
```
Rarely used. Skew shears the coordinate space by `x` / `y` radians. Useful for fake perspective and isometric effects.
### Coordinate conversion
```ts
const globalPoint = container.toGlobal({ x: 10, y: 20 });
const localPoint = container.toLocal({ x: 400, y: 300 });
const localFromSprite = container.toLocal({ x: 0, y: 0 }, otherSprite);
const cached = container.getGlobalPosition();
```
- `toGlobal(localPoint)`: convert from this container's local space to global (scene root) space.
- `toLocal(point, from?)`: convert from global (or another container's) space to this container's local space.
- `getGlobalPosition()`: shortcut for `toGlobal({ x: 0, y: 0 })`; this container's origin in global space.
All three accept an optional `point` argument to write into (reduces allocation in hot paths) and a `skipUpdate` flag that uses the cached transform (faster but can be stale).
### The three matrices
```ts
container.localTransform; // from this node's own position/scale/rotation/pivot/skew
container.groupTransform; // relative to the render group it belongs to
container.worldTransform; // relative to the scene root
```
Each frame, PixiJS composes these three levels:
1. `localTransform`; derived from the container's own transform setters.
2. `groupTransform`; if an ancestor is a render group, this is the transform relative to that group.
3. `worldTransform`; relative to the scene root; what the renderer consumes.
For normal code, set `x` / `y` / `scale` / `rotation` and let the renderer compose the rest. Reading `worldTransform` directly is useful for hit testing, custom rendering, or integrating with physics.
### Sizing via width, height, setSize
```ts
container.width = 100;
container.height = 200;
container.setSize(100, 200);
const { width, height } = container.getSize();
```
Setting `width` and `height` scales the container to fit the requested dimensions; internally they assign `scale.x` / `scale.y` based on the measured bounds. Assigning the two setters independently re-measures the subtree twice, which is wasteful. Use `setSize(width, height?)` to assign both in a single pass, and `getSize()` to read them back as `{ width, height }`.
### Bounds in different spaces
```ts
const localBounds = container.getLocalBounds();
const globalBounds = container.getBounds();
const reusable = new Bounds();
container.getBounds(true, reusable); // skipUpdate + in-place
const rect = container.getBounds().rectangle;
rect.contains(pointerX, pointerY);
```
- `getLocalBounds()`: rectangle in the container's own local space.
- `getBounds(skipUpdate?, bounds?)`: rectangle in world space (accounts for all ancestor transforms). Pass `true` for `skipUpdate` to reuse the cached transform instead of forcing a fresh pass, and pass an existing `Bounds` instance as the second argument to avoid allocating a new one.
Both methods return a `Bounds` instance, not a `Rectangle`. `Bounds` exposes `x`, `y`, `width`, and `height` getters plus a `.rectangle` accessor for APIs like `Rectangle.contains()`.
Bounds are recalculated lazily. Call them sparingly; each call walks the container's sub-tree. For containers with many cheap children (particles, tile layers), set `container.boundsArea = new Rectangle(0, 0, w, h)` so `getBounds()` returns that rectangle directly without recursing.
### Global, local, and screen coordinates
PixiJS uses three coordinate spaces:
- **Local**: relative to the object's parent. This is what `container.x` / `container.y` and `position.set()` always operate on.
- **Global** (a.k.a. "world"): relative to the scene root. `toGlobal()`, `toLocal()`, and `getGlobalPosition()` convert between local and global space.
- **Screen** (a.k.a. "viewport"): relative to the top-left of the canvas element PixiJS is rendering into. DOM events and native mouse clicks use screen space.
Global and screen usually match, but they diverge when the canvas is CSS-scaled or rendered at a non-1 resolution. PixiJS's event system handles this conversion automatically for pointer events, so `onPointerDown` handlers always receive global coordinates. When you need raw screen coordinates, read `renderer.events.pointer`; use `toLocal` / `toGlobal` for the world side.
### Cumulative alpha (getGlobalAlpha)
`container.alpha` is local to the container; the cumulative alpha (parent × this × ancestors) is exposed via `container.getGlobalAlpha(skipUpdate?)`. It's computed during render, so reading it before the first frame returns 1 on a freshly-added subtree. Useful for custom render hooks that need to know how transparent the renderer will actually draw this node.
## Common Mistakes
### [HIGH] Setting scale to 0
Wrong:
```ts
container.scale.set(0);
```
Correct:
```ts
container.scale.set(0.01); // or use visible = false
container.visible = false;
```
Scale of exactly 0 collapses the transform matrix to zero, and any subsequent `toLocal` / `toGlobal` / inverse calculations divide by zero. Use `visible = false` to hide, or scale to a tiny non-zero value if you need an animation.
### [MEDIUM] Reading world transform before first render
Wrong:
```ts
const pos = container.getGlobalPosition();
console.log(pos); // { x: 0, y: 0 } even though container.x is set
```
Correct:
```ts
app.stage.addChild(container);
await new Promise((r) => requestAnimationFrame(r));
const pos = container.getGlobalPosition();
```
`worldTransform` is computed during render. Before the first render, it's identity. If you need a live position before rendering, use `container.toGlobal({x:0, y:0})` which walks the transforms explicitly.
### [MEDIUM] Confusing anchor and pivot
On `Sprite`, `anchor` is normalized (0–1) and shifts only the draw origin. `pivot` is in pixel space and shifts both the transform origin AND the visual position. For centering a sprite, use `anchor`. For off-center rotation of a Container (which has no `anchor`), use `pivot`.
## API Reference
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
- [ToLocalGlobalMixin](https://pixijs.download/release/docs/scene.ToLocalGlobalMixin.html.md)
- [Matrix](https://pixijs.download/release/docs/maths.Matrix.html.md)
- [ObservablePoint](https://pixijs.download/release/docs/maths.ObservablePoint.html.md)
@@ -0,0 +1,193 @@
---
name: pixijs-scene-dom-container
description: "Use this skill when overlaying HTML elements on the PixiJS v8 canvas. Covers DOMContainer with element, anchor, and scene-graph-driven CSS transforms, the pixi.js/dom side-effect import, DOMPipe registration, visibility sync, pointer-events handling. Triggers on: DOMContainer, pixi.js/dom, DOMPipe, HTML overlay, input on canvas, iframe overlay, DOMContainerOptions, element, anchor, constructor options."
license: MIT
---
`DOMContainer` positions an HTML element over the PixiJS canvas and drives its CSS transform from the scene graph. Use it for native inputs, iframes, videos, or rich HTML that needs to follow a display object's position. The default `pixi.js` browser bundle registers the `DOMPipe` automatically; custom builds add a side-effect `import 'pixi.js/dom'`.
> `DOMContainer` is marked EXPERIMENTAL in PixiJS v8. The API may change between minor releases.
Assumes familiarity with `pixijs-scene-core-concepts`. `DOMContainer` extends `ViewContainer`, so it's a leaf: do not nest PixiJS children inside it. Nest DOM content inside the HTML element itself, or wrap multiple `DOMContainer` instances in a `Container`. Not available in Web Workers; a worker has no DOM to overlay.
## Quick Start
```ts
import "pixi.js/dom";
const input = document.createElement("input");
input.type = "text";
input.placeholder = "Enter name...";
const dom = new DOMContainer({
element: input,
anchor: 0.5,
});
dom.position.set(app.screen.width / 2, app.screen.height / 2);
app.stage.addChild(dom);
```
**Related skills:** `pixijs-scene-core-concepts` (scene graph basics), `pixijs-scene-container` (wrap multiple DOM overlays), `pixijs-events` (pointer handling on canvas vs DOM), `pixijs-accessibility` (screen-reader overlays).
## Constructor options
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
Leaf-specific options added by `DOMContainerOptions`:
| Option | Type | Default | Description |
| --------- | --------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `element` | `HTMLElement` | `document.createElement('div')` | The HTML element the container drives. Any element is valid: `input`, `textarea`, `iframe`, `video`, `div`, etc. If omitted, a bare `<div>` is created. |
| `anchor` | `PointData \| number` | `0` | Origin of the element relative to its own dimensions. `0` is top-left, `0.5` centers, `1` is bottom-right. A single number sets both axes; `{ x, y }` sets each independently. |
`tint`, `filters`, `mask`, and `blendMode` are accepted (inherited from `Container`) but have no visual effect — DOM elements live outside the WebGL/WebGPU pipeline. Style the element via CSS for those effects.
## Core Patterns
### Setup and the side-effect import
```ts
import "pixi.js/dom";
import { DOMContainer } from "pixi.js";
```
Or use the combined import that registers the pipe and re-exports the class:
```ts
import { DOMContainer } from "pixi.js/dom";
```
The default `pixi.js` browser bundle already imports `pixi.js/dom` for you via `browserAll.ts`, so `DOMContainer` works out of the box in a typical browser app. You only need the explicit `import 'pixi.js/dom'` line when you set `skipExtensionImports: true` (custom builds) or when running under a non-browser bundle.
### Transforms, anchor, and alpha
```ts
const dom = new DOMContainer({
element: document.createElement("div"),
anchor: 0.5,
});
dom.position.set(400, 300);
dom.scale.set(1.5);
dom.rotation = Math.PI / 8;
dom.alpha = 0.5;
```
Transforms on the `DOMContainer` propagate to the element as CSS `transform`. `anchor` shifts the element's origin relative to its own dimensions: `0` is top-left, `0.5` centers, `1` is bottom-right. A single number sets both axes; an object `{ x, y }` sets each independently. `alpha` (including inherited parent alpha) is written to the element's `style.opacity` every frame.
If no `element` is provided, a `<div>` is created by default.
### Styling the element directly
```ts
const panel = document.createElement("div");
panel.innerHTML = "<h2>Score</h2><p>1500</p>";
panel.style.color = "white";
panel.style.fontFamily = "Arial";
panel.style.pointerEvents = "none";
const dom = new DOMContainer({ element: panel });
dom.position.set(50, 50);
app.stage.addChild(dom);
```
PixiJS does not interfere with CSS styling on the element. The shared root `<div>` is set to `pointer-events: none`, and each attached element defaults to `pointer-events: auto`. Override to `none` on purely decorative overlays so the canvas still receives clicks underneath them.
### Visibility and cleanup
```ts
dom.visible = false;
dom.visible = true;
dom.destroy();
```
Setting `visible = false` or removing the `DOMContainer` from the scene graph detaches the element from the DOM. Restoring visibility re-attaches it. `destroy()` removes the element from its parent node and nulls internal references; the HTML element itself is preserved, so you can re-attach it elsewhere:
```ts
const element = dom.element;
dom.destroy();
document.body.appendChild(element);
```
### The DOM container root
The DOMPipe uses a shared root `<div>` with `z-index: 1000` that hosts every attached element. It's exposed as `app.domContainerRoot` (an `HTMLDivElement`). All `DOMContainer` elements render above canvas content; you can't interleave DOM elements between PixiJS draw calls.
On the first render that has an attached `DOMContainer`, the pipe automatically appends the root to the canvas's parent node. Append it yourself next to `app.canvas` if you need explicit, stable placement in the DOM tree (for example, when the canvas shares a wrapper with other layered content):
```ts
document.body.appendChild(app.canvas);
document.body.appendChild(app.domContainerRoot);
```
The root uses absolute positioning and its transform is recomputed from the canvas `getBoundingClientRect()` via a `ResizeObserver`, so CSS-scaled canvases stay aligned without extra work.
## Common Mistakes
### [MEDIUM] Missing the pixi.js/dom import in custom builds
The default browser bundle auto-registers `DOMPipe`, so most apps do not need an explicit import. It is only required when you opt out of auto-imports:
```ts
await app.init({ skipExtensionImports: true });
// Now you must add this yourself:
import "pixi.js/dom";
```
Without registration under a custom build, `DOMContainer` is still importable but the renderer has no pipe to process it; elements never synchronize with the scene graph and never appear.
### [MEDIUM] Expecting filters, masks, or blend modes to affect DOM elements
Wrong:
```ts
const dom = new DOMContainer();
dom.filters = [new BlurFilter()];
```
Correct:
```ts
dom.element.style.filter = "blur(4px)";
```
DOM elements are HTML overlays positioned via CSS transforms; they exist outside the WebGL/WebGPU pipeline. PixiJS filters, masks, and blend modes have no effect on them. Use CSS filters and CSS `mix-blend-mode` on the element directly.
### [MEDIUM] Do not nest children inside a DOMContainer
Wrong:
```ts
const dom = new DOMContainer();
dom.addChild(new Sprite(texture));
```
Correct:
```ts
const group = new Container();
group.addChild(dom, new Sprite(texture));
```
`DOMContainer` extends `ViewContainer`, which sets `allowChildren = false`. It is a leaf in the PixiJS scene graph. For PixiJS children, wrap the `DOMContainer` alongside them in a plain `Container`. For nested HTML, nest inside the element itself (`element.appendChild(...)`).
### [LOW] Forgetting to set anchor for centered positioning
The default anchor is `(0, 0)`, placing the element's top-left corner at the container's position. For centering a UI element on its scene-graph position, set `anchor: 0.5`:
```ts
const dom = new DOMContainer({ element: myElement, anchor: 0.5 });
dom.position.set(400, 300);
```
## API Reference
- [DOMContainer](https://pixijs.download/release/docs/scene.DOMContainer.html.md)
- [DOMContainerOptions](https://pixijs.download/release/docs/scene.DOMContainerOptions.html.md)
- [ViewContainer](https://pixijs.download/release/docs/scene.ViewContainer.html.md)
- [Container](https://pixijs.download/release/docs/scene.Container.html.md)
+233
View File
@@ -0,0 +1,233 @@
---
name: pixijs-scene-gif
description: "Use this skill when displaying animated GIFs in PixiJS v8. Covers the pixi.js/gif side-effect import, Assets.load returning a GifSource, GifSprite playback (play/stop/currentFrame/animationSpeed), autoPlay/loop options, onComplete/onLoop/onFrameChange callbacks, GifSource sharing, clone, destroy. Triggers on: GifSprite, GifSource, pixi.js/gif, animationSpeed, currentFrame, autoPlay, onComplete, onFrameChange, constructor options, GifSpriteOptions."
license: MIT
---
`GifSprite` plays an animated GIF as a display object. `Assets.load('animation.gif')` returns a `GifSource` (not a `Texture`), and you wrap that in a `GifSprite`. Requires a side-effect `import 'pixi.js/gif'` to register the loader extension.
Assumes familiarity with `pixijs-scene-core-concepts`. `GifSprite` extends `Sprite`, so it is a leaf: do not nest children inside it. Wrap multiple `GifSprite` instances in a `Container` to group them.
## Quick Start
```ts
import "pixi.js/gif";
import { GifSprite } from "pixi.js/gif";
const source = await Assets.load("animation.gif");
const gif = new GifSprite({
source,
autoPlay: true,
loop: true,
animationSpeed: 1,
});
gif.anchor.set(0.5);
gif.x = app.screen.width / 2;
gif.y = app.screen.height / 2;
app.stage.addChild(gif);
```
> [!NOTE]
> GIFs decode every frame into a separate canvas texture. For performance-critical animations with many frames, prefer a spritesheet with `AnimatedSprite` — it uses a single atlas texture and batches better on the GPU.
**Related skills:** `pixijs-scene-core-concepts` (scene graph basics), `pixijs-scene-sprite` (`AnimatedSprite` for spritesheet-based animation), `pixijs-assets` (`Assets.load`, caching, unloading), `pixijs-ticker` (frame timing), `pixijs-performance` (texture memory).
## Constructor options
`GifSpriteOptions` extends `Omit<SpriteOptions, 'texture'>`; `texture` is managed internally (set from `source.textures[0]` and swapped per frame). All other `Sprite` options (`anchor`, `scale`, `tint`, `roundPixels`, etc.) are valid, and all `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
Leaf-specific options added by `GifSpriteOptions`:
| Option | Type | Default | Description |
| ---------------- | --------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------- |
| `source` | `GifSource` | — | Required. The parsed GIF data returned by `Assets.load('file.gif')`. Can be shared across multiple `GifSprite` instances. |
| `autoPlay` | `boolean` | `true` | Start playback immediately on construction. If `false`, you must call `gif.play()` to begin. |
| `loop` | `boolean` | `true` | Repeat the animation on reaching the last frame. When `false`, the sprite stops at the final frame and fires `onComplete`. |
| `animationSpeed` | `number` | `1` | Multiplier on the GIF's native frame timing. `2` runs at double speed; `0.5` runs at half. |
| `autoUpdate` | `boolean` | `true` | Connect playback to `Ticker.shared`. Set to `false` to drive updates yourself via `gif.update(ticker)`. |
| `fps` | `number` | `30` | Fallback frame rate for GIFs that do not specify per-frame delays. |
| `onComplete` | `() => void \| null` | `null` | Called when a non-looping animation reaches the last frame. |
| `onLoop` | `() => void \| null` | `null` | Called each time a looping animation wraps around. |
| `onFrameChange` | `(frame: number) => void \| null` | `null` | Called every time the displayed frame index changes. |
| `scaleMode` | `SCALE_MODE` | `'linear'` | Deprecated since 8.13.0 — pass `scaleMode` via `Assets.load(..., { data: { scaleMode } })` instead. |
The constructor also accepts a bare `GifSource` as its sole argument (`new GifSprite(source)`), which is shorthand for `new GifSprite({ source })` using the defaults above.
## Core Patterns
### Setup and the side-effect import
```ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
import { GifSprite } from "pixi.js/gif";
const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
```
`pixi.js/gif` calls `extensions.add(GifAsset)`, registering `.gif` with the asset loader. Without it, `Assets.load` does not recognize GIF files. `GifSprite` and `GifSource` are exported from `pixi.js/gif`, not `pixi.js`.
Importing a named export from `pixi.js/gif` also triggers the side effect, so a bare `import 'pixi.js/gif'` is only needed when you don't import anything from that path.
### Playback control
```ts
const gif = new GifSprite({ source });
gif.play();
gif.stop();
gif.currentFrame = 5;
gif.animationSpeed = 2;
gif.animationSpeed = 0.5;
gif.playing; // read-only
gif.progress; // 0-1 playback position
gif.totalFrames; // number of frames
gif.duration; // total duration in ms
```
`autoPlay: true` (default) starts playback immediately; `loop: true` (default) repeats. `animationSpeed` is a multiplier on the GIF's native frame timing. `currentFrame` is zero-based.
### Loading options
```ts
const source = await Assets.load({
src: "animation.gif",
data: {
fps: 12,
scaleMode: "nearest",
resolution: 2,
},
});
const fromDataUri = await Assets.load("data:image/gif;base64,R0lGODlh...");
```
Options in `data` are passed to `GifSource.from`. `fps` sets the fallback frame delay for GIFs that don't specify timing. `scaleMode` and `resolution` control the canvas textures created for each frame. The loader matches both `.gif` file extensions and `data:image/gif` URIs.
### Callbacks
```ts
const gif = new GifSprite({
source,
loop: false,
onComplete: () => console.log("animation finished"),
onLoop: () => console.log("loop completed"),
onFrameChange: (frame) => console.log("now on frame", frame),
});
```
- `onComplete` fires when a non-looping animation reaches the last frame.
- `onLoop` fires each time a looping animation wraps around.
- `onFrameChange` fires every time the displayed frame changes.
### Manual update mode
```ts
const gif = new GifSprite({ source, autoUpdate: false });
app.ticker.add((ticker) => {
gif.update(ticker);
});
```
`autoUpdate: false` disconnects from `Ticker.shared`. You call `gif.update(ticker)` yourself, passing any `Ticker` instance. Useful when animation should be driven by a private ticker (e.g., a pause-aware game ticker).
### Sharing source data and cloning
```ts
const source = await Assets.load("animation.gif");
const gif1 = new GifSprite({ source, autoPlay: true });
const gif2 = new GifSprite({ source, autoPlay: false });
const gif3 = gif1.clone();
gif3.animationSpeed = 0.5;
```
`GifSource` can be shared across multiple `GifSprite` instances; each sprite has independent playback state. `clone()` copies all playback settings but creates an independent instance.
## Common Mistakes
### [HIGH] Not importing pixi.js/gif
Wrong:
```ts
import { Assets } from "pixi.js";
const gif = await Assets.load("animation.gif");
```
Correct:
```ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
const source = await Assets.load("animation.gif");
```
The GIF loader extension must be registered before loading. Without the side-effect import, the loader does not recognize `.gif` files and the load either fails or returns raw data.
### [MEDIUM] Expecting Assets.load to return a Texture
Wrong:
```ts
const texture = await Assets.load("animation.gif");
const sprite = new Sprite(texture);
```
Correct:
```ts
const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
```
`Assets.load` on a GIF returns a `GifSource` containing frame textures and timing data. Pass the source to `GifSprite`; for a single still frame, read `source.textures[0]`.
### [MEDIUM] GIF memory not released on destroy
Wrong:
```ts
gif.destroy();
// GifSource and frame textures remain in memory
```
Correct:
```ts
gif.destroy(true);
// or
await Assets.unload("animation.gif");
```
GIF frames hold decoded pixel data as individual canvas textures. `gif.destroy()` (or `destroy(false)`) destroys the sprite but keeps the `GifSource` intact. Pass `true` to also destroy the source. For shared sources, only destroy when the last consumer is done, or call `Assets.unload` to let the asset cache handle it.
### [LOW] Do not nest children inside a GifSprite
`GifSprite` extends `Sprite`, which sets `allowChildren = false`. It is a leaf. To group a GIF with other display objects, wrap them all in a plain `Container`:
```ts
const group = new Container();
group.addChild(gif, label);
```
## API Reference
- [GifSprite](https://pixijs.download/release/docs/gif.GifSprite.html.md)
- [GifSpriteOptions](https://pixijs.download/release/docs/gif.GifSpriteOptions.html.md)
- [GifSource](https://pixijs.download/release/docs/gif.GifSource.html.md)
- [GifAsset](https://pixijs.download/release/docs/gif.GifAsset.html.md)
- [GifBufferOptions](https://pixijs.download/release/docs/gif.GifBufferOptions.html.md)
- [GifFrame](https://pixijs.download/release/docs/gif.GifFrame.html.md)
@@ -0,0 +1,576 @@
---
name: pixijs-scene-graphics
description: "Use this skill when drawing vector shapes and paths in PixiJS v8. Covers the Graphics API: shape-then-fill methods (rect/circle/ellipse/poly/roundRect/star/regularPoly/roundPoly/roundShape/filletRect/chamferRect), path methods (moveTo/lineTo/bezierCurveTo/quadraticCurveTo/arc/arcTo/arcToSvg/closePath), fill/stroke/cut, holes, FillGradient (linear/radial), FillPattern, GraphicsContext sharing, svg import/export, containsPoint hit testing, cloning, clearing, bounds, fillStyle/strokeStyle, draw-time transforms (rotateTransform/scaleTransform/translateTransform/setTransform/save/restore), default styles, GraphicsPath reuse. Triggers on: Graphics, GraphicsContext, rect, circle, poly, roundRect, fill, stroke, cut, hole, beginHole, FillGradient, FillPattern, moveTo, bezierCurveTo, svg, graphicsContextToSvg, svg export, GraphicsOptions, containsPoint, clone, clear, bounds, rotateTransform, translateTransform, setFillStyle, setStrokeStyle, GraphicsPath."
license: MIT
---
`Graphics` is the vector-drawing leaf of the PixiJS v8 scene graph. The v8 API follows a shape-then-style pattern: draw a shape or path with `rect`, `circle`, `moveTo`, etc., then apply `fill` and/or `stroke`. Every method returns `this` for chaining, and the drawing instructions live on a `GraphicsContext` that can be shared between instances.
Assumes familiarity with `pixijs-scene-core-concepts`. `Graphics` is a leaf: do not nest children inside it. Wrap multiple `Graphics` objects in a `Container` to group them.
## Quick Start
```ts
const g = new Graphics();
g.rect(10, 10, 200, 100)
.fill({ color: 0x3498db, alpha: 0.8 })
.stroke({ width: 3, color: 0x2c3e50 });
g.circle(300, 60, 40).fill(0xe74c3c);
g.moveTo(50, 200)
.lineTo(200, 200)
.bezierCurveTo(250, 250, 100, 300, 50, 250)
.closePath()
.fill(0x6c5ce7);
app.stage.addChild(g);
```
**Related skills:** `pixijs-scene-core-concepts` (scene graph basics), `pixijs-scene-container` (group graphics with other objects), `pixijs-scene-core-concepts/references/masking.md` (Graphics as a stencil mask), `pixijs-filters` (effects), `pixijs-performance` (batching, `cacheAsTexture`).
## Constructor options
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
Leaf-specific options added by `GraphicsOptions`:
| Option | Type | Default | Description |
| ------------- | ----------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `context` | `GraphicsContext` | new `GraphicsContext()` | Shared drawing context. Passing a context reuses its tessellated geometry across multiple `Graphics` nodes, avoiding duplicate GPU work. If omitted, each `Graphics` creates and owns a new context. |
| `roundPixels` | `boolean` | `false` | Rounds the final on-screen `x`/`y` to the nearest pixel. Produces crisper lines for pixel-art styles at the cost of smooth sub-pixel movement. |
The constructor also accepts a `GraphicsContext` instance as its sole argument (`new Graphics(ctx)`), which is shorthand for `new Graphics({ context: ctx })`.
## Core Patterns
### Shape-then-fill workflow
```ts
const g = new Graphics();
g.rect(10, 10, 200, 100)
.fill({ color: 0x3498db, alpha: 0.8 })
.stroke({ width: 3, color: 0x2c3e50 });
g.circle(150, 200, 40).fill(0xe74c3c);
g.roundRect(300, 10, 150, 80, 12).fill(0x2ecc71);
g.poly([0, 0, 60, 0, 30, 50], true).fill(0x9b59b6);
g.star(400, 200, 5, 40, 20, 0).fill(0xf39c12);
g.ellipse(100, 350, 60, 30).fill(0x1abc9c);
```
`fill()` accepts a `FillInput`: a color number/string, `{ color, alpha, texture, matrix, textureSpace }`, a `FillGradient`, a `FillPattern`, or a `Texture`. When filling with a texture, `textureSpace` controls coordinate mapping:
- `'local'` (default): texture is scaled to fit each shape's bounding box (normalized 0-1 coordinates).
- `'global'`: texture position/scale are relative to the Graphics object's coordinate system, shared across all shapes.
- Atlas sub-textures: `'global'` honors the frame origin and rotation, so a shape drawn at the frame's size matches a `Sprite` of that frame. `'local'` maps the whole source image; pass a `matrix` that targets the frame's region of the source, or `renderer.generateTexture()` the frame first.
`FillInput` also supports a nested `fill` subfield: a `FillStyle` options object can embed a `FillGradient` or `FillPattern` under its `fill` key, which applies the gradient or pattern alongside the `color`, `alpha`, `texture`, and `matrix` modifiers on the outer object.
`stroke()` accepts a color, a `FillGradient`, a `FillPattern`, or a `StrokeStyle` object that combines all `FillStyle` keys (`color`, `alpha`, `texture`, `matrix`, `fill`, `textureSpace`) with stroke attributes:
| Attribute | Default | Notes |
| ------------ | --------- | ----------------------------------------------------------------------- |
| `width` | `1` | Pixel width of the stroke. |
| `cap` | `'butt'` | One of `'butt'`, `'round'`, `'square'`. End style for open paths. |
| `join` | `'miter'` | One of `'miter'`, `'round'`, `'bevel'`. Corner style. |
| `miterLimit` | `10` | Caps how far miter joins extend before falling back to bevel. |
| `alignment` | `0.5` | `1` = inside the shape, `0.5` = centered, `0` = outside. |
| `pixelLine` | `false` | Aligns 1-pixel lines to the pixel grid for crisp output. Graphics-only. |
Strokes can use the same gradients and patterns as fills via `fill: gradient` or `texture: tex`:
```ts
const grad = new FillGradient({
end: { x: 1, y: 0 },
colorStops: [
{ offset: 0, color: 0xff0000 },
{ offset: 1, color: 0x0000ff },
],
});
g.rect(0, 0, 200, 100).stroke({
width: 8,
fill: grad,
join: "round",
cap: "round",
});
```
Both `fill()` and `stroke()` can be called after the same shape; calling `stroke()` immediately after `fill()` reuses the same path.
### Advanced shape primitives
```ts
g.regularPoly(100, 100, 50, 6, 0).fill(0x3498db);
g.roundPoly(250, 100, 50, 5, 10).fill(0xe74c3c);
g.chamferRect(350, 50, 100, 80, 15).fill(0x2ecc71);
g.filletRect(500, 50, 100, 80, 15).fill(0x9b59b6);
g.roundShape(
[
{ x: 50, y: 250, radius: 20 },
{ x: 150, y: 250, radius: 5 },
{ x: 150, y: 350, radius: 10 },
{ x: 50, y: 350, radius: 15 },
],
10,
).fill(0xf39c12);
```
### Holes with cut()
```ts
g.rect(0, 0, 200, 200).fill(0x00ff00).circle(100, 100, 50).cut();
```
`cut()` subtracts the current active path from the previously drawn fill or stroke. Rules:
- The hole must be **completely inside** the target shape. Holes that overlap edges or sit outside the shape will not render correctly because the renderer triangulates with the hole as an interior boundary.
- `cut()` looks back at up to the **last two** instructions. When you `fill()` and then `stroke()` the same path, a single `cut()` adds the hole to the stroke first; a second `cut()` adds it to the fill underneath.
- After `cut()`, the active path resets so you can start the next shape with `moveTo`, `rect`, etc.
- `cut()` applies to strokes too — `g.rect(...).stroke(...).circle(...).cut()` cuts a hole through the stroke outline.
Punch multiple holes with a single `cut()` by drawing several shapes into the active path before calling it. Each shape accumulates into the same hole path:
```ts
const g = new Graphics();
g.rect(350, 350, 150, 150).fill(0x00ff00);
// Draw three circles into the active path, then cut them all in one call
g.circle(375, 375, 25);
g.circle(425, 425, 25);
g.circle(475, 475, 25);
g.cut();
```
If you need holes on **separate** filled shapes, give each shape its own `fill()` and matching `cut()`:
```ts
g.rect(0, 0, 100, 100).fill(0x3498db);
g.circle(50, 50, 20).cut(); // hole in the rect
g.rect(120, 0, 100, 100).fill(0xe74c3c);
g.circle(170, 50, 20).cut(); // hole in the second rect
```
Calling `cut()` on a shape that already has a hole **adds** to the existing hole path rather than replacing it. Use this to layer holes additively.
### Paths and complex shapes
```ts
g.moveTo(50, 50)
.lineTo(200, 50)
.bezierCurveTo(250, 100, 250, 150, 200, 200)
.quadraticCurveTo(100, 250, 50, 200)
.closePath()
.fill({ color: 0x6c5ce7, alpha: 0.7 })
.stroke({ width: 2, color: 0xdfe6e9 });
```
Path methods: `moveTo`, `lineTo`, `bezierCurveTo`, `quadraticCurveTo`, `arc`, `arcTo`, `arcToSvg`, `closePath`. Call `beginPath()` to discard the current path and start a new one.
```ts
// arc(cx, cy, radius, startAngle, endAngle, counterclockwise?)
g.moveTo(80, 50)
.arc(50, 50, 30, 0, Math.PI)
.stroke({ width: 4, color: 0x2c3e50 });
// arcTo(x1, y1, x2, y2, radius) — rounded corner between two line segments
g.moveTo(150, 20)
.arcTo(200, 20, 200, 80, 20)
.lineTo(200, 80)
.stroke({ width: 2 });
// arcToSvg(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) — matches the SVG `A` command
g.moveTo(250, 50).arcToSvg(40, 20, 0, 1, 0, 330, 50).stroke({ width: 2 });
```
### Gradients and patterns
```ts
// Linear gradient
const linear = new FillGradient({
end: { x: 1, y: 0 },
colorStops: [
{ offset: 0, color: 0xff0000 },
{ offset: 1, color: 0x0000ff },
],
});
g.rect(0, 0, 200, 100).fill(linear);
// Radial gradient. Coordinates are normalized 0-1 in the default "local" space:
// inner circle at the center, outer circle reaching the edges.
const radial = new FillGradient({
type: "radial",
center: { x: 0.5, y: 0.5 },
innerRadius: 0,
outerCenter: { x: 0.5, y: 0.5 },
outerRadius: 0.5,
colorStops: [
{ offset: 0, color: 0xffffff },
{ offset: 1, color: 0x000000 },
],
});
g.circle(100, 100, 100).fill(radial);
// Pixel coordinates need textureSpace: "global"; the gradient then spans shapes.
const shared = new FillGradient({
type: "radial",
center: { x: 100, y: 100 },
outerRadius: 100,
textureSpace: "global",
colorStops: [
{ offset: 0, color: 0xffffff },
{ offset: 1, color: 0x000000 },
],
});
g.rect(0, 0, 200, 200).fill(shared);
const brick = await Assets.load("brick.png");
// Options-object form (preferred)
const pattern = new FillPattern({
texture: brick,
repetition: "repeat", // 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat'
textureSpace: "global", // 'global' (default) | 'local'
});
// Legacy positional form is still supported
const pattern2 = new FillPattern(brick, "repeat");
g.rect(0, 120, 200, 100).fill(pattern);
```
`FillGradient`'s default `type` is `'linear'` with `start {0,0}` to `end {0,1}` (vertical). Set `type: 'radial'` with `center`/`innerRadius` and `outerCenter`/`outerRadius` for radial gradients; `rotation` (radians, default `0`) and `scale` (default `1`) make it elliptical and apply to Graphics only. `textureSpace` defaults to `'local'` (normalized 0-1 shape coordinates); use `'global'` for pixel coordinates shared across shapes.
`FillPattern` takes an options object (`{ texture, repetition?, textureSpace? }`) or the legacy positional form (`new FillPattern(texture, repetition?)`). `repetition` selects the tiling mode. `textureSpace` controls how tiles map to shapes:
- `'global'` (default): tiles repeat continuously across the `Graphics` coordinate system, so adjacent shapes share one tiling grid. Best for backgrounds and seamless textures.
- `'local'`: a single tile fits each shape's bounds. Combine with `setTransform` to subdivide a shape into a tile grid.
Note `FillPattern` defaults `textureSpace` to `'global'`, unlike the `'local'` default for texture fills shown above.
`setTransform(matrix)` copies the given matrix directly onto the pattern transform to scale, rotate, or offset the tiling; call `setTransform()` with no argument to reset to identity.
Set `textureSpace` and the transform on the `FillPattern` itself. When a pattern is passed inside a style object (`fill({ fill: pattern, textureSpace: "local" })`), the pattern's own values replace the style's `textureSpace` and `matrix`.
### Drawing a texture directly
```ts
const tex = await Assets.load("icon.png");
// Draw the whole texture at (x, y) with optional tint
g.texture(tex, 0xffffff, 20, 20);
// Draw a subregion (dx, dy, dw, dh)
g.texture(tex, 0xff0000, 100, 20, 64, 64);
```
`Graphics.texture(texture, tint?, dx?, dy?, dw?, dh?)` is a shortcut for drawing a single textured rect without going through `fill()`. Useful for icons where you don't need the full sprite lifecycle.
### GraphicsContext sharing
```ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
g2.x = 100;
```
Context sharing avoids duplicate GPU geometry; the expensive tessellation runs once. You can also assign a context after construction: `g.context = existingContext`.
### SVG import and export
Parse SVG markup into the active context with `svg()`:
```ts
g.svg(`<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>`);
```
`svg()` parses `<path>` (with `fill-rule="evenodd"` holes), `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>`, `<polyline>`, and `<g>` grouping. Styling comes from `fill`, `stroke`, `stroke-width`, `fill-opacity`, `stroke-opacity`, and `opacity`, as attributes or inline `style`. `<linearGradient>` and `<radialGradient>` definitions in `<defs>` become `FillGradient`s applied through `url(#id)`; `gradientUnits` maps to `textureSpace` and percentage coordinates are accepted. Not supported: `transform` attributes, `<style>` blocks, `stroke-linecap`/`stroke-linejoin`/`stroke-dasharray`, `gradientTransform`, `spreadMethod`, `stop-opacity`, `<text>`, `<image>`, `<use>`, `<clipPath>`, `<mask>`, `<pattern>`. Unsupported elements log a warning and are skipped. Complex hole geometries may render inaccurately because Pixi's triangulation is performance-optimized.
Serialize a `Graphics` or `GraphicsContext` back to a self-contained SVG document string with `graphicsContextToSvg`:
```ts
import { Graphics, graphicsContextToSvg } from "pixi.js";
const g = new Graphics()
.rect(0, 0, 100, 50)
.fill({ color: 0xff0000 })
.circle(150, 25, 25)
.stroke({ color: 0x0000ff, width: 4 });
const svgString = graphicsContextToSvg(g, 2);
```
`graphicsContextToSvg(source, precision = 2)` is a pure function that reads the context's instructions and returns a complete `<svg>` string with an auto-computed `viewBox`. Pass a `Graphics` or a `GraphicsContext`; `precision` controls decimal places on emitted coordinates. Exports every shape-then-fill primitive (advanced ones like `regularPoly`/`filletRect` fall back to a shape-path), all path methods, stroke attributes (`width`, `cap`, `join`, `miterLimit`), `fill-opacity`/`stroke-opacity`, and `FillGradient` (linear and radial) via a `<defs>` block. Holes collapse into one `<path>` with `fill-rule="evenodd"`. `FillPattern` and texture fills have no SVG equivalent: patterns fall through to the fill's solid `color`, and `texture()` instructions are skipped entirely. Exported markup roundtrips back through `g.svg(...)` without cleanup, so you can export, store, and later reimport a shape into another `Graphics`.
### Reusing a GraphicsPath
```ts
const arrow = new GraphicsPath()
.moveTo(0, 0)
.lineTo(40, 0)
.lineTo(40, -10)
.lineTo(60, 10)
.lineTo(40, 30)
.lineTo(40, 20)
.lineTo(0, 20)
.closePath();
g.path(arrow).fill(0x3498db);
g.translateTransform(80, 0).path(arrow).fill(0xe74c3c);
```
`Graphics.path(graphicsPath)` (and `GraphicsContext.path()`) appends a prebuilt `GraphicsPath` onto the active path. Build once, draw many times.
### Draw-time transforms
`Graphics` has its own transform stack used **while drawing** that is separate from the `Container` transform applied to the rendered output. The drawing methods are renamed to avoid clashing with `Container.rotation`, `Container.scale`, `Container.position`:
| Drawing transform | Container transform |
| --------------------------------------------------------- | ------------------------- |
| `g.rotateTransform(angle)` | `g.rotation` |
| `g.scaleTransform(x, y?)` | `g.scale.set(x, y)` |
| `g.translateTransform(x, y?)` | `g.position.set(x, y)` |
| `g.setTransform(matrix)` or `setTransform(a,b,c,d,tx,ty)` | `g.setFromMatrix(matrix)` |
| `g.transform(matrix)` or `transform(a,b,c,d,tx,ty)` | n/a |
| `g.getTransform()` / `g.resetTransform()` | n/a |
```ts
const g = new Graphics();
g.translateTransform(100, 100)
.rotateTransform(Math.PI / 4)
.rect(-25, -25, 50, 50)
.fill(0x3498db);
// The square is rotated 45 degrees as it is added to the geometry.
// Setting g.rotation later rotates the entire Graphics on screen.
```
The drawing transform affects every subsequent shape and path command added to the context. Use `save()`/`restore()` to scope it.
### State save/restore
```ts
g.save();
g.translateTransform(100, 100);
g.rotateTransform(Math.PI / 4);
g.rect(0, 0, 50, 50).fill(0xff0000);
g.restore();
```
`save()` pushes the drawing transform, fill style, and stroke style onto a stack; `restore()` pops them. `Graphics` exposes `save`/`restore` directly, mirroring the underlying `GraphicsContext` calls.
### Default styles via setFillStyle / setStrokeStyle
```ts
g.setFillStyle({ color: 0x3498db, alpha: 0.8 }).setStrokeStyle({
width: 2,
color: 0x2c3e50,
});
g.rect(0, 0, 100, 100).fill().stroke();
g.circle(150, 50, 40).fill().stroke();
```
`setFillStyle()` and `setStrokeStyle()` configure the default style used by subsequent `fill()` / `stroke()` calls when no argument is passed. Read or replace the current style at any time via the `fillStyle` and `strokeStyle` getters/setters. Override the library-wide defaults by mutating `GraphicsContext.defaultFillStyle` and `GraphicsContext.defaultStrokeStyle` once at startup.
### Hit testing
```ts
const g = new Graphics().star(100, 100, 5, 60, 30).fill(0xf39c12);
g.eventMode = "static";
g.on("pointermove", (e) => {
if (g.containsPoint(g.toLocal(e.global))) {
/* over the star, not just its bbox */
}
});
```
`Graphics.containsPoint(pointInLocalSpace)` runs a topology-aware test against every filled and stroked shape in the context, including holes. Convert global pointer coordinates with `toLocal()` first. Stroked shapes hit-test against the drawn stroke: the hit band follows the stroke's `width` and `alignment` (`1` inside, `0.5` centered, `0` outside), independent of the polygon's winding order.
### Cloning, clearing, and bounds
```ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);
const shallow = g.clone(); // shares the same GraphicsContext
const deep = g.clone(true); // creates an independent context
console.log(g.bounds.width); // 100 - geometry bounds before transforms
g.clear(); // wipes active path, instructions, and transform; fill/stroke styles persist
```
- `clone()` returns a new `Graphics` that shares the source context (cheap, geometry is reused). Both objects update together if the context changes.
- `clone(true)` clones the context as well so the new `Graphics` can be edited independently.
- `bounds` returns the geometry bounds before the `Container` transform. Useful for layout decisions.
- `clear()` resets the context so the same `Graphics` can be reused. See **Common Mistakes** below for guidance on when to clear versus when to keep stable geometry.
### GraphicsContext utilities
| Member | Behavior |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `ctx.path(graphicsPath)` | Apply a prebuilt `GraphicsPath` onto the active path. Reuse one path across many contexts or frames. |
| `ctx.beginPath()` | Discard the current active path and start a new one without affecting committed instructions. |
| `ctx.setFillStyle(style)` / `ctx.fillStyle` | Set or read the default fill style used by subsequent shapes without calling `fill()`. |
| `ctx.setStrokeStyle(style)` / `ctx.strokeStyle` | Set or read the default stroke style used by subsequent shapes without calling `stroke()`. |
| `ctx.bounds` | Cached geometry bounds across all fill/stroke/texture instructions. |
| `ctx.clear()` | Wipe instructions, the active path, and the drawing transform. |
| `ctx.clone()` | Deep copy including instructions, active path, transform, styles, and stack. |
| `ctx.containsPoint(point)` | Topology-aware hit test against all filled and stroked shapes (including holes). |
| `ctx.batchMode` | One of `'auto'`, `'batch'`, `'no-batch'` — force or disable batching for the shapes in this context. |
| `ctx.customShader` | Assign a `Shader` to override the default graphics shader. |
| `GraphicsContext.defaultFillStyle` | Static fallback used when `fill()` is called without arguments and no fill style is set. |
| `GraphicsContext.defaultStrokeStyle` | Static fallback used when `stroke()` is called without arguments and no stroke style is set. |
`GraphicsContext` is an `EventEmitter` that emits `update`, `destroy`, and `unload` events. Subscribe via `ctx.on('update' | 'destroy' | 'unload', cb)` when tooling or pools need to react to context lifecycle changes.
## Common Mistakes
### [CRITICAL] Using v7 beginFill/drawRect/endFill
Wrong:
```ts
const g = new Graphics().beginFill(0xff0000).drawRect(0, 0, 100, 100).endFill();
```
Correct:
```ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);
```
v8 replaced "set style, draw, end" with "draw shape, then apply style". `beginFill`/`endFill` do not exist.
### [CRITICAL] Using old shape method names
Wrong:
```ts
g.drawCircle(50, 50, 25);
```
Correct:
```ts
g.circle(50, 50, 25);
```
All `draw*` methods were renamed in v8: `drawRect` → `rect`, `drawCircle` → `circle`, `drawEllipse` → `ellipse`, `drawPolygon` → `poly`, `drawRoundedRect` → `roundRect`, `drawStar` → `star`.
### [CRITICAL] Using lineStyle instead of stroke
Wrong:
```ts
g.lineStyle(2, 0xffffff);
g.drawRect(0, 0, 100, 100);
```
Correct:
```ts
g.rect(0, 0, 100, 100).stroke({ width: 2, color: 0xffffff });
```
`lineStyle` was removed. Use `stroke()` after drawing the shape. The stroke options object accepts `width`, `color`, `alpha`, `cap`, `join`, `alignment`, `miterLimit`, and `pixelLine`.
### [HIGH] Using beginHole/endHole for holes
Wrong:
```ts
g.beginFill(0x00ff00)
.drawRect(0, 0, 100, 100)
.beginHole()
.drawCircle(50, 50, 20)
.endHole()
.endFill();
```
Correct:
```ts
g.rect(0, 0, 100, 100).fill(0x00ff00).circle(50, 50, 20).cut();
```
`beginHole`/`endHole` were replaced by `cut()`. Draw the outer shape, fill it, then draw the hole shape and call `cut()`.
### [HIGH] Using GraphicsGeometry instead of GraphicsContext
Wrong:
```ts
const geom = g.geometry;
const clone = new Graphics(geom);
```
Correct:
```ts
const ctx = new GraphicsContext().rect(0, 0, 100, 100).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
```
`GraphicsGeometry` was replaced by `GraphicsContext` in v8. There is no `.geometry` property.
### [HIGH] Destroying a shared GraphicsContext unexpectedly
```ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
g1.destroy({ context: true }); // g2 is left holding a destroyed context
```
Destroying a shared `GraphicsContext` does not destroy the other `Graphics` using it, but they keep a reference to the now-destroyed context and stop updating or rendering correctly. When passing a context via the constructor, `destroy()` with no args preserves the context and detaches the instance from it; use `destroy({ context: false })` to be explicit. Only destroy the context when all sharing instances are done with it. A self-owned context (not passed via constructor) is still destroyed by `destroy()` with no args.
### [HIGH] Clearing and redrawing Graphics every frame
Graphics are designed to be stable, not dynamic. Calling `clear()` and redrawing every frame rebuilds GPU geometry each time. For dynamic visuals:
- Use `Sprite` with pre-rendered textures and transform changes.
- Use `cacheAsTexture(true)` for complex static graphics.
- For real-time shape changes, consider `Mesh` with custom geometry updates.
This is the opposite of HTML Canvas 2D, where redrawing each frame is normal. PixiJS tessellates shapes into GPU triangles, so initial draw is expensive but subsequent renders are fast. Treat `Graphics` more like SVG elements than canvas draw calls.
### [MEDIUM] Do not nest children inside a Graphics
`Graphics` sets `allowChildren = false`. Adding children logs a deprecation warning and will be a hard error in a future version. Wrap multiple graphics alongside other leaves in a plain `Container`:
```ts
const group = new Container();
group.addChild(graphics, sprite);
```
## API Reference
- [Graphics](https://pixijs.download/release/docs/scene.Graphics.html.md)
- [GraphicsOptions](https://pixijs.download/release/docs/scene.GraphicsOptions.html.md)
- [GraphicsContext](https://pixijs.download/release/docs/scene.GraphicsContext.html.md)
- [GraphicsPath](https://pixijs.download/release/docs/scene.GraphicsPath.html.md)
- [graphicsContextToSvg](https://pixijs.download/release/docs/scene.graphicsContextToSvg.html.md)
- [FillGradient](https://pixijs.download/release/docs/scene.FillGradient.html.md)
- [FillPattern](https://pixijs.download/release/docs/scene.FillPattern.html.md)
- [FillStyle](https://pixijs.download/release/docs/scene.FillStyle.html.md)
- [FillInput](https://pixijs.download/release/docs/scene.FillInput.html.md)
+141
View File
@@ -0,0 +1,141 @@
---
name: pixijs-scene-mesh
description: "Use this skill when rendering custom geometry in PixiJS v8. Covers Mesh with MeshGeometry (positions, uvs, indices, topology), MeshSimple for per-frame vertex animation, MeshPlane for subdivided deformation, MeshRope for path-following textures, PerspectiveMesh for 2.5D corners. Triggers on: Mesh, MeshGeometry, MeshSimple, MeshPlane, MeshRope, PerspectiveMesh, positions, uvs, indices, topology, setCorners, constructor options, MeshOptions, MeshPlaneOptions, MeshRopeOptions, SimpleMeshOptions, PerspectivePlaneOptions."
license: MIT
---
Meshes render arbitrary 2D (or perspective-projected) geometry with a texture or custom shader. PixiJS ships the base `Mesh` class plus four specialized subclasses for common shapes: `MeshSimple`, `MeshPlane`, `MeshRope`, and `PerspectiveMesh`. Pick the subclass that matches your shape; drop to the base `Mesh` when you need full vertex-level control or a custom shader.
Assumes familiarity with `pixijs-scene-core-concepts`. Meshes are leaf nodes; they cannot have children. Wrap multiple meshes in a `Container` to group them.
## Quick Start
```ts
const texture = await Assets.load("pattern.png");
const geometry = new MeshGeometry({
positions: new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
topology: "triangle-list",
});
const mesh = new Mesh({
geometry,
texture,
roundPixels: false,
});
app.stage.addChild(mesh);
```
Every `Mesh` subclass takes a single options object. The base `Mesh` requires a `geometry`; subclasses (`MeshSimple`, `MeshPlane`, `MeshRope`, `PerspectiveMesh`) build the geometry internally and require a `texture` instead. See each variant's reference for the full field list.
## Variants
| Variant | Use when | Trade-offs | Reference |
| ----------------- | ----------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------- |
| `Mesh` | Full control, custom geometry, custom shaders | You build the `MeshGeometry` yourself | [references/mesh.md](references/mesh.md) |
| `MeshSimple` | Quick textured shapes with per-frame vertex animation | Thin wrapper; auto-updates the vertex buffer | [references/mesh-simple.md](references/mesh-simple.md) |
| `MeshPlane` | Subdivided textured rectangle for distortion effects | Fixed topology; `verticesX`/`verticesY` control density | [references/mesh-plane.md](references/mesh-plane.md) |
| `MeshRope` | Texture following a polyline path | Bent at each point; needs many points for smooth curves | [references/mesh-rope.md](references/mesh-rope.md) |
| `PerspectiveMesh` | 2D plane with perspective corners | Not true 3D; UV-level perspective correction only | [references/mesh-perspective.md](references/mesh-perspective.md) |
## When to use what
- **"I need a textured quad"** → `Sprite` (see `pixijs-scene-sprite`), not a mesh. Meshes are for cases Sprite can't express.
- **"I need to deform a textured rectangle"** → `MeshPlane`. Set `verticesX`/`verticesY` for the desired smoothness.
- **"I need a rope or trail that follows points"** → `MeshRope`. Control thickness with `width`; use `textureScale: 0` to stretch or `> 0` to repeat.
- **"I need a tilted 2D card or floor"** → `PerspectiveMesh`. Pass four corner positions; not real 3D but good enough for 2.5D effects.
- **"I need per-frame animated vertices with a simple shape"** → `MeshSimple`. It handles the buffer-update dance for you.
- **"I need a custom shader or unusual geometry"** → Base `Mesh` with a hand-built `MeshGeometry`. See `pixijs-custom-rendering` for shader authoring.
- **"I need true 3D rendering"** → Use a dedicated 3D library. `PerspectiveMesh` simulates perspective at the UV level but has no depth buffer.
## Quick concepts
### MeshGeometry owns the vertex data
`MeshGeometry` holds the `positions`, `uvs`, `indices`, and `topology`. You can share one geometry across multiple `Mesh` instances; positions are reference-counted.
### Batching
A mesh batches (combines with other draw calls) only if it uses `MeshGeometry`, has no custom shader, no depth or culling state, and the `'auto'` rule (`batchMode = 'auto'` and ≤100 vertices). Custom shaders always render independently.
### Topology is on the geometry, not the mesh
`new MeshGeometry({ topology: 'triangle-strip' })`; topology is a geometry property. The default is `'triangle-list'`; set it explicitly if your data is organized differently.
### Extra knobs
- `new MeshGeometry({ shrinkBuffersToFit: true })` — trims GPU buffer storage to the actual vertex count on creation. Use it when feeding large, one-shot geometries.
- `Mesh.containsPoint(point)` — topology-aware hit test that walks the triangles. Works with any `MeshGeometry`, including custom layouts.
- `new Mesh({ geometry, state })` — pass a `State` object to control blend, depth, and culling. Batching is disabled automatically if depth or culling flags are set. Defaults to `State.for2d()` when omitted.
## Common Mistakes
### [HIGH] Using old `SimpleMesh` / `SimplePlane` / `SimpleRope` names
Wrong:
```ts
import { SimpleRope } from "pixi.js";
const rope = new SimpleRope(texture, points);
```
Correct:
```ts
import { MeshRope } from "pixi.js";
const rope = new MeshRope({ texture, points });
```
Renamed in v8: `SimpleMesh` → `MeshSimple`, `SimplePlane` → `MeshPlane`, `SimpleRope` → `MeshRope`. All switched to options-object constructors.
### [HIGH] Positional constructor args for `MeshGeometry`
Wrong:
```ts
const geom = new MeshGeometry(vertices, uvs, indices);
```
Correct:
```ts
const geom = new MeshGeometry({
positions: vertices,
uvs,
indices,
topology: "triangle-list",
});
```
v8 uses an options object. Note the property is `positions`, not `vertices`; the `vertices` name is only used by `MeshSimple`.
### [MEDIUM] Adding children to a mesh
Wrong:
```ts
mesh.addChild(otherMesh);
```
Correct:
```ts
const group = new Container();
group.addChild(mesh, otherMesh);
```
`Mesh` sets `allowChildren = false`. Adding children logs a deprecation warning. Group meshes inside a plain `Container`.
## API Reference
- [Mesh](https://pixijs.download/release/docs/scene.Mesh.html.md)
- [MeshGeometry](https://pixijs.download/release/docs/scene.MeshGeometry.html.md)
- [MeshSimple](https://pixijs.download/release/docs/scene.MeshSimple.html.md)
- [MeshPlane](https://pixijs.download/release/docs/scene.MeshPlane.html.md)
- [MeshRope](https://pixijs.download/release/docs/scene.MeshRope.html.md)
- [PerspectiveMesh](https://pixijs.download/release/docs/scene.PerspectiveMesh.html.md)
@@ -0,0 +1,189 @@
# PerspectiveMesh
A mesh that renders a textured plane with perspective projection via four corner points. The UV interpolation is computed per vertex in a subdivided grid, so the more vertices you allocate, the smoother the projection. Use `PerspectiveMesh` for 2D billboards, floor planes, angled cards, fake 3D layouts, or anywhere you want a texture to appear tilted into the scene.
## Quick Start
```ts
const texture = await Assets.load("card.png");
const mesh = new PerspectiveMesh({
texture,
verticesX: 20,
verticesY: 20,
x0: 0,
y0: 0, // top-left
x1: 300,
y1: 30, // top-right (raised)
x2: 280,
y2: 300, // bottom-right
x3: 20,
y3: 280, // bottom-left
});
app.stage.addChild(mesh);
```
The four corner coordinates define a quadrilateral in local space; the mesh warps the texture to fit it with perspective-correct UVs.
## Constructor options
`new PerspectiveMesh(options: PerspectivePlaneOptions)`
> Note: the interface is `PerspectivePlaneOptions`, not `PerspectiveMeshOptions`. It extends `MeshPlaneOptions`.
| Option | Type | Default | Description |
| ----------- | --------- | --------------- | --------------------------------------------------------------------------------------------------------------------- |
| `texture` | `Texture` | `Texture.WHITE` | Texture warped onto the quad. Inherited from `MeshPlaneOptions`; also drives the geometry's initial `width`/`height`. |
| `verticesX` | `number` | `10` | Grid columns. More vertices yield smoother perspective at higher draw cost. |
| `verticesY` | `number` | `10` | Grid rows. More vertices yield smoother perspective at higher draw cost. |
| `x0` | `number` | `0` | Top-left corner x. |
| `y0` | `number` | `0` | Top-left corner y. |
| `x1` | `number` | `100` | Top-right corner x. |
| `y1` | `number` | `0` | Top-right corner y. |
| `x2` | `number` | `100` | Bottom-right corner x. |
| `y2` | `number` | `100` | Bottom-right corner y. |
| `x3` | `number` | `0` | Bottom-left corner x. |
| `y3` | `number` | `100` | Bottom-left corner y. |
Corners must be listed clockwise from the top-left. Defaults form a 100x100 square with `Texture.WHITE`; `PerspectiveMesh.defaultOptions` overrides them globally. The constructor omits `geometry` (it builds its own `PerspectivePlaneGeometry`). Other `MeshOptions` fields (`shader`, `state`, `roundPixels`) are inherited from `mesh.md`.
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
Call `mesh.setCorners(x0, y0, x1, y1, x2, y2, x3, y3)` at runtime to animate the warp.
## Core Patterns
### Corner order
```ts
mesh.setCorners(
0,
0, // top-left (x0, y0)
200,
0, // top-right (x1, y1)
200,
200, // bottom-right(x2, y2)
0,
200, // bottom-left (x3, y3)
);
```
Corners must be specified clockwise starting from the top-left. `setCorners` updates the geometry in place; use it for animation.
### Animated perspective
```ts
const mesh = new PerspectiveMesh({
texture,
verticesX: 20,
verticesY: 20,
});
app.ticker.add(() => {
const t = performance.now() / 1000;
const wave = Math.sin(t) * 30;
mesh.setCorners(0, wave, 200, -wave, 200, 200, 0, 200);
});
```
Call `setCorners` each frame to animate the warp. The geometry recalculates perspective-correct UVs automatically.
### Vertex density vs quality
```ts
const coarse = new PerspectiveMesh({ texture, verticesX: 5, verticesY: 5 });
const smooth = new PerspectiveMesh({ texture, verticesX: 30, verticesY: 30 });
```
The number of vertices controls how smooth the perspective projection looks. A 5×5 grid shows obvious triangular stretching; 20×20 is a good default; 30×30+ is smooth but adds draw overhead. Each axis defaults to `10`.
### Fake floor
```ts
const floor = new PerspectiveMesh({
texture: floorTex,
verticesX: 20,
verticesY: 20,
x0: 200,
y0: 300, // near left on screen
x1: 600,
y1: 300, // near right
x2: 800,
y2: 200, // far right
x3: 0,
y3: 200, // far left
});
app.stage.addChild(floor);
```
Put the "far" corners higher on the screen and closer together than the "near" corners to create a floor-extending-into-the-distance effect. Use with a scrolling TilingSprite above for a stylized 2D driving game.
### Updating the texture
```ts
mesh.texture = await Assets.load("new-card.png");
```
Changing the texture rebuilds the geometry to match the new dimensions while keeping the current corner positions. The perspective projection persists through texture swaps.
## Common Mistakes
### [HIGH] Expecting true 3D
`PerspectiveMesh` is a 2D mesh with UV correction to simulate perspective. There is no Z axis, no depth buffer, and no camera. For real 3D, use a full WebGL/WebGPU library on top of PixiJS, or drive vertex positions through a manual transform.
### [MEDIUM] Too few vertices for a noticeable tilt
Wrong:
```ts
const mesh = new PerspectiveMesh({
texture,
verticesX: 2,
verticesY: 2,
x0: 0,
y0: 0,
x1: 300,
y1: 50,
x2: 280,
y2: 250,
x3: 20,
y3: 200,
});
```
Correct:
```ts
const mesh = new PerspectiveMesh({
texture,
verticesX: 20,
verticesY: 20,
x0: 0,
y0: 0,
x1: 300,
y1: 50,
x2: 280,
y2: 250,
x3: 20,
y3: 200,
});
```
A 2×2 grid has only two triangles; the texture stretches linearly with no perspective correction. Bump density above 10×10 for any visible tilt.
### [MEDIUM] Non-convex corners
If your four corners form a non-convex (self-intersecting or bow-tie) quadrilateral, the UV interpolation produces visual artifacts. Keep the corners in consistent clockwise order and check that the quad is convex.
## API Reference
- [PerspectiveMesh](https://pixijs.download/release/docs/scene.PerspectiveMesh.html.md)
- [PerspectivePlaneOptions](https://pixijs.download/release/docs/scene.PerspectivePlaneOptions.html.md)
- [MeshPlane](https://pixijs.download/release/docs/scene.MeshPlane.html.md)
@@ -0,0 +1,159 @@
# MeshPlane
A mesh that maps a texture onto a subdivided plane with configurable vertex density. Use `MeshPlane` for distortion effects, wave simulations, cloth, heat haze, or any effect that needs per-vertex deformation of a flat textured rectangle.
## Quick Start
```ts
const texture = await Assets.load("background.png");
const plane = new MeshPlane({
texture,
verticesX: 10,
verticesY: 10,
});
app.stage.addChild(plane);
```
`verticesX` / `verticesY` control the grid density (each defaults to `10`). More vertices give smoother deformation at higher draw overhead. The plane sizes itself to the texture by default.
## Constructor options
`new MeshPlane(options: MeshPlaneOptions)`
| Option | Type | Default | Description |
| ----------- | --------- | ------- | ---------------------------------------------------------------------------------- |
| `texture` | `Texture` | — | Texture mapped onto the plane. Required; also drives the initial `width`/`height`. |
| `verticesX` | `number` | `10` | Grid columns. Higher values yield smoother deformation at higher draw cost. |
| `verticesY` | `number` | `10` | Grid rows. Higher values yield smoother deformation at higher draw cost. |
`MeshPlane` builds its own `PlaneGeometry`, so you cannot pass `geometry` — it is omitted from the options type. Other `MeshOptions` fields (`shader`, `state`, `roundPixels`) are inherited from `mesh.md` and behave identically.
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
`autoResize` is a runtime property set to `true` by the constructor, not a constructor option. Toggle it after construction to control whether texture changes rebuild the plane geometry.
## Core Patterns
### Deforming the vertex grid
```ts
const { buffer } = plane.geometry.getAttribute("aPosition");
app.ticker.add(() => {
for (let i = 0; i < buffer.data.length; i++) {
buffer.data[i] += Math.sin(performance.now() / 1000 + i) * 0.3;
}
buffer.update();
});
```
Grab the position buffer via `getAttribute('aPosition')`, mutate the `data` array, then call `buffer.update()` to push changes to the GPU. The texture UVs are fixed once the plane is built, so as long as you only move vertices (not change the grid topology), the texture stretches to follow.
### Auto-resize on texture change
```ts
plane.texture = await Assets.load("new-background.png");
```
`autoResize` defaults to `true`. When the plane's texture changes (or emits an `'update'` event), the geometry rebuilds to match the new texture dimensions. Set `autoResize = false` to keep the original size regardless of the new texture.
### Fixed-size plane
```ts
const fixedPlane = new MeshPlane({
texture,
verticesX: 20,
verticesY: 20,
});
fixedPlane.autoResize = false;
const geometry = fixedPlane.geometry;
geometry.width = 500;
geometry.height = 300;
geometry.build({});
```
For a plane whose size is decoupled from the texture, disable `autoResize` and set the geometry's `width` / `height` explicitly. Call `build({})` to regenerate vertex positions at the new size.
### Higher vertex density for smooth distortion
```ts
const smooth = new MeshPlane({
texture,
verticesX: 40,
verticesY: 40,
});
```
Vertex density directly controls how smoothly the plane can deform. A 10×10 grid is fine for coarse ripples; for waves, cloth, or fine distortion, bump density to 20×20 or higher. Density above ~50×50 starts to affect draw overhead on lower-end devices.
### Wave animation
```ts
const plane = new MeshPlane({ texture, verticesX: 30, verticesY: 30 });
const { buffer } = plane.geometry.getAttribute("aPosition");
const original = new Float32Array(buffer.data);
app.ticker.add((ticker) => {
const t = performance.now() / 500;
for (let i = 0; i < buffer.data.length; i += 2) {
buffer.data[i] = original[i];
buffer.data[i + 1] = original[i + 1] + Math.sin(t + original[i] * 0.1) * 5;
}
buffer.update();
});
```
Cache the original positions once, then offset from them each frame. Resetting to the base positions each frame avoids cumulative drift.
## Common Mistakes
### [HIGH] Using the old `SimplePlane` name
Wrong:
```ts
import { SimplePlane } from "pixi.js";
const plane = new SimplePlane(texture, 10, 10);
```
Correct:
```ts
import { MeshPlane } from "pixi.js";
const plane = new MeshPlane({ texture, verticesX: 10, verticesY: 10 });
```
`SimplePlane` was renamed to `MeshPlane` in v8 and switched to an options-object constructor.
### [MEDIUM] Mutating positions without calling `buffer.update()`
Wrong:
```ts
buffer.data[1] = 50;
```
Correct:
```ts
buffer.data[1] = 50;
buffer.update();
```
The buffer does not observe its own `data` array. Without `update()`, the changes stay on the CPU and the next render draws stale vertex data.
### [MEDIUM] High vertex density on pixel-art textures
A dense grid on a small pixel-art texture can cause visible UV interpolation artifacts. Use fewer vertices (10×10 or less) for pixel art, or set `roundPixels: true` on the mesh.
## API Reference
- [MeshPlane](https://pixijs.download/release/docs/scene.MeshPlane.html.md)
- [MeshPlaneOptions](https://pixijs.download/release/docs/scene.MeshPlaneOptions.html.md)
- [PlaneGeometry](https://pixijs.download/release/docs/scene.PlaneGeometry.html.md)
@@ -0,0 +1,176 @@
# MeshRope
A mesh that renders a texture along a path defined by points. Each segment bends the texture to follow the curve. Use `MeshRope` for ropes, chains, snakes, trails, whip effects, tentacles, and any effect where you want a textured ribbon that follows a moving polyline.
## Quick Start
```ts
const texture = await Assets.load("rope.png");
const points = [];
for (let i = 0; i < 20; i++) {
points.push(new Point(i * 50, 0));
}
const rope = new MeshRope({
texture,
points,
textureScale: 0,
width: texture.height,
});
app.stage.addChild(rope);
app.ticker.add(() => {
const t = performance.now() / 500;
for (let i = 0; i < points.length; i++) {
points[i].y = Math.sin(i * 0.5 + t) * 30;
}
});
```
The rope uses the y-axis of the texture as its thickness and stretches the x-axis along the path. Move points each frame; with `autoUpdate` enabled (default), the geometry updates automatically.
## Constructor options
`new MeshRope(options: MeshRopeOptions)`
| Option | Type | Default | Description |
| -------------- | ------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `texture` | `Texture` | — | Texture sampled along the rope. Required. |
| `points` | `PointData[]` | — | Ordered path the rope follows. Required. Each entry bends the texture; more points yield smoother curves. |
| `textureScale` | `number` | `0` | `0` stretches the texture across the full length. Positive values repeat the texture while preserving aspect ratio and switch the source's `addressMode` to `'repeat'`. Values `< 1` with a larger source reduce alpha artifacts. |
| `width` | `number` | `texture.height` | Rope thickness. Defaults to the texture height when omitted. |
`MeshRope` builds its own `RopeGeometry`, so `geometry` is omitted from the options type. Other `MeshOptions` fields (`shader`, `state`, `roundPixels`) are inherited from `mesh.md` and behave identically.
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
`autoUpdate` is a runtime property (defaults to `true`), not a constructor option. Set `rope.autoUpdate = false` after construction to control when the geometry recomputes from the points. `MeshRope.defaultOptions` overrides the `textureScale` default globally.
## Core Patterns
### `textureScale`: stretch vs repeat
```ts
// stretch (default); entire texture maps across the rope
const stretched = new MeshRope({ texture, points, textureScale: 0 });
// repeat; texture tiles along the rope, preserving aspect ratio
const repeated = new MeshRope({ texture, points, textureScale: 1 });
// higher resolution; downsample an HD texture for better quality
const sharp = new MeshRope({ texture: hdRope, points, textureScale: 0.5 });
```
- `textureScale: 0` (default): stretches the texture across the full rope length.
- `textureScale > 0`: repeats the texture while preserving its aspect ratio. The underlying texture source has its `addressMode` set to `'repeat'`. Power-of-two textures are recommended for WebGL compatibility.
- `textureScale < 1` with a larger source texture reduces alpha-channel artifacts.
### Rope width
```ts
const thick = new MeshRope({
texture,
points,
width: 60,
});
```
`width` (thickness) defaults to `texture.height`. Override it for a rope narrower or wider than the source art.
### Manual update mode
```ts
const rope = new MeshRope({ texture, points });
rope.autoUpdate = false;
app.ticker.add(() => {
for (let i = 0; i < points.length; i++) {
points[i].y = Math.sin(i + performance.now() / 1000) * 30;
}
(rope.geometry as RopeGeometry).update();
});
```
Set `autoUpdate = false` to control when the geometry recomputes from the points. Useful when your point array only changes occasionally, or when you want to update once per multiple frames for performance.
### Trail effect
```ts
const trailPoints: Point[] = [];
for (let i = 0; i < 30; i++) {
trailPoints.push(new Point(0, 0));
}
const trail = new MeshRope({
texture: trailTex,
points: trailPoints,
textureScale: 0,
});
app.stage.addChild(trail);
app.ticker.add(() => {
for (let i = trailPoints.length - 1; i > 0; i--) {
trailPoints[i].x = trailPoints[i - 1].x;
trailPoints[i].y = trailPoints[i - 1].y;
}
trailPoints[0].x = mouseX;
trailPoints[0].y = mouseY;
});
```
A simple tail effect: shift all points one slot down each frame, then write the new head. Stretch texture mode (`textureScale: 0`) makes the full texture visible along the trail regardless of length.
## Common Mistakes
### [HIGH] Using the old `SimpleRope` or `Rope` name
Wrong:
```ts
import { SimpleRope } from "pixi.js";
const rope = new SimpleRope(texture, points);
```
Correct:
```ts
import { MeshRope } from "pixi.js";
const rope = new MeshRope({ texture, points });
```
`SimpleRope` was renamed to `MeshRope` in v8 and switched to an options-object constructor.
### [HIGH] Too few points for a smooth curve
Wrong:
```ts
const rope = new MeshRope({
texture,
points: [new Point(0, 0), new Point(400, 0)],
});
```
Correct:
```ts
const points = [];
for (let i = 0; i < 20; i++) points.push(new Point(i * 20, 0));
const rope = new MeshRope({ texture, points });
```
The rope only bends at point boundaries. Two points produce a straight segment; a curved rope needs many closely-spaced points (typically 15–30 for a visible bend).
### [MEDIUM] Non-power-of-two texture with `textureScale > 0`
When `textureScale` is positive, the rope sets the texture source's `addressMode` to `'repeat'`. Some WebGL drivers clamp non-power-of-two textures instead of wrapping, causing the tile pattern to stretch. Resize the source to power-of-two dimensions (128, 256, 512, etc.) for reliable wrapping.
## API Reference
- [MeshRope](https://pixijs.download/release/docs/scene.MeshRope.html.md)
- [MeshRopeOptions](https://pixijs.download/release/docs/scene.MeshRopeOptions.html.md)
- [RopeGeometry](https://pixijs.download/release/docs/scene.RopeGeometry.html.md)
@@ -0,0 +1,144 @@
# MeshSimple
A thin `Mesh` subclass that handles geometry construction for you. Pass `vertices`, optional `uvs`, and optional `indices`, and it builds the `MeshGeometry` internally and auto-updates the vertex buffer each frame. Use `MeshSimple` for quick textured quads, triangles, or any shape where you plan to animate vertex positions.
## Quick Start
```ts
const texture = await Assets.load("sprite.png");
const triangle = new MeshSimple({
texture,
vertices: new Float32Array([0, 0, 100, 0, 50, 100]),
uvs: new Float32Array([0, 0, 1, 0, 0.5, 1]),
topology: "triangle-list",
});
app.stage.addChild(triangle);
```
`MeshSimple` wraps `MeshGeometry` creation, exposes `vertices` directly, and auto-updates the position buffer each frame via `onRender`.
## Constructor options
`new MeshSimple(options: SimpleMeshOptions)`
| Option | Type | Default | Description |
| ---------- | -------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------- |
| `texture` | `Texture` | — | Texture sampled by the mesh. Required. |
| `vertices` | `Float32Array` | `undefined` | Flat `x, y` pairs for each vertex. Passed through to `MeshGeometry` as `positions`. |
| `uvs` | `Float32Array` | `undefined` | Flat `u, v` pairs matching `vertices`. Without UVs the geometry fills zeros and the mesh samples only pixel `(0, 0)`. |
| `indices` | `Uint32Array` | `undefined` | Triangle indices into `vertices`. Omit for unindexed rendering in vertex order. |
| `topology` | `Topology` | `'triangle-list'` | `'triangle-list' \| 'triangle-strip' \| 'line-list' \| 'line-strip' \| 'point-list'`. |
`MeshSimple` builds its own `MeshGeometry`, so `geometry` is omitted from the options type. Note the option is named `vertices` here (converted to `positions` internally), matching the `mesh.vertices` getter. Other `MeshOptions` fields (`shader`, `state`, `roundPixels`) are inherited from `mesh.md` and behave identically.
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
`autoUpdate` is a runtime property (defaults to `true`), not a constructor option. Set `mesh.autoUpdate = false` after construction to suppress the per-frame position-buffer upload.
## Core Patterns
### Animated vertices
```ts
app.ticker.add(() => {
const verts = triangle.vertices;
verts[5] = 100 + Math.sin(performance.now() / 500) * 20;
triangle.vertices = verts;
});
```
Because `autoUpdate` defaults to `true`, assigning to `vertices` or mutating the array in place is enough; the buffer is pushed to the GPU automatically during the next render pass.
### Indexed quad
```ts
const quad = new MeshSimple({
texture,
vertices: new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
});
```
Indices are optional; omit them and the mesh uses unindexed vertex order. Useful for a small, simple shape where explicit indexing adds no value.
### Manual update mode
```ts
triangle.autoUpdate = false;
app.ticker.add(() => {
const verts = triangle.vertices;
verts[1] = Math.sin(performance.now() / 1000) * 20;
triangle.vertices = verts;
triangle.geometry.getBuffer("aPosition").update();
});
```
Set `autoUpdate = false` when you want explicit control over when the GPU sees new vertex data; for example, when you only update once per several frames, or when you want to batch multiple vertex mutations before a single upload.
### Alternative topologies
```ts
const lineStrip = new MeshSimple({
texture,
vertices: new Float32Array([0, 0, 50, 50, 100, 0, 150, 50]),
topology: "line-strip",
});
```
`MeshSimple` accepts any topology supported by `MeshGeometry` (`'triangle-list'`, `'triangle-strip'`, `'line-list'`, `'line-strip'`, `'point-list'`). The default is `'triangle-list'`.
## Common Mistakes
### [HIGH] Using the old `SimpleMesh` name
Wrong:
```ts
import { SimpleMesh } from "pixi.js";
const mesh = new SimpleMesh(texture, vertices, uvs, indices);
```
Correct:
```ts
import { MeshSimple } from "pixi.js";
const mesh = new MeshSimple({ texture, vertices, uvs, indices });
```
`SimpleMesh` was renamed to `MeshSimple` in v8. The old name is not exported; the class also switched to an options-object constructor.
### [MEDIUM] Forgetting UVs on a textured mesh
Wrong:
```ts
const mesh = new MeshSimple({
texture,
vertices: new Float32Array([0, 0, 100, 0, 50, 100]),
});
```
Correct:
```ts
const mesh = new MeshSimple({
texture,
vertices: new Float32Array([0, 0, 100, 0, 50, 100]),
uvs: new Float32Array([0, 0, 1, 0, 0.5, 1]),
});
```
Omitting `uvs` makes the underlying `MeshGeometry` fill a zero array, sampling only pixel `(0, 0)` of the texture. Always provide UVs when you want the texture to map across the geometry.
## API Reference
- [MeshSimple](https://pixijs.download/release/docs/scene.MeshSimple.html.md)
- [SimpleMeshOptions](https://pixijs.download/release/docs/scene.SimpleMeshOptions.html.md)
- [Mesh](https://pixijs.download/release/docs/scene.Mesh.html.md)
- [MeshGeometry](https://pixijs.download/release/docs/scene.MeshGeometry.html.md)
@@ -0,0 +1,213 @@
# Mesh
The base mesh class. Combines a `Geometry` (vertex positions, UVs, indices, topology) with a `Texture` or custom `Shader` to render arbitrary 2D (or perspective-projected) graphics. Use `Mesh` when you need vertex-level control, custom shaders, or batched draw calls for geometry that doesn't fit the Sprite / Graphics / Particle model.
## Quick Start
```ts
const texture = await Assets.load("pattern.png");
const geometry = new MeshGeometry({
positions: new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
topology: "triangle-list",
});
const mesh = new Mesh({
geometry,
texture,
roundPixels: false,
});
app.stage.addChild(mesh);
```
`Mesh` is a leaf; `allowChildren` is `false`. It owns a reference to its geometry (shareable across meshes) and either a texture or a custom shader.
## Constructor options
`new Mesh<GEOMETRY, SHADER>(options: MeshOptions<GEOMETRY, SHADER>)`
| Option | Type | Default | Description |
| ------------- | ------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------- |
| `geometry` | `GEOMETRY extends Geometry` | — | Vertex buffers, indices, UVs, and topology. Required. Shareable across meshes. |
| `shader` | `SHADER extends Shader \| null` | `null` | Custom vertex/fragment shader. When set, the mesh skips batching and the shader decides what to sample. |
| `state` | `State` | `State.for2d()` | GPU state (blend, depth, culling). Depth or culling flags disable batching. |
| `texture` | `Texture` | `Texture.WHITE` | Texture sampled by the default shader. Ignored if a custom `shader` provides its own texture. |
| `roundPixels` | `boolean` | `false` | Snap `x`/`y` to integer pixels at render time. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
The constructor assigns `texture` from `shader.texture` when a custom shader is passed without an explicit `texture` option. Passing `null`/`undefined` to the `texture` setter at runtime coerces it to `Texture.EMPTY`.
## Core Patterns
### MeshGeometry anatomy
```ts
const geometry = new MeshGeometry({
positions: new Float32Array([
0,
0, // vertex 0: x, y
100,
0, // vertex 1
100,
100, // vertex 2
0,
100, // vertex 3
]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
topology: "triangle-list",
});
```
- `positions`: flat x,y pairs in local space.
- `uvs`: flat u,v pairs in `[0, 1]` texture space. If omitted, defaults to zero-filled.
- `indices`: triangle indices. If omitted, defaults to a quad `[0, 1, 2, 0, 2, 3]`.
- `topology`: how indices are interpreted (see below).
After construction, read or replace the typed arrays via the getters `geometry.positions`, `geometry.uvs`, `geometry.indices`. They return the underlying buffers' `data` directly; mutating in place is equivalent to mutating `getBuffer('aPosition').data`.
### Topology
```ts
new MeshGeometry({ positions, uvs, indices, topology: "triangle-list" });
```
Five topology types:
| Topology | Meaning |
| --------------------------- | ------------------------------------------------ |
| `'triangle-list'` (default) | Every 3 indices form one triangle |
| `'triangle-strip'` | Each new index extends the strip by one triangle |
| `'line-list'` | Pairs of indices form independent lines |
| `'line-strip'` | Connected line segments |
| `'point-list'` | Each index renders a point |
Topology is set on the **geometry**, not the mesh. The default is `'triangle-list'`; any other data layout needs an explicit topology or the mesh renders garbage.
### Batching
```ts
geometry.batchMode = "auto"; // default
geometry.batchMode = "batch"; // always batched
geometry.batchMode = "no-batch"; // never batched
```
A mesh is batched (combined with other draw calls) only when:
- It uses `MeshGeometry` (not a custom geometry subclass).
- It has no custom `shader`.
- Its `state` has no depth test or culling.
- The `'auto'` rule: geometry has 100 or fewer vertices.
Custom shaders always render independently. For large static meshes, set `batchMode = 'no-batch'` to skip the batch-eligibility check overhead.
### Custom shader
```ts
import { Shader } from "pixi.js";
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
resources: { uTexture: texture.source, uSampler: texture.source.style },
});
const mesh = new Mesh({ geometry, shader });
```
When a shader is provided, `texture` is optional; the shader decides what to sample. Custom shaders bypass batching entirely. See the `pixijs-custom-rendering` skill for full shader authoring detail.
### Shared geometry
```ts
const sharedGeom = new MeshGeometry({ positions, uvs, indices });
const mesh1 = new Mesh({ geometry: sharedGeom, texture: tex1 });
const mesh2 = new Mesh({ geometry: sharedGeom, texture: tex2 });
```
Geometry is reference-counted. Multiple meshes can share one geometry, saving memory for instances that share a shape but differ in transform or texture.
### Updating vertices at runtime
```ts
mesh.geometry.positions[1] = Math.sin(performance.now() / 500) * 20;
mesh.geometry.getBuffer("aPosition").update();
```
`MeshGeometry` exposes `positions`, `uvs`, and `indices` getters that return the underlying `Float32Array` / `Uint32Array` directly; they point at the same data as `getBuffer('aPosition').data` / `getBuffer('aUV').data` / `getIndex().data`. Mutate in place for the common case, or assign a whole new array via the setter (the setters do `buffer.data = value` with no length check; the real invariant is `uvs.length >= positions.length` so every vertex has a UV).
Call `update()` on the buffer after mutating its `data` array to push changes to the GPU. For auto-update behavior, use `MeshSimple` which handles this for you.
## Common Mistakes
### [HIGH] Positional constructor args
Wrong:
```ts
const mesh = new Mesh(geometry, shader);
```
Correct:
```ts
const mesh = new Mesh({ geometry, shader });
```
v8 uses an options object. The positional form is deprecated and logs a warning. Note also that the `drawMode` argument was removed; use `geometry.topology` instead.
### [HIGH] `vertices` instead of `positions`
Wrong:
```ts
const geometry = new MeshGeometry({
vertices: new Float32Array([0, 0, 100, 0, 50, 100]),
});
```
Correct:
```ts
const geometry = new MeshGeometry({
positions: new Float32Array([0, 0, 100, 0, 50, 100]),
});
```
The `MeshGeometry` option is `positions`. `vertices` is the convenience name used only by `MeshSimple`, where it's converted internally.
### [MEDIUM] Forgetting to set topology
Wrong:
```ts
const geometry = new MeshGeometry({
positions: stripPositions,
indices: stripIndices,
});
```
Correct:
```ts
const geometry = new MeshGeometry({
positions: stripPositions,
indices: stripIndices,
topology: "triangle-strip",
});
```
The default topology is `'triangle-list'`. If your data is organized as a strip or line list, the mesh renders garbage without an explicit topology.
## API Reference
- [Mesh](https://pixijs.download/release/docs/scene.Mesh.html.md)
- [MeshOptions](https://pixijs.download/release/docs/scene.MeshOptions.html.md)
- [MeshGeometry](https://pixijs.download/release/docs/scene.MeshGeometry.html.md)
- [MeshGeometryOptions](https://pixijs.download/release/docs/scene.MeshGeometryOptions.html.md)
@@ -0,0 +1,323 @@
---
name: pixijs-scene-particle-container
description: "Use this skill when rendering thousands of lightweight sprites in PixiJS v8. Covers ParticleContainer with Particle instances, addParticle/removeParticle, particleChildren array, dynamicProperties (vertex, position, rotation, uvs, color), boundsArea, roundPixels, update, inherited alpha/tint/blendMode from ancestors. Triggers on: ParticleContainer, Particle, IParticle, addParticle, particleChildren, dynamicProperties, boundsArea, particle effects, particle alpha, particle tint, fade particles, constructor options, ParticleContainerOptions, ParticleOptions."
license: MIT
---
`ParticleContainer` is a specialized container for rendering hundreds to tens of thousands of lightweight sprites in a single draw call. Use it for particle effects, bullet patterns, or any case where you need a large number of similar-looking objects with minimal per-object overhead. Particles share a single base texture and have a restricted transform set; they are not full `Container` children.
Assumes familiarity with `pixijs-scene-core-concepts`. `ParticleContainer` is a special leaf in a different sense: it contains `Particle` instances in its own `particleChildren` array and rejects normal PixiJS children. Use `addParticle`, not `addChild`, and wrap the whole `ParticleContainer` in a `Container` if you need to group it with other scene objects.
The Particle API is new in v8 but is stable for production use.
## Quick Start
```ts
const texture = await Assets.load("particle.png");
const container = new ParticleContainer({
texture,
boundsArea: new Rectangle(0, 0, app.screen.width, app.screen.height),
dynamicProperties: {
position: true,
rotation: false,
color: false,
},
});
for (let i = 0; i < 10000; i++) {
container.addParticle(
new Particle({
texture,
x: Math.random() * app.screen.width,
y: Math.random() * app.screen.height,
}),
);
}
app.stage.addChild(container);
```
**Related skills:** `pixijs-scene-core-concepts` (scene graph basics), `pixijs-scene-sprite` (when you need full features per object), `pixijs-assets` (shared textures, atlases), `pixijs-performance` (batching, texture optimization), `pixijs-scene-container` (wrap with other display objects).
## Constructor options
### ParticleContainerOptions
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`. Note that `children` is omitted: use `particles` instead.
| Option | Type | Default | Description |
| ------------------- | -------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `texture` | `Texture` | `null` | Shared base texture for all particles. If omitted, the container falls back to the texture of the first particle added; every particle must share the same base texture source. |
| `particles` | `T[]` | `[]` | Initial array of `Particle` (or `IParticle`) instances. Equivalent to calling `addParticle` for each, but skips per-call view updates. |
| `dynamicProperties` | `ParticleProperties` | `{ vertex: false, position: true, rotation: false, uvs: false, color: false }` | Flags for which particle attributes re-upload to the GPU every frame. Only `position` is dynamic by default; mark what you animate, leave the rest static for speed. |
| `roundPixels` | `boolean` | `false` | Rounds particle positions to the nearest pixel. Produces crisper rendering for pixel-art styles at the cost of smooth sub-pixel motion. |
| `shader` | `Shader` | default particle shader | Replaces the default particle shader. The custom shader must declare `aPosition`, `aUV`, `aColor`, plus any dynamic-only attributes enabled via `dynamicProperties`. |
`boundsArea` is inherited from `Container` but is effectively required on `ParticleContainer`: the container returns empty bounds `(0, 0, 0, 0)` by default for performance, so without `boundsArea` it is culled as invisible when culling is active and `containsPoint` always misses.
### ParticleOptions
`Particle` is a lightweight struct, not a `Container` subclass — none of the `ContainerOptions` fields apply. The full option list:
| Option | Type | Default | Description |
| ---------- | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `texture` | `Texture` | — | Required. Texture used to render this particle. All particles in the same `ParticleContainer` must share the same base texture source. |
| `x` | `number` | `0` | X position in the container's local space. |
| `y` | `number` | `0` | Y position in the container's local space. |
| `scaleX` | `number` | `1` | Horizontal scale factor. |
| `scaleY` | `number` | `1` | Vertical scale factor. |
| `anchorX` | `number` | `0` | Horizontal anchor in 0–1 range; `0` is left, `0.5` is center, `1` is right. |
| `anchorY` | `number` | `0` | Vertical anchor in 0–1 range; `0` is top, `0.5` is center, `1` is bottom. |
| `rotation` | `number` | `0` | Rotation in radians. |
| `tint` | `ColorSource` | `0xffffff` | Tint color as hex number or CSS color string. Combined with `alpha` into the internal `color` field. |
| `alpha` | `number` | `1` | Transparency (0–1). Values outside the range are clamped. Combined with `tint` into the internal `color` field. |
The constructor also accepts a bare `Texture` as its sole argument (`new Particle(texture)`), which is shorthand for `new Particle({ texture })` using the defaults above.
`Particle.defaultOptions` is a static object you can reassign to change defaults globally; see the "Particle creation" section below.
## Core Patterns
### Particle creation
```ts
const particle = new Particle({
texture,
x: 100,
y: 200,
scaleX: 0.5,
scaleY: 0.5,
anchorX: 0.5,
anchorY: 0.5,
rotation: Math.PI / 4,
tint: 0xff0000,
alpha: 0.8,
});
container.addParticle(particle);
```
`Particle` is a lightweight struct with flat numeric fields: `x`, `y`, `scaleX`, `scaleY`, `anchorX`, `anchorY`, `rotation`, `color`, `texture`. It also exposes `tint` (hex/CSS color) and `alpha` (0-1) as setters that combine into the internal `color` field. No transform hierarchy, no events, no filters.
You can pass a `Texture` directly as the sole argument: `new Particle(texture)`.
Override `Particle.defaultOptions` to change defaults globally:
```ts
Particle.defaultOptions = {
...Particle.defaultOptions,
anchorX: 0.5,
anchorY: 0.5,
};
```
### Pre-populating with the particles option
```ts
const particles = Array.from(
{ length: 10000 },
() =>
new Particle({
texture,
x: Math.random() * 800,
y: Math.random() * 600,
}),
);
const container = new ParticleContainer({
texture,
boundsArea: new Rectangle(0, 0, 800, 600),
particles,
});
```
Passing `particles` in the constructor is equivalent to creating the container empty and calling `addParticle` for each one, but avoids per-call view updates.
### Dynamic vs static properties and update()
```ts
const container = new ParticleContainer({
dynamicProperties: {
rotation: true,
},
});
```
`dynamicProperties` controls which particle attributes re-upload to the GPU every frame. The defaults on `ParticleContainer.defaultOptions.dynamicProperties` are:
```ts
{ vertex: false, position: true, rotation: false, uvs: false, color: false }
```
You only need to override the properties you are animating; the rest inherit the defaults (position dynamic, everything else static). Five properties in total:
- `vertex`: scale/anchor vertices
- `position`
- `rotation`
- `uvs`: texture coordinates (for frame-swapped particles)
- `color`: tint and alpha
Mark only what you animate; static properties are cheaper. If you change a static property at runtime, call `container.update()` to re-upload:
```ts
container.particleChildren.forEach((p) => {
p.tint = 0x00ff00;
});
container.update();
```
### Batch operations on particleChildren
```ts
// Bulk add
const batch = [];
for (let i = 0; i < 5000; i++) {
batch.push(
new Particle({ texture, x: Math.random() * 800, y: Math.random() * 600 }),
);
}
container.particleChildren.push(...batch);
container.update();
// Bulk remove
container.particleChildren.length = 0;
container.update();
```
`addParticle`, `addParticleAt`, `removeParticle`, `removeParticleAt`, and `removeParticles` all trigger view updates per call. For large batch operations, direct array manipulation plus a single `update()` is faster.
### Texture and shader options
`texture` in `ParticleContainerOptions` is optional. If omitted, the container falls back to the texture of the first particle added; every subsequent particle must share the same base texture source. Set it explicitly when you want to declare the atlas up front, or when the first particle might change mid-run:
```ts
const container = new ParticleContainer({ texture });
```
`shader` lets you replace the default particle shader with any `Shader` instance. The custom shader must declare the attributes the particle pipe uploads (`aPosition`, `aUV`, `aColor`, plus any dynamic-only attributes enabled via `dynamicProperties`). Use this for custom blending math, distance-field sprites, or non-standard effects:
```ts
const container = new ParticleContainer({ texture, shader: myCustomShader });
```
### Fading or tinting a whole particle system
```ts
const burst = new ParticleContainer({ texture, particles });
const layer = new Container();
layer.addChild(burst);
app.ticker.add(() => {
layer.alpha -= 0.01; // fades every particle
});
burst.tint = 0x66ccff; // tints every particle
```
Container `alpha`, `tint`, and `blendMode` cascade into particles the same way they cascade into sprites, so you can fade or recolor an entire system without touching `particleChildren`.
### Limitations
`ParticleContainer` intentionally sacrifices features for speed:
- No filters, masks, or per-particle blend modes. Blend modes apply at the container level: set `blendMode` on the `ParticleContainer` or let it inherit from a parent `Container` (the default `"inherit"` resolves to the ancestor's blend mode, like `Sprite` and `Mesh`). The whole particle batch shares one blend mode. `alpha` and `tint` on the container or any ancestor multiply into every particle, on top of each particle's own `alpha`/`tint`.
- No nested children on particles.
- No automatic bounds calculation.
- All particles must share the same base texture source (atlases work; multiple unrelated textures do not).
- Custom shaders are supported via the `shader` option.
### Container method migration
`ParticleContainer` uses a separate child management API optimized for GPU buffer updates. The standard `Container` child methods throw when called on a `ParticleContainer`.
| Standard Container method | ParticleContainer equivalent |
| ---------------------------- | --------------------------------------------------- |
| `addChild(child)` | `addParticle(particle)` |
| `removeChild(child)` | `removeParticle(particle)` |
| `addChildAt(child, index)` | `addParticleAt(particle, index)` |
| `removeChildAt(index)` | `removeParticleAt(index)` |
| `removeChildren(begin, end)` | `removeParticles(begin, end)` |
| `getChildAt(index)` | Access `container.particleChildren[index]` directly |
| `swapChildren()` | Not available |
| `reparentChild()` | Not available |
## Common Mistakes
### [CRITICAL] Adding Sprites to ParticleContainer
Wrong:
```ts
const container = new ParticleContainer();
const sprite = new Sprite(texture);
container.addChild(sprite);
```
Correct:
```ts
const container = new ParticleContainer();
const particle = new Particle(texture);
container.addParticle(particle);
```
`ParticleContainer` does not accept `Sprite` children. `addChild` throws an error. Particles must be `Particle` instances (or any object implementing `IParticle`), added via `addParticle`. This is a complete rework from v7, where `ParticleContainer` accepted `Sprite` children.
### [HIGH] Not setting boundsArea on ParticleContainer
Wrong:
```ts
const container = new ParticleContainer();
// bounds is always (0, 0, 0, 0) — culling and hit testing fail
```
Correct:
```ts
const container = new ParticleContainer({
boundsArea: new Rectangle(0, 0, 800, 600),
});
```
`ParticleContainer` returns empty bounds `(0, 0, 0, 0)` by default for performance. Without `boundsArea`, the container is culled as invisible when culling is active, and `containsPoint` always misses. Set `boundsArea` to the region your particles occupy.
### [HIGH] Using children instead of particleChildren
Wrong:
```ts
container.addParticle(new Particle(texture));
console.log(container.children.length); // 0
```
Correct:
```ts
container.addParticle(new Particle(texture));
console.log(container.particleChildren.length); // 1
```
Particles are stored in the `particleChildren` array, not `children`. The standard `Container.children` array is empty on a `ParticleContainer`. All particle enumeration, counting, and manipulation must use `particleChildren` plus the `*Particle` methods.
### [MEDIUM] Do not use ParticleContainer as a normal container
`ParticleContainer` contains particles, not display objects. If you need to group a particle system with a background sprite or UI overlay, wrap the `ParticleContainer` itself inside a plain `Container`:
```ts
const world = new Container();
world.addChild(backgroundSprite, particleContainer, uiLayer);
```
## API Reference
- [ParticleContainer](https://pixijs.download/release/docs/scene.ParticleContainer.html.md)
- [ParticleContainerOptions](https://pixijs.download/release/docs/scene.ParticleContainerOptions.html.md)
- [Particle](https://pixijs.download/release/docs/scene.Particle.html.md)
- [ParticleOptions](https://pixijs.download/release/docs/scene.ParticleOptions.html.md)
- [IParticle](https://pixijs.download/release/docs/scene.IParticle.html.md)
- [ParticleProperties](https://pixijs.download/release/docs/scene.ParticleProperties.html.md)
+120
View File
@@ -0,0 +1,120 @@
---
name: pixijs-scene-sprite
description: "Use this skill when drawing images in PixiJS v8. Covers Sprite with anchor/tint/texture, AnimatedSprite for frame animation, NineSliceSprite for resizable UI panels, TilingSprite for scrolling/repeating backgrounds. Triggers on: Sprite, AnimatedSprite, NineSliceSprite, TilingSprite, Sprite.from, anchor, tint, tilePosition, animationSpeed, gotoAndPlay, leftWidth, topHeight, constructor options, SpriteOptions, AnimatedSpriteOptions, NineSliceSpriteOptions, TilingSpriteOptions."
license: MIT
---
PixiJS has three sprite classes for different drawing tasks. `Sprite` is the default image-drawing leaf; `NineSliceSprite` is a resizable UI-panel variant that preserves corner art; `TilingSprite` repeats a texture across an area. The `AnimatedSprite` subclass of `Sprite` cycles through texture frames for frame-based animation.
Assumes familiarity with `pixijs-scene-core-concepts`. All sprite classes are leaf nodes; they cannot have children. Wrap multiple sprites in a `Container` to group them.
## Quick Start
```ts
const texture = await Assets.load("bunny.png");
const sprite = new Sprite({
texture,
anchor: 0.5,
tint: 0xff8888,
});
sprite.x = app.screen.width / 2;
sprite.y = app.screen.height / 2;
app.stage.addChild(sprite);
```
Position is set after construction because `app.screen.width / 2` depends on the live renderer size. Literal positions can go directly in the options object via `x`/`y` (inherited from `Container`).
**Related skills:** `pixijs-scene-core-concepts` (leaves, transforms), `pixijs-assets` (texture loading), `pixijs-scene-particle-container` (thousands of sprites), `pixijs-performance` (spritesheets, batching).
## Variants
| Variant | Use when | Trade-offs | Reference |
| ----------------- | --------------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------- |
| `Sprite` | Draw a single texture at a position | Fixed size = texture size | [references/sprite.md](references/sprite.md) |
| `AnimatedSprite` | Frame-based animation from a texture array or spritesheet | Pre-rendered frames only; no tweening | [references/animated-sprite.md](references/animated-sprite.md) |
| `NineSliceSprite` | Resizable UI panels, buttons, dialog frames | Border width is fixed; center stretches | [references/nineslice-sprite.md](references/nineslice-sprite.md) |
| `TilingSprite` | Scrolling backgrounds, parallax, repeating patterns | Single texture repeated; `tilePosition` scrolls | [references/tiling-sprite.md](references/tiling-sprite.md) |
`AnimatedSprite` is a subclass of `Sprite`; all `Sprite` properties (anchor, tint, position) apply.
Each variant's constructor options are documented in its sub-reference file (`references/{variant}.md`). All variants also accept the `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
## When to use what
- **"I want to draw a single image at a position"** → `Sprite`. The default choice for 90% of 2D game and app content.
- **"I want to animate a character through a series of frames"** → `AnimatedSprite`. Load a spritesheet via Assets and pass `sheet.animations['walk']`. See `references/animated-sprite.md`.
- **"I want a UI button/panel that resizes without stretching the borders"** → `NineSliceSprite`. Set border widths, then set `width`/`height`. See `references/nineslice-sprite.md`.
- **"I want a scrolling repeating background"** → `TilingSprite`. Animate `tilePosition` to scroll. See `references/tiling-sprite.md`.
- **"I want thousands of identical sprites"** → Use `ParticleContainer` with `Particle` instances (see `pixijs-scene-particle-container`), not plain sprites.
- **"I want to draw shapes or paths"** → Use `Graphics` (see `pixijs-scene-graphics`), not a sprite.
## Quick concepts
### Anchor vs pivot
`Sprite.anchor` is normalized `[0, 1]` and shifts only the texture draw origin; no position offset. `Container.pivot` is pixel-space and shifts both the transform origin and the visual position. For centering a sprite, always use `anchor.set(0.5)`.
### Loading before creating
`Sprite.from(id)` only reads the Assets cache; it does not fetch. Always `await Assets.load(...)` first, or pass the returned `Texture` directly to `new Sprite(texture)`.
### Dynamic textures
Once a texture is loaded, modifying its `frame` or swapping its source does not automatically notify sprites. Set `texture.dynamic = true` once, or call `sprite['onViewUpdate']()` manually after changes.
## Common Mistakes
### [HIGH] Using `Texture.from(url)` to load
Wrong:
```ts
const texture = Texture.from("https://example.com/image.png");
```
Correct:
```ts
const texture = await Assets.load("https://example.com/image.png");
```
`Texture.from()` only reads the cache in v8. Use `Assets.load()` first; its return value is the texture.
### [HIGH] Confusing anchor and pivot
Wrong:
```ts
sprite.pivot.set(sprite.width / 2, sprite.height / 2);
```
Correct:
```ts
sprite.anchor.set(0.5);
```
`anchor` shifts only the draw origin. `pivot` shifts the transform origin AND the visual position, causing the sprite to move unexpectedly.
### [HIGH] Old `NineSlicePlane` name
`NineSlicePlane` was renamed to `NineSliceSprite` in v8 and switched to an options-object constructor: `new NineSliceSprite({ texture, leftWidth, topHeight, rightWidth, bottomHeight })`.
### [MEDIUM] Adding children to a sprite
`Sprite`, `NineSliceSprite`, and `TilingSprite` all set `allowChildren = false`. Wrap in a `Container` to group sprites with other content.
## API Reference
- [Sprite](https://pixijs.download/release/docs/scene.Sprite.html.md)
- [SpriteOptions](https://pixijs.download/release/docs/scene.SpriteOptions.html.md)
- [AnimatedSprite](https://pixijs.download/release/docs/scene.AnimatedSprite.html.md)
- [NineSliceSprite](https://pixijs.download/release/docs/scene.NineSliceSprite.html.md)
- [TilingSprite](https://pixijs.download/release/docs/scene.TilingSprite.html.md)
- [Texture](https://pixijs.download/release/docs/rendering.Texture.html.md)
@@ -0,0 +1,262 @@
# AnimatedSprite
A `Sprite` subclass that cycles through an array of textures for frame-based animation. Use for character walk cycles, explosions, UI icon loops, or any sequence driven by pre-rendered frames from a spritesheet.
## Quick Start
```ts
const sheet = await Assets.load("character.json");
const walk = new AnimatedSprite({
textures: sheet.animations["walk"],
animationSpeed: 0.15,
loop: true,
autoPlay: true,
});
app.stage.addChild(walk);
```
`AnimatedSprite` extends `Sprite`, so anchor, tint, position, and scale all work the same way. It adds frame playback on top. Inherits `allowChildren = false` from `Sprite`.
## Core Patterns
### Construction
```ts
new AnimatedSprite(frames, autoUpdate?);
new AnimatedSprite({ textures, autoUpdate, autoPlay, loop, animationSpeed });
```
Two constructor forms are supported. The options form accepts all `SpriteOptions` (anchor, tint, position, etc.) plus the animation-specific fields below. The positional form takes a frames array and an optional `autoUpdate` flag.
```ts
const sheet = await Assets.load("character.json");
const walk = new AnimatedSprite({
textures: sheet.animations["walk"],
animationSpeed: 0.2,
loop: true,
autoPlay: true,
anchor: 0.5,
x: 200,
y: 300,
});
```
#### AnimatedSpriteOptions
| Option | Type | Default | Description |
| ---------------- | -------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| `textures` | `AnimatedSpriteFrames` | — | Frame list: a `Texture[]` or `FrameObject[]` (each `{ texture, time }` with `time` in ms). Required. |
| `animationSpeed` | `number` | `1` | Playback multiplier; negative values reverse direction. |
| `autoPlay` | `boolean` | `false` | Start playback immediately on construction. |
| `autoUpdate` | `boolean` | `true` | Drive playback from `Ticker.shared`; set `false` to call `update(ticker)` manually. |
| `loop` | `boolean` | `true` | Restart after the last frame; set `false` for one-shot animations. |
| `onComplete` | `() => void` | `null` | Fires when a non-looping animation reaches its end. |
| `onFrameChange` | `(currentFrame: number) => void` | `null` | Fires every time the displayed texture changes. |
| `onLoop` | `() => void` | `null` | Fires when a looping animation wraps back to the start. |
| `updateAnchor` | `boolean` | `false` | Copy `texture.defaultAnchor` onto the sprite's anchor on every frame change. Overrides any previously set anchor. |
Also inherits `SpriteOptions` minus `texture` (use `textures` for frames) — see `sprite.md`. All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
### Playback control
```ts
walk.play();
walk.stop();
walk.gotoAndStop(3);
walk.gotoAndPlay(0);
walk.currentFrame = 2;
console.log(walk.totalFrames);
console.log(walk.playing);
```
- `play()` / `stop()`: start or freeze playback at the current frame.
- `gotoAndStop(frame)` / `gotoAndPlay(frame)`: jump to a specific frame index.
- `currentFrame`: readable and writable. The setter throws if the value is outside `[0, totalFrames - 1]`.
- `totalFrames` (readonly): number of frames in the current texture list.
- `playing` (readonly): current playback state.
### Speed and looping
```ts
walk.animationSpeed = 0.15;
walk.animationSpeed = -1;
walk.loop = false;
```
- `animationSpeed` (default `1`): playback multiplier. Negative reverses direction.
- `loop` (default `true`): restart after last frame. Set to `false` and use `onComplete` for one-shot animations.
### Callbacks
```ts
walk.onComplete = () => console.log("animation done");
walk.onFrameChange = (frame) => console.log(`now on frame ${frame}`);
walk.onLoop = () => console.log("looped back to start");
```
- `onComplete`: fires when a non-looping animation reaches its end.
- `onFrameChange(frameIndex)`: fires every time the displayed texture changes.
- `onLoop`: fires when a looping animation wraps around to the start.
### Auto update
```ts
const walk = new AnimatedSprite({
textures: sheet.animations["walk"],
autoUpdate: false,
});
app.ticker.add((ticker) => {
walk.update(ticker);
});
```
`autoUpdate` (default `true`): uses `Ticker.shared`. Set `false` and call `update(ticker)` manually to drive playback from a custom ticker or pause it with game logic.
### Per-frame timing
```ts
const explosion = new AnimatedSprite({
textures: [
{ texture: frame0, time: 100 },
{ texture: frame1, time: 200 },
{ texture: frame2, time: 300 },
],
});
```
`FrameObject` entries use `{ texture, time }` where `time` is in **milliseconds**, not seconds. Mix per-frame timing for effects that linger on key frames (impact, reveal, pause).
Spritesheets loaded via `Assets.load` expose per-frame `duration` values at `sheet.data.frames[key].duration`. Build a `FrameObject[]` from those durations when you need pre-authored timing:
```ts
const sheet = await Assets.load("0123456789.json");
const frames = [];
for (let i = 0; i < 10; i++) {
const key = `0123456789 ${i}.ase`;
frames.push({
texture: Texture.from(key),
time: sheet.data.frames[key].duration,
});
}
const sprite = new AnimatedSprite(frames);
```
### Factories
```ts
const walk = AnimatedSprite.fromFrames(["walk0.png", "walk1.png", "walk2.png"]);
const idle = AnimatedSprite.fromImages(["idle0.png", "idle1.png"]);
```
- `fromFrames(aliases)`: builds textures via `Texture.from` from Assets cache aliases. Requires the spritesheet to already be loaded.
- `fromImages(urls)`: builds textures from URLs. Does not await loading; textures resolve asynchronously.
Prefer `new AnimatedSprite({ textures: sheet.animations[...] })` after `await Assets.load(...)` for deterministic loading.
### updateAnchor
```ts
const walk = new AnimatedSprite({
textures: sheet.animations["walk"],
updateAnchor: true,
});
```
`updateAnchor` (default `false`): when `true`, the sprite's anchor is copied from the current texture's `defaultAnchor` on every frame change. Useful when exporting frames with per-frame pivot points (e.g., to pin the animation to a moving foot or hand). Overrides any previously set anchor on each frame change.
## Common Mistakes
### [HIGH] Using `Texture.from` on unloaded frames
Wrong:
```ts
const walk = new AnimatedSprite([
Texture.from("walk0.png"),
Texture.from("walk1.png"),
]);
```
Correct:
```ts
const sheet = await Assets.load("character.json");
const walk = new AnimatedSprite(sheet.animations["walk"]);
```
`Texture.from()` only reads the cache in v8. If the spritesheet has not been loaded, the textures resolve to `Texture.EMPTY` and the sprite shows nothing. Always `await Assets.load()` the spritesheet first, then use `sheet.animations[key]`.
### [HIGH] Forgetting to call `play()` or set `autoPlay`
Wrong:
```ts
const walk = new AnimatedSprite({ textures: sheet.animations["walk"] });
app.stage.addChild(walk);
```
Correct:
```ts
const walk = new AnimatedSprite({
textures: sheet.animations["walk"],
autoPlay: true,
});
app.stage.addChild(walk);
```
`autoPlay` defaults to `false`. Without `autoPlay: true` or a manual `walk.play()` call, the sprite displays only the first frame.
### [MEDIUM] Using seconds instead of milliseconds for `FrameObject.time`
Wrong:
```ts
new AnimatedSprite([
{ texture: frame0, time: 0.1 },
{ texture: frame1, time: 0.2 },
]);
```
Correct:
```ts
new AnimatedSprite([
{ texture: frame0, time: 100 },
{ texture: frame1, time: 200 },
]);
```
`FrameObject.time` is in milliseconds. A value of `0.1` will advance frames almost instantly.
### [MEDIUM] Setting `currentFrame` out of range
Wrong:
```ts
walk.currentFrame = walk.totalFrames;
```
Correct:
```ts
walk.currentFrame = walk.totalFrames - 1;
```
The setter throws if the value is outside `[0, totalFrames - 1]`. Use `totalFrames - 1` for the last frame.
## API Reference
- [AnimatedSprite](https://pixijs.download/release/docs/scene.AnimatedSprite.html.md)
- [AnimatedSpriteOptions](https://pixijs.download/release/docs/scene.AnimatedSpriteOptions.html.md)
- [FrameObject](https://pixijs.download/release/docs/scene.FrameObject.html.md)
- [Spritesheet](https://pixijs.download/release/docs/assets.Spritesheet.html.md)
@@ -0,0 +1,202 @@
# NineSliceSprite
A sprite variant that stretches a texture using 9-slice scaling. The four corner regions stay unscaled, the top and bottom edges stretch horizontally, the left and right edges stretch vertically, and the center stretches both ways. Use this for resizable UI panels, buttons, and dialog frames where you want the border art to remain crisp at any size.
## Quick Start
```ts
const texture = await Assets.load("panel.png");
const panel = new NineSliceSprite({
texture,
leftWidth: 20,
topHeight: 20,
rightWidth: 20,
bottomHeight: 20,
width: 400,
height: 200,
});
app.stage.addChild(panel);
```
All four border values default to `10`. Assign `width` / `height` on the sprite (not the texture) to control the stretch region.
## Construction
```ts
const panel = new NineSliceSprite({
texture,
leftWidth: 20,
topHeight: 20,
rightWidth: 20,
bottomHeight: 20,
width: 400,
height: 200,
anchor: 0.5,
});
```
### NineSliceSpriteOptions
| Option | Type | Default | Description |
| -------------- | --------------------- | ----------------------------- | ------------------------------------------------------------------ |
| `texture` | `Texture` | `Texture.EMPTY` | Source texture for the 9-slice. |
| `leftWidth` | `number` | `10` | Width of the left border column that stays unscaled. |
| `topHeight` | `number` | `10` | Height of the top border row that stays unscaled. |
| `rightWidth` | `number` | `10` | Width of the right border column that stays unscaled. |
| `bottomHeight` | `number` | `10` | Height of the bottom border row that stays unscaled. |
| `width` | `number` | `texture.width` (else `100`) | Width of the stretched sprite region; modifies vertices, not UVs. |
| `height` | `number` | `texture.height` (else `100`) | Height of the stretched sprite region; modifies vertices, not UVs. |
| `anchor` | `PointData \| number` | `0` | Normalized draw origin in `[0, 1]`. |
| `roundPixels` | `boolean` | `false` | Snap rendering coordinates to integers for crisp pixel art. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
Border values fall back to `texture.defaultBorders` if set on the texture; see the Texture-defined borders section below.
## Core Patterns
### The 9-slice grid
```
leftWidth rightWidth
+---+--------------------+---+
| 1 | 2 | 3 | topHeight
+---+--------------------+---+
| | | |
| 4 | 5 | 6 |
| | | |
+---+--------------------+---+
| 7 | 8 | 9 | bottomHeight
+---+--------------------+---+
```
- Corners (1, 3, 7, 9): unscaled
- Top and bottom edges (2, 8): stretched horizontally
- Left and right edges (4, 6): stretched vertically
- Center (5): stretched both ways
### Runtime resize
```ts
panel.width = 600;
panel.height = 300;
panel.setSize(600, 300);
const size = panel.getSize();
```
Setting `width` / `height` modifies the sprite's vertices directly. It does not scale the underlying texture. The corners stay fixed-size regardless of how small or large you make the panel. `setSize(value, height?)` and `getSize(out?)` are the override pair used to avoid recomputing bounds twice when both axes change.
### Texture-defined borders
```ts
const texture = new Texture({
source: baseSource,
defaultBorders: { left: 15, top: 15, right: 15, bottom: 15 },
});
const panel = new NineSliceSprite({ texture, width: 400, height: 200 });
```
`defaultBorders` is a readonly Texture property. Pass it in the constructor options (or set it on the spritesheet data so `Assets.load` bakes it into the loaded texture). If the texture has borders set, the sprite picks them up automatically when no explicit border values are passed to the `NineSliceSprite` constructor. Define them once per texture and reuse across multiple panels.
### Border updates
```ts
panel.leftWidth = 25;
panel.rightWidth = 25;
panel.topHeight = 15;
panel.bottomHeight = 15;
```
All four border values are mutable at runtime. The sprite rebuilds its geometry on the next render.
### Source texture dimensions
```ts
console.log(panel.originalWidth, panel.originalHeight);
panel.setSize(panel.originalWidth, panel.originalHeight);
```
`originalWidth` and `originalHeight` are readonly getters that return the underlying `texture.width` / `texture.height`. Use them to reset a panel to its source size or to compute scaled sizes relative to the unstretched texture.
### Global defaults
```ts
NineSliceSprite.defaultOptions.texture = Texture.from("defaultPanel.png");
```
`NineSliceSprite.defaultOptions` is a mutable static object, but only its `texture` field is read as a fallback. Border defaults come from `texture.defaultBorders` (per-texture) or `NineSliceGeometry.defaultOptions` (global), and size defaults fall back to `texture.width` / `texture.height` or `NineSliceGeometry.defaultOptions.width` / `.height`.
### Round pixels for crisp borders
```ts
const panel = new NineSliceSprite({
texture,
leftWidth: 10,
topHeight: 10,
rightWidth: 10,
bottomHeight: 10,
roundPixels: true,
});
```
Use with pixel-art UI textures to avoid sub-pixel seams at the slice boundaries.
## Common Mistakes
### [HIGH] Using the old `NineSlicePlane` name
Wrong:
```ts
import { NineSlicePlane } from "pixi.js";
const panel = new NineSlicePlane(texture, 10, 10, 10, 10);
```
Correct:
```ts
import { NineSliceSprite } from "pixi.js";
const panel = new NineSliceSprite({
texture,
leftWidth: 10,
topHeight: 10,
rightWidth: 10,
bottomHeight: 10,
});
```
`NineSlicePlane` was renamed in v8 and switched to an options-object constructor. The old `NineSlicePlane` name is deprecated — use `NineSliceSprite` instead.
### [HIGH] Setting `texture.scale` to resize the panel
Wrong:
```ts
panel.scale.set(2);
```
Correct:
```ts
panel.width = 400;
panel.height = 200;
```
`scale` stretches the entire geometry including corners, defeating the purpose of 9-slice. Always use `width` / `height` to resize a `NineSliceSprite`; this preserves corner art.
### [MEDIUM] Borders larger than half the texture
If `leftWidth + rightWidth >= texture.width` (or `topHeight + bottomHeight >= texture.height`), no texture pixels are left for the center strip, so it is filled by stretching the seam between the two borders instead of the texture's middle. Keep the sum of opposing borders less than the corresponding texture dimension.
## API Reference
- [NineSliceSprite](https://pixijs.download/release/docs/scene.NineSliceSprite.html.md)
- [NineSliceGeometry](https://pixijs.download/release/docs/scene.NineSliceGeometry.html.md)
@@ -0,0 +1,181 @@
# Sprite
The core image-drawing leaf. Displays a single `Texture` at a transform. Use `Sprite` whenever you want to draw a static image that isn't animated (`AnimatedSprite`), repeating (`TilingSprite`), or resizable with borders (`NineSliceSprite`).
## Quick Start
```ts
const texture = await Assets.load("bunny.png");
const sprite = new Sprite({
texture,
anchor: 0.5,
tint: 0xff8888,
});
sprite.x = app.screen.width / 2;
sprite.y = app.screen.height / 2;
app.stage.addChild(sprite);
```
`Sprite` is a leaf; `allowChildren` is `false`. Wrap sprites in a `Container` if you need to group or nest them.
Position is set after construction because `app.screen.width / 2` depends on the live renderer; literal positions can go directly in the options as `x`/`y`.
## Core Patterns
### Construction
```ts
const fromTexture = new Sprite(texture);
const fromCache = Sprite.from("bunny.png");
const fromCanvasNoCache = Sprite.from(canvas, true);
const withOptions = new Sprite({
texture,
anchor: 0.5,
x: 100,
y: 200,
tint: 0xffcc00,
alpha: 0.8,
roundPixels: true,
});
```
#### SpriteOptions
| Option | Type | Default | Description |
| ------------- | --------------------- | --------------- | ------------------------------------------------------------------------------------- |
| `texture` | `Texture` | `Texture.EMPTY` | Texture to draw. |
| `anchor` | `PointData \| number` | `0` | Normalized draw origin in `[0, 1]`; falls back to `texture.defaultAnchor` when unset. |
| `roundPixels` | `boolean` | `false` | Snap rendering coordinates to integers for crisp pixel art. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
`Sprite.from(source, skipCache?)` accepts a `Texture` or a `TextureSourceLike` (canvas, video, URL). With a cached alias it only reads the cache and returns `Texture.EMPTY` if the texture was not loaded first; always `await Assets.load(...)` for images. The optional second `skipCache` argument forwards to `Texture.from` to avoid storing ephemeral textures in the global cache.
Video and canvas elements work as texture sources too. Load a video file via `await Assets.load('clip.mp4')` and pass the returned texture to `new Sprite(texture)`; on mobile platforms, start playback from a user gesture to satisfy autoplay policies.
### Sizing helpers
```ts
sprite.setSize(200); // square: both axes
sprite.setSize(200, 120); // width and height
sprite.setSize({ width: 200, height: 120 });
const size = sprite.getSize(); // { width, height }
const reused = { width: 0, height: 0 };
sprite.getSize(reused); // write into an existing object
```
`setSize` avoids the double bounds recalculation of setting `width` and `height` separately. `getSize(out?)` returns the current drawn size and optionally writes into a passed object.
### Visual vs source bounds
```ts
const drawn = sprite.visualBounds; // minX, maxX, minY, maxY of the drawn region (anchor-aware)
```
`sprite.visualBounds` is the rectangle the sprite actually draws in local space, accounting for anchor and texture trim. It differs from `getLocalBounds()` when the texture has padding/trim or a non-zero anchor.
### Anchor
```ts
sprite.anchor.set(0.5); // center both axes
sprite.anchor.set(0, 0); // top-left (default)
sprite.anchor.set(1, 0); // top-right
sprite.anchor = { x: 0.5, y: 1 }; // bottom-center
```
`anchor` is normalized `[0, 1]` relative to the texture dimensions. It shifts where the texture draws relative to the sprite's `(x, y)` without offsetting the sprite's position. If omitted, falls back to `texture.defaultAnchor`. Anchor is Sprite-only; it differs from `pivot` (inherited from `Container`, in pixel space); pivot shifts both transform origin and visual position.
### Tint and alpha
```ts
sprite.tint = 0xff0000; // multiply against the texture colors
sprite.alpha = 0.5; // parent-combined transparency
```
`tint` multiplies pixel values; white (`0xffffff`) is a no-op. `alpha` is combined with ancestor alpha up the tree.
### Round pixels
```ts
const sprite = new Sprite({ texture, roundPixels: true });
```
Snaps rendering coordinates to integers for crisp pixel-art. Apply per-sprite, or globally via `TextureStyle.defaultOptions.scaleMode = 'nearest'` + `roundPixels: true` on the renderer.
### Dynamic textures
```ts
texture.dynamic = true;
texture.frame.width /= 2;
texture.update();
```
v8 removed event-based change notification. Set `texture.dynamic = true` once, then normal `texture.update()` calls propagate to all sprites that reference it. Without `dynamic`, you must call `sprite['onViewUpdate']()` manually after mutating the texture.
## Common Mistakes
### [HIGH] Using `Texture.from(url)` to load
Wrong:
```ts
const texture = Texture.from("https://example.com/image.png");
const sprite = new Sprite(texture);
```
Correct:
```ts
const texture = await Assets.load("https://example.com/image.png");
const sprite = new Sprite(texture);
```
In v8, `Texture.from()` only retrieves from the cache. It does not fetch. Use `Assets.load()` first; its return value is the texture, so you don't need a separate `Texture.from()` call.
### [HIGH] Confusing anchor with pivot
Wrong:
```ts
sprite.pivot.set(sprite.width / 2, sprite.height / 2);
```
Correct:
```ts
sprite.anchor.set(0.5);
```
`anchor` is normalized `[0, 1]` and shifts where the texture draws without offsetting position. `pivot` is in pixel space and offsets both the transform origin and the rendered position. For centering a sprite, always use `anchor`.
### [MEDIUM] Adding children to a Sprite
Wrong:
```ts
sprite.addChild(childSprite);
```
Correct:
```ts
const group = new Container();
group.addChild(sprite, childSprite);
```
`Sprite` sets `allowChildren = false`. Adding children logs a deprecation warning and will become a hard error. Group leaves inside a `Container`.
## API Reference
- [Sprite](https://pixijs.download/release/docs/scene.Sprite.html.md)
- [SpriteOptions](https://pixijs.download/release/docs/scene.SpriteOptions.html.md)
- [Texture](https://pixijs.download/release/docs/rendering.Texture.html.md)
@@ -0,0 +1,216 @@
# TilingSprite
A sprite variant that repeats a texture across a given area. The texture can be scrolled, scaled, and rotated independently of the sprite itself. Use for scrolling backgrounds, parallax layers, repeating ground patterns, and any surface that tiles a single texture.
## Quick Start
```ts
const texture = await Assets.load("grass.png");
const bg = new TilingSprite({
texture,
width: app.screen.width,
height: app.screen.height,
});
app.stage.addChild(bg);
app.ticker.add((ticker) => {
bg.tilePosition.x -= 1 * ticker.deltaTime;
});
```
`width` / `height` define the visible tiling region. `tilePosition` scrolls the pattern within that region.
## Construction
```ts
const bg = new TilingSprite({
texture,
width: 800,
height: 600,
tilePosition: { x: 0, y: 0 },
tileScale: { x: 1.5, y: 1.5 },
anchor: 0.5,
roundPixels: true,
});
const fromTexture = TilingSprite.from(texture, { width: 800, height: 600 });
const fromCache = TilingSprite.from("pattern.png", { width: 800, height: 600 });
```
`TilingSprite.from(source, options?)` accepts a `Texture` or a cached alias string. The alias form reads from the Assets cache only; `await Assets.load('pattern.png')` first or the returned sprite draws `Texture.EMPTY`.
### TilingSpriteOptions
| Option | Type | Default | Description |
| ---------------------- | --------------------- | ---------------- | ---------------------------------------------------------------------------------- |
| `texture` | `Texture` | `Texture.EMPTY` | Texture repeated across the tiling region. |
| `width` | `number` | `256` | Width of the visible tiling region. |
| `height` | `number` | `256` | Height of the visible tiling region. |
| `anchor` | `PointData \| number` | `{ x: 0, y: 0 }` | Normalized origin of the tiling sprite itself (not the pattern). |
| `tilePosition` | `PointData` | `{ x: 0, y: 0 }` | Offset of the repeated pattern within the region; animate to scroll. |
| `tileScale` | `PointData` | `{ x: 1, y: 1 }` | Scale applied to the tile pattern only; sprite region stays the same size. |
| `tileRotation` | `number` | `0` | Rotation in radians applied to the texture before tiling. |
| `applyAnchorToTexture` | `boolean` | `false` | Shift the texture origin by the anchor instead of locking `(0,0)` to the top-left. |
| `roundPixels` | `boolean` | `false` | Snap the sprite's position (not the tile pattern) to integer coordinates. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
## Core Patterns
### Scrolling pattern
```ts
app.ticker.add((ticker) => {
bg.tilePosition.x -= 2 * ticker.deltaTime;
bg.tilePosition.y -= 0.5 * ticker.deltaTime;
});
```
`tilePosition` is an `ObservablePoint`. Shifting it moves the pattern without moving the sprite. This is the cheapest way to scroll a background.
### Tile scale and rotation
```ts
bg.tileScale.set(2, 2);
bg.tileRotation = Math.PI / 4;
```
- `tileScale`: scales the pattern independently of the sprite. A value of `{ x: 2, y: 2 }` doubles each tile.
- `tileRotation`: rotates the tile pattern in radians. The rotation is applied to the texture before tiling, so the underlying sprite stays axis-aligned.
### Anchor on the tiling region
```ts
const bg = new TilingSprite({
texture,
width: 800,
height: 600,
anchor: 0.5,
});
bg.x = app.screen.width / 2;
bg.y = app.screen.height / 2;
```
`anchor` is the normalized origin of the tiling sprite itself (same semantics as `Sprite`), not of the repeated tile. The visible region is anchored, the tiles fill it.
### `applyAnchorToTexture`
```ts
const bg = new TilingSprite({
texture,
width: 800,
height: 600,
anchor: 0.5,
applyAnchorToTexture: true,
});
```
By default, the top-left corner of the tiling region always maps to the `(0, 0)` texture coordinate. Set `applyAnchorToTexture: true` to shift the texture origin based on the anchor; useful when you want the pattern to stay centered on the sprite's anchor point as it scales.
### Parallax layers
```ts
const far = new TilingSprite({ texture: farTex, width: 800, height: 600 });
const near = new TilingSprite({ texture: nearTex, width: 800, height: 600 });
app.stage.addChild(far, near);
app.ticker.add((ticker) => {
far.tilePosition.x -= 0.5 * ticker.deltaTime;
near.tilePosition.x -= 2 * ticker.deltaTime;
});
```
Give each layer a different `tilePosition` scroll rate for a parallax effect. Scroll speeds are independent per sprite.
### Round pixels
```ts
const bg = new TilingSprite({
texture,
width: 800,
height: 600,
roundPixels: true,
});
```
Snaps the sprite's position (not the tile pattern) to integer coordinates. Useful for pixel-art tilesets to avoid shimmer.
### Hit testing
```ts
bg.eventMode = "static";
bg.on("pointertap", (e) => {
console.log("tile clicked", bg.toLocal(e.global));
});
```
`TilingSprite` overrides `containsPoint` so hit testing respects the anchor-offset bounds of the tiling region (not the texture). Use it as a regular event target for clickable backgrounds.
### Global defaults
```ts
TilingSprite.defaultOptions.texture = Texture.from("defaultPattern.png");
TilingSprite.defaultOptions.tileScale = { x: 2, y: 2 };
```
`TilingSprite.defaultOptions` is a mutable static object merged with any options passed to the constructor. Override fields once at startup for project-wide defaults.
### Resizing the tiling region
```ts
bg.setSize(app.screen.width, app.screen.height);
const size = bg.getSize();
```
`setSize(value, height?)` accepts a square value, two numbers, or `{ width, height }`. `getSize(out?)` returns the current region and optionally writes into an existing object. Both override the base `Sprite` behavior so a single call avoids recomputing bounds twice.
## Common Mistakes
### [HIGH] Forgetting to pass a texture
Wrong:
```ts
const bg = new TilingSprite({ width: 800, height: 600 });
```
Correct:
```ts
const texture = await Assets.load("pattern.png");
const bg = new TilingSprite({ texture, width: 800, height: 600 });
```
The runtime default is `Texture.EMPTY` (set in `TilingSprite.defaultOptions`), so omitting the texture produces an invisible sprite with nothing to tile. Always pass a real texture.
### [HIGH] Scaling the sprite instead of the tile
Wrong:
```ts
bg.scale.set(2);
```
Correct:
```ts
bg.tileScale.set(2);
```
Scaling the sprite stretches everything; including the visible area. Use `tileScale` to make each tile larger while keeping the sprite's region the same size.
### [MEDIUM] Non-power-of-two textures with `tileScale`
Some WebGL implementations cannot repeat non-power-of-two textures in hardware. If you see the pattern clamp to the edge instead of wrapping, resize the source texture to power-of-two dimensions (128, 256, 512, etc.) or pre-bake the tile pattern into a larger texture.
## API Reference
- [TilingSprite](https://pixijs.download/release/docs/scene.TilingSprite.html.md)
- [TilingSpriteOptions](https://pixijs.download/release/docs/scene.TilingSpriteOptions.html.md)
+136
View File
@@ -0,0 +1,136 @@
---
name: pixijs-scene-text
description: "Use this skill when rendering text in PixiJS v8. Covers Text for canvas-quality styled labels, BitmapText for cheap per-frame updates via glyph atlas, HTMLText for HTML/CSS markup via SVG, SplitText and SplitBitmapText for per-character animation, TextStyle, tagStyles, constructor options, TextOptions, HTMLTextOptions, BitmapText, SplitTextOptions, SplitBitmapTextOptions. Triggers on: Text, BitmapText, HTMLText, SplitText, SplitBitmapText, TextStyle, HTMLTextStyle, BitmapFont.install, tagStyles, fontFamily, wordWrap."
license: MIT
---
PixiJS has five text-rendering classes that cover different trade-offs between styling, performance, and animation. `Text` renders to a canvas for full CSS-style fidelity. `BitmapText` reads from a pre-generated atlas for cheap updates. `HTMLText` renders an HTML fragment via SVG `<foreignObject>` for rich markup. `SplitText` and `SplitBitmapText` wrap the first two classes and expose per-character, per-word, and per-line containers for animation.
Assumes familiarity with `pixijs-scene-core-concepts`. All text classes are leaf nodes; they cannot have children. Wrap multiple text instances in a `Container` to group them.
## Quick Start
```ts
const text = new Text({
text: "Hello PixiJS",
style: {
fontFamily: "Arial",
fontSize: 36,
fill: 0xffffff,
stroke: { color: 0x4a1850, width: 5 },
dropShadow: { color: 0x000000, blur: 4, distance: 6 },
},
});
text.anchor.set(0.5);
text.x = app.screen.width / 2;
text.y = 40;
app.stage.addChild(text);
```
All text classes use options-object constructors; positional `(string, style)` from v7 is not supported.
**Related skills:** `pixijs-scene-core-concepts` (leaves, transforms), `pixijs-assets` (font loading), `pixijs-performance` (BitmapText tradeoffs), `pixijs-color` (`FillInput` for fill/stroke), `pixijs-scene-graphics` (gradients and patterns reused via `FillInput`).
## Variants
| Variant | Use when | Trade-offs | Reference |
| ----------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `Text` | High-quality static or infrequent-update labels | Expensive to update (canvas re-draw + GPU upload) | [references/text.md](references/text.md) |
| `BitmapText` | Scores, timers, gameplay labels, anything that changes every frame | Limited styling; fixed glyph atlas; requires MSDF for crisp scaling | [references/bitmap-text.md](references/bitmap-text.md) |
| `HTMLText` | Rich formatted text, mixed styles, real HTML tags | Async rendering (one frame delay); similar update cost to `Text` | [references/html-text.md](references/html-text.md) |
| `SplitText` | Per-character animation with rich styling | Each char is a full `Text`; expensive for long strings | [references/split-text.md](references/split-text.md) |
| `SplitBitmapText` | Per-character animation on long strings or dynamic content | Inherits BitmapText limitations (glyph atlas, no MSDF-free crispness) | [references/split-bitmap-text.md](references/split-bitmap-text.md) |
## When to use what
- **"I need a styled static label"** → `Text`. Use for titles, menus, dialog, error messages. See `references/text.md`.
- **"I need a score or timer that updates every frame"** → `BitmapText`. Updates only reposition quads; no canvas re-draw. See `references/bitmap-text.md`.
- **"I need mixed formatting with `<b>`, `<i>`, `<br>`"** → `HTMLText`. Real HTML/CSS rendering via SVG. See `references/html-text.md`.
- **"I need inline colored tags like `<red>Warning:</red>`"** → `Text` or `HTMLText` with `tagStyles`. Both support it.
- **"I need to animate each character individually"** → `SplitText` for short strings, `SplitBitmapText` for long strings or many instances. See `references/split-text.md` / `references/split-bitmap-text.md`.
- **"I need CJK / Arabic / emoji-heavy text"** → `Text` or `HTMLText`. `BitmapText` fails because the glyph set is too large for a single atlas.
- **"I need a custom font"** → Load via `Assets.load({ src: 'font.woff2', data: { family: 'MyFont' } })` first, then set `style.fontFamily: 'MyFont'`. Works for `Text` and `HTMLText`.
## Update cost comparison
| Update trigger | Text | BitmapText | HTMLText | SplitText | SplitBitmapText |
| ------------------- | ---- | ---------- | -------- | ----------------------------- | ------------------------ |
| Changing `.text` | High | Very low | High | Very high (N text re-renders) | Low (N quad repositions) |
| Changing `.style` | High | Medium | High | Very high | Medium |
| Moving (`.x`, `.y`) | Free | Free | Free | Free | Free |
| Rotating / scaling | Free | Free | Free | Free | Free |
"Free" = normal Container transform cost. "High" = new canvas draw + GPU upload. "Very low" = quad reposition only. Update strings that change per-frame only on `BitmapText` or `SplitBitmapText`.
## Quick concepts
- **Options-object constructors.** Every v8 text class uses `new Text({ text, style, ... })`. The v7 `(string, style)` form is removed.
- **`tagStyles`.** `Text` and `HTMLText` support per-tag styling via `style.tagStyles`. Tags are only parsed when `tagStyles` has entries; otherwise `<` is treated literally.
- **`BitmapFont.install`.** Pre-generates an atlas before you create any `BitmapText`. Without install, the first `BitmapText` with a new `fontFamily` generates the atlas lazily.
- **MSDF fonts.** Multi-channel Signed Distance Field fonts stay sharp at any size. Generate with external tools (e.g., msdf-bmfont), load via `Assets.load('font.fnt')`. Requires `import 'pixi.js/text-bitmap'` in custom builds.
## Common Mistakes
### [HIGH] Updating `Text.text` every frame
Wrong:
```ts
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
```
Correct:
```ts
const scoreText = new BitmapText({ text: "Score: 0", style });
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
```
Every `Text` update re-rasterizes the whole string. Use `BitmapText` for any value that changes per-frame.
### [HIGH] Positional constructor args
Wrong:
```ts
const text = new Text("Hello", { fontSize: 24 });
```
Correct:
```ts
const text = new Text({ text: "Hello", style: { fontSize: 24 } });
```
v8 removed the `(string, style)` form. All text classes use options objects.
### [HIGH] Not importing `pixi.js/text-bitmap` in custom builds
Under `skipExtensionImports: true` or aggressive tree-shaking, `Assets.load('font.fnt')` silently returns raw data unless you add `import 'pixi.js/text-bitmap'`. The standard `import { ... } from 'pixi.js'` bundle includes the extension.
### [MEDIUM] Adding children to a text instance
Every text class sets `allowChildren = false`. Wrap in a `Container` to group text with other content.
## API Reference
- [Text](https://pixijs.download/release/docs/scene.Text.html.md)
- [TextStyle](https://pixijs.download/release/docs/text.TextStyle.html.md)
- [BitmapText](https://pixijs.download/release/docs/scene.BitmapText.html.md)
- [BitmapFont](https://pixijs.download/release/docs/text.BitmapFont.html.md)
- [HTMLText](https://pixijs.download/release/docs/scene.HTMLText.html.md)
- [HTMLTextStyle](https://pixijs.download/release/docs/text.HTMLTextStyle.html.md)
- [SplitText](https://pixijs.download/release/docs/text.SplitText.html.md)
- [SplitBitmapText](https://pixijs.download/release/docs/text.SplitBitmapText.html.md)
- [AbstractSplitText](https://pixijs.download/release/docs/text.AbstractSplitText.html.md)
- [AbstractText](https://pixijs.download/release/docs/scene.AbstractText.html.md)
@@ -0,0 +1,232 @@
# BitmapText
Text rendered from a pre-generated texture atlas of glyphs. Updating the text string only repositions quads; no canvas re-render, no GPU upload per change. Use `BitmapText` for scores, timers, gameplay labels, and any text whose content changes frequently. Trade-off: limited styling, fixed glyph set, pixel-perfect only at the font's native size (unless you use MSDF).
## Quick Start
```ts
const score = new BitmapText({
text: "Score: 0",
style: {
fontFamily: "Arial",
fontSize: 32,
fill: 0xffffff,
},
});
app.stage.addChild(score);
app.ticker.add(() => {
score.text = `Score: ${Math.floor(performance.now() / 100)}`;
});
```
When you pass a system font family without calling `BitmapFont.install`, the text-bitmap system generates a dynamic bitmap font on first use.
## Construction
```ts
const minimal = new BitmapText({ text: "Score: 0" });
const styled = new BitmapText({
text: "Hello",
style: { fontFamily: "GameFont", fontSize: 48, fill: 0xff0000 },
anchor: 0.5,
roundPixels: true,
});
```
### BitmapTextOptions
`BitmapText`'s constructor accepts the base `TextOptions` directly (no additional bitmap-specific fields). Fields match `references/text.md` with two caveats: `style` is still `TextStyle \| TextStyleOptions` (the same class `Text` uses, but many style fields are ignored by the bitmap pipeline), and `resolution` is managed by the underlying `BitmapFont` at install time rather than per-instance.
| Option | Type | Default | Description |
| ------------- | ------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `text` | `TextString` | `''` | Text content. Same as `Text`. |
| `style` | `TextStyle \| TextStyleOptions` | `new TextStyle()` with `fill = 0xffffff` | Shared TextStyle type; fields like `fontFamily`, `fontSize`, `fill`, `stroke`, `align`, `wordWrap`, `wordWrapWidth`, and `lineHeight` are respected. Gradients as fill and filters are not. See the TextStyle reference in `references/text.md`. |
| `anchor` | `PointData \| number` | `0` | Same as `Text`. |
| `resolution` | `number \| null` | `null` | Accepted but ignored at runtime — set resolution on the `BitmapFont` via `BitmapFont.install({ resolution })` instead. Passing a non-null value logs a warning. |
| `roundPixels` | `boolean` | `false` | Same as `Text`. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
> `BitmapText` does NOT accept `textureStyle` or `autoGenerateMipmaps`; those are specific to canvas `Text` and `HTMLText`. The atlas texture style is controlled when installing the font via `BitmapFont.install({ textureStyle })`.
## Core Patterns
### Dynamic fonts (system font -> runtime atlas)
```ts
const dynamic = new BitmapText({
text: "Hello",
style: { fontFamily: "Arial", fontSize: 32, fill: 0xff1010 },
});
```
The first `BitmapText` with a given `fontFamily` + `fontSize` generates an atlas lazily. Subsequent `BitmapText` instances reuse it. The system also scales an existing close-match size rather than re-generating.
### Pre-installed fonts
```ts
import { BitmapFont } from "pixi.js";
BitmapFont.install({
name: "GameFont",
style: {
fontFamily: "Arial",
fontSize: 48,
fill: 0xffffff,
stroke: { color: "#000000", width: 2 },
},
});
const title = new BitmapText({
text: "Level 1",
style: { fontFamily: "GameFont", fontSize: 48, fill: 0x00ff00 },
});
```
`BitmapFont.install` pre-generates an atlas so the first `BitmapText` render has no setup cost. Useful for known fixed styles in a game.
#### Install options
| Option | Purpose |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chars` | Character set to pre-render. Accepts a string, nested ranges, or a preset: `BitmapFontManager.ALPHA`, `BitmapFontManager.NUMERIC`, `BitmapFontManager.ALPHANUMERIC`, `BitmapFontManager.ASCII`. Essential for non-ASCII, CJK, or restricted charsets. |
| `resolution` | Texture atlas resolution. Default `1`. Use `window.devicePixelRatio` for HiDPI displays. |
| `padding` | Glyph padding inside the atlas. Default `4`. Raise to avoid bleeding at large scales. |
| `skipKerning` | Skip kerning metadata to save memory and install time. Default `false`. |
| `textureStyle` | `TextureStyle`/`TextureStyleOptions` override for the generated atlas (for example `{ scaleMode: 'nearest' }` for pixel fonts). |
| `dynamicFill` | Allow runtime tinting via `BitmapText.tint`. Requires the font `style.fill` to be white, no stroke, no drop shadow, or a drop shadow with color `0x000000` (black). The idiomatic way to color bitmap text without generating a new atlas per color. |
```ts
import { BitmapFont, BitmapFontManager } from "pixi.js";
BitmapFont.install({
name: "UIFont",
chars: BitmapFontManager.ALPHANUMERIC,
resolution: window.devicePixelRatio,
padding: 8,
skipKerning: true,
textureStyle: { scaleMode: "nearest" },
dynamicFill: true,
style: { fontFamily: "Arial", fontSize: 32, fill: 0xffffff },
});
const hp = new BitmapText({
text: "100",
style: { fontFamily: "UIFont", fill: "red" },
});
const mp = new BitmapText({
text: "50",
style: { fontFamily: "UIFont", fill: "blue" },
});
```
### Loaded bitmap fonts (FNT / XML)
```ts
import "pixi.js/text-bitmap";
import { Assets, BitmapText } from "pixi.js";
await Assets.load("fonts/arcade.fnt");
const arcade = new BitmapText({
text: "HIGH SCORE",
style: { fontFamily: "arcade", fontSize: 36 },
});
```
Load `.fnt` or `.xml` files (AngelCode BMFont format) via Assets. Generate them from a `.ttf` / `.otf` with [AssetPack](https://pixijs.io/assetpack/). The side-effect import `'pixi.js/text-bitmap'` registers the loader; required for custom builds that set `skipExtensionImports: true`.
### MSDF / SDF fonts for crisp scaling
Multi-channel Signed Distance Field (MSDF) fonts stay sharp at any size. Generate them with [AssetPack](https://pixijs.io/assetpack/) (Pixi's own asset pipeline, which takes a `.ttf` or `.otf` and emits the `.fnt` + atlas) or [msdf-bmfont](https://msdf-bmfont.donmccurdy.com/). Load them via Assets; they're detected automatically when the FNT file declares a distanceField section.
```ts
await Assets.load("fonts/msdf-hero.fnt");
const heading = new BitmapText({
text: "Title",
style: { fontFamily: "msdf-hero", fontSize: 120 },
});
heading.scale.set(2);
```
MSDF fonts trade CPU rendering time for a custom fragment shader, but remain crisp when scaled up or down.
### Word wrap
```ts
const paragraph = new BitmapText({
text: "A long wrapped paragraph of bitmap text",
style: {
fontFamily: "Arial",
fontSize: 24,
wordWrap: true,
wordWrapWidth: 300,
lineHeight: 30,
},
});
```
Standard TextStyle wrapping properties work. Line-height and alignment (`align: 'center' | 'left' | 'right'`) apply to wrapped output.
### Updating content
```ts
score.text = `Score: ${value}`;
```
Updates reposition glyph quads only. No canvas re-draw, no GPU upload. This is why `BitmapText` is the right choice for every-frame text updates.
## Common Mistakes
### [HIGH] Not importing `pixi.js/text-bitmap` in custom builds
Wrong (custom build with `skipExtensionImports: true`):
```ts
import { Assets } from "pixi.js";
await Assets.load("font.fnt");
```
Correct:
```ts
import "pixi.js/text-bitmap";
import { Assets } from "pixi.js";
await Assets.load("font.fnt");
```
Without the side-effect import, `.fnt` and `.xml` files aren't recognized by the asset loader; the call silently succeeds but returns raw data instead of a `BitmapFont`.
### [MEDIUM] Setting `resolution` on BitmapText
Wrong:
```ts
text.resolution = 2;
```
`BitmapText` ignores `resolution` and logs a warning. The effective resolution is baked into the `BitmapFont` at install time. To get higher resolution, install the font with a larger `fontSize` and scale the text down.
### [MEDIUM] Missing characters silently dropped
If the font atlas doesn't contain a glyph (e.g., a rare Unicode character), the glyph is silently skipped with no visible error. Text may appear incomplete. For unknown or user-generated content, fall back to canvas `Text` or `HTMLText`.
### [HIGH] Using BitmapText for CJK or emoji-heavy content
CJK (Chinese/Japanese/Korean), Arabic, and emoji-heavy strings need thousands of glyphs. A bitmap atlas containing all of them exceeds GPU texture-size limits. Use `Text` or `HTMLText` for text with unpredictable or very large character sets.
## API Reference
- [BitmapText](https://pixijs.download/release/docs/scene.BitmapText.html.md)
- [BitmapFont](https://pixijs.download/release/docs/text.BitmapFont.html.md)
- [BitmapFontManager](https://pixijs.download/release/docs/text.BitmapFontManager.html.md)
- [AbstractBitmapFont](https://pixijs.download/release/docs/text.AbstractBitmapFont.html.md)
@@ -0,0 +1,192 @@
# HTMLText
Text rendered via an SVG `<foreignObject>` wrapping an HTML fragment. This gives you the full HTML/CSS box model for typography; real `<b>`, `<i>`, `<br>`, `<div>`, line-breaks, nested styles, emoji; rasterized to a texture. Use `HTMLText` for rich formatting, mixed content, inline custom tags, or markup that the canvas `Text` class can't express.
## Quick Start
```ts
const rich = new HTMLText({
text: "<b>Bold</b> and <i>italic</i> text",
style: {
fontFamily: "Arial",
fontSize: 24,
fill: 0x333333,
wordWrap: true,
wordWrapWidth: 400,
},
});
app.stage.addChild(rich);
```
`HTMLText` is a leaf. It uses `HTMLTextStyle`, which is `TextStyle` minus `leading`, `textBaseline`, `trim`, and `filters` (those four are unsupported by the SVG rendering path). Rendering is asynchronous; the text may not appear on the same frame it's created.
## Construction
```ts
const minimal = new HTMLText({ text: "<b>Hello</b>" });
const styled = new HTMLText({
text: "<i>Styled</i>",
style: { fontSize: 24, fill: 0xffffff },
anchor: 0.5,
resolution: 2,
autoGenerateMipmaps: true,
textureStyle: { scaleMode: "linear" },
});
```
### HTMLTextOptions
`HTMLText` extends the base `TextOptions` (typed with `HTMLTextStyle` / `HTMLTextStyleOptions` as its style) and adds HTML-specific fields. Inherited `text`, `style`, `anchor`, `resolution`, and `roundPixels` behave as documented in `references/text.md` — only the HTMLText-specific additions are listed here.
| Option | Type | Default | Description |
| --------------------- | --------------------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `style` | `HTMLTextStyle \| HTMLTextStyleOptions` | `new HTMLTextStyle()` | HTML text style object or options. Matches `TextStyle` minus `leading`, `textBaseline`, `trim`, and `filters`. Adds `cssOverrides` for raw CSS injection. |
| `textureStyle` | `TextureStyle \| TextureStyleOptions` | `undefined` | Scale mode for the generated texture (`nearest` or `linear`); every other `TextureStyle` field is ignored. (@advanced) |
| `autoGenerateMipmaps` | `boolean` | `TextureSource.defaultOptions.autoGenerateMipmaps` | Generate mipmaps for the text texture; improves quality when scaled down. |
All base text options (`text`, `anchor`, `resolution`, `roundPixels`) are inherited from `TextOptions` — see `references/text.md`.
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
> Both `textureStyle` and `autoGenerateMipmaps` are also exposed as runtime instance properties, but they are only read when a new texture is generated for the text (a text, style or resolution change); `onViewUpdate()` alone does not regenerate it.
## Core Patterns
### Custom tags via `tagStyles`
```ts
const message = new HTMLText({
text: "<warning>Low power</warning> <custom>Press any key</custom>",
style: {
fontFamily: "Arial",
fontSize: 28,
fill: 0xffffff,
tagStyles: {
warning: { fill: 0xff3333, fontWeight: "bold" },
custom: { fill: 0x66ccff, fontStyle: "italic" },
},
},
});
```
`tagStyles` maps custom (or standard) HTML tag names to style overrides. Inherit is automatic; a nested `<warning>` inside `<custom>` inherits the outer style. Standard tags like `<b>`, `<i>`, `<u>`, `<br>` work as expected.
### Raw CSS overrides
```ts
const styled = new HTMLText({
text: "Underlined shadowed text",
style: { fontSize: 24, fill: 0xffffff },
});
styled.style.addOverride("text-decoration: underline");
styled.style.addOverride("text-shadow: 2px 2px 4px rgba(0,0,0,0.5)");
```
For CSS properties without a `TextStyle` equivalent, use `addOverride` to inject raw CSS. Useful for `text-decoration`, `text-transform`, `letter-spacing` beyond what TextStyle exposes, and any other CSS property supported inside SVG `<foreignObject>`.
### Word wrap
```ts
const wrapped = new HTMLText({
text: "A long paragraph of HTML text that should wrap automatically",
style: {
fontFamily: "Arial",
fontSize: 20,
fill: 0xffffff,
wordWrap: true,
wordWrapWidth: 300,
align: "center",
},
});
```
Word wrap is handled by the browser's SVG layout, so it supports everything CSS wrapping supports; including hyphenation, justification, and RTL scripts when the font and the rendered CSS support them.
### Resolution and mipmaps
```ts
const crisp = new HTMLText({
text: "Retina crisp",
style: { fontSize: 32, fill: 0xffffff },
resolution: 2,
autoGenerateMipmaps: true,
});
```
Same pattern as canvas `Text`: `resolution` controls the rasterized texture density; `autoGenerateMipmaps` improves quality when drawn smaller than native.
### Async rendering
```ts
const htmlText = new HTMLText({
text: "Initial content",
style: { fontSize: 24, fill: 0xffffff },
});
htmlText.visible = false;
app.stage.addChild(htmlText);
app.ticker.addOnce(() => {
htmlText.visible = true;
});
```
HTMLText renders to an SVG blob, then a texture. The texture is available one frame after creation. If you need the text ready before showing it, add it while hidden and reveal it on the next tick.
## Common Mistakes
### [HIGH] Updating HTMLText content every frame
Wrong:
```ts
app.ticker.add(() => {
htmlText.text = `Score: ${score}`;
});
```
Correct:
```ts
const bitmap = new BitmapText({ text: "Score: 0", style });
app.ticker.add(() => {
bitmap.text = `Score: ${score}`;
});
```
Each `HTMLText.text` assignment re-renders the SVG, rasterizes it, and uploads to the GPU. At 60fps this is far too expensive. Use `BitmapText` for any text that changes per-frame.
### [HIGH] Missing CORS headers on fonts
If the HTML references a web font loaded from a different origin without CORS headers, the SVG `<foreignObject>` is tainted and the rasterization fails (or falls back to a default font). Host fonts on the same origin or include `Access-Control-Allow-Origin`.
### [MEDIUM] Expecting HTMLText frame on creation
Wrong:
```ts
const text = new HTMLText({ text: "Hello", style });
text.x = (app.screen.width - text.width) / 2; // text.width is 0 here
```
Correct:
```ts
const text = new HTMLText({ text: "Hello", style });
app.ticker.addOnce(() => {
text.x = (app.screen.width - text.width) / 2;
});
```
HTMLText measurement happens asynchronously. Defer layout calculations to the next frame, or use canvas `Text` when you need immediate metrics.
## API Reference
- [HTMLText](https://pixijs.download/release/docs/scene.HTMLText.html.md)
- [HTMLTextStyle](https://pixijs.download/release/docs/text.HTMLTextStyle.html.md)
- [HTMLTextSystem](https://pixijs.download/release/docs/rendering.HTMLTextSystem.html.md)
@@ -0,0 +1,187 @@
# SplitBitmapText (experimental)
The bitmap counterpart to `SplitText`. Wraps a `BitmapText` and exposes `lines`, `words`, and `chars` as independently-animatable containers. Use `SplitBitmapText` when you want per-character animation on long strings, many simultaneous instances, or text that changes frequently; scenarios where `SplitText`'s per-char canvas rasterization would be too expensive.
## Quick Start
```ts
import { BitmapFont, SplitBitmapText } from "pixi.js";
BitmapFont.install({
name: "GameFont",
style: { fontFamily: "Arial", fontSize: 48 },
});
const split = new SplitBitmapText({
text: "Fast Animate",
style: { fontFamily: "GameFont", fontSize: 48 },
charAnchor: { x: 0.5, y: 1 },
});
app.stage.addChild(split);
split.chars.forEach((char, i) => {
char.onRender = () => {
const t = performance.now() / 200 + i;
char.y = Math.sin(t) * 5;
};
});
```
The API mirrors `SplitText` exactly; the only difference is the underlying text engine. Install a bitmap font (or load one from a `.fnt` file) before creating the instance.
## Construction
```ts
const minimal = new SplitBitmapText({
text: "Hello World",
style: { fontFamily: "GameFont", fontSize: 32 },
});
const full = new SplitBitmapText({
text: "Fast\nPer-char",
style: { fontFamily: "GameFont", fontSize: 48, fill: 0xffffff },
autoSplit: true,
lineAnchor: 0.5,
wordAnchor: { x: 0, y: 0.5 },
charAnchor: { x: 0.5, y: 1 },
x: 100,
y: 200,
});
```
### SplitBitmapTextOptions
`SplitBitmapText` uses the same option shape as `SplitText`: all splitting fields are inherited from `AbstractSplitOptions`, and the only concrete difference is that `style` drives a `BitmapText` render instead of a `Text` render. Like `SplitText`, it is a `Container`, not a `ViewContainer`; the top-level options do NOT include `anchor`, `resolution`, `roundPixels`, `textureStyle`, or `autoGenerateMipmaps`.
| Option | Type | Default | Description |
| ------------ | ---------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text` | `string` | — | Text content to render and segment. Required. |
| `style` | `TextStyle \| Partial<TextStyleOptions>` | — | TextStyle instance or style options; `fill` defaults to `0xffffff` when unset, matching `BitmapText`. See `references/bitmap-text.md` for which fields the bitmap pipeline respects. Required. |
| `autoSplit` | `boolean` | `true` | Automatically re-split when `text` or `style` changes; set `false` to batch updates and call `split.split()` manually. |
| `lineAnchor` | `number \| PointData` | `0` | Normalized transform origin (0–1) for each line container. |
| `wordAnchor` | `number \| PointData` | `0` | Normalized transform origin for each word container. |
| `charAnchor` | `number \| PointData` | `0` | Normalized transform origin for each character container. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
> `SplitBitmapText.defaultOptions` overrides the defaults globally for every new `SplitBitmapText` instance. `SplitBitmapText.from(existingBitmapText, options?)` builds an instance by cloning the source's text and style — `tagStyles` on the source are discarded (bitmap text does not support them) and a warning is logged.
## Core Patterns
### Segment access
```ts
split.lines.forEach((line) => {
line.alpha = 0.9;
});
split.words.forEach((word) => {
word.scale.set(1.1);
});
split.chars.forEach((char) => {
char.rotation = 0.05;
});
```
Each `lines[i]`, `words[i]`, `chars[i]` is a Container wrapping a `BitmapText` instance for that segment. BitmapText glyph quads are cheap, so iterating and transforming hundreds of characters stays performant.
### Transform origins
```ts
const split = new SplitBitmapText({
text: "Wave motion",
style: { fontFamily: "GameFont", fontSize: 48 },
lineAnchor: 0.5,
wordAnchor: { x: 0, y: 0.5 },
charAnchor: { x: 0.5, y: 1 },
});
```
Same normalized 0–1 anchors as `SplitText`: line, word, and char containers each get a separate transform origin. Set once at construction; the anchors apply to every future re-split.
### Stagger animation
```ts
split.chars.forEach((char, i) => {
char.alpha = 0;
});
let elapsed = 0;
app.ticker.add((ticker) => {
elapsed += ticker.deltaMS;
split.chars.forEach((char, i) => {
if (elapsed > i * 50) char.alpha = Math.min(char.alpha + 0.05, 1);
});
});
```
Reveal characters one at a time. Because each char is a cheap BitmapText, this scales to long strings without dropping frames.
### Constructing from an existing BitmapText
```ts
const label = new BitmapText({
text: "Press start",
style: { fontFamily: "GameFont", fontSize: 32 },
});
const animatable = SplitBitmapText.from(label);
```
`SplitBitmapText.from(existingBitmapText)` copies content and style, then splits. Useful for attaching per-character animation to a text that was already laid out elsewhere.
### Updating content
```ts
split.text = "New string";
```
`autoSplit` (default `true`) rebuilds the segment arrays on every text/style change. Per-segment animations attached via `onRender` persist across re-splits as long as you re-apply them in the update step.
## Common Mistakes
### [HIGH] Using SplitBitmapText without a BitmapFont
Wrong:
```ts
const split = new SplitBitmapText({
text: "Hello",
style: { fontFamily: "Arial", fontSize: 48 },
});
```
The above works; dynamic bitmap fonts auto-generate; but for known game fonts prefer pre-installing:
Correct:
```ts
BitmapFont.install({
name: "GameFont",
style: { fontFamily: "Arial", fontSize: 48 },
});
const split = new SplitBitmapText({
text: "Hello",
style: { fontFamily: "GameFont", fontSize: 48 },
});
```
Pre-installation avoids first-render latency and gives you control over the atlas.
### [MEDIUM] Expecting CJK or emoji support
`SplitBitmapText` inherits BitmapText's limitations: the glyph atlas must contain every character, and very large character sets exceed GPU texture size. For per-character animation on CJK or emoji-heavy text, use `SplitText` (which accepts the performance cost) or pre-generate a targeted atlas covering only the characters you'll use.
### [MEDIUM] Missing glyphs silently dropped
If a character isn't in the font atlas, its segment is skipped and no error is thrown. Array indices may not line up one-to-one with source character positions if glyphs are missing. Always test your font against the full string content.
## API Reference
- [SplitBitmapText](https://pixijs.download/release/docs/text.SplitBitmapText.html.md)
- [AbstractSplitText](https://pixijs.download/release/docs/text.AbstractSplitText.html.md)
- [BitmapText](https://pixijs.download/release/docs/scene.BitmapText.html.md)
- [BitmapFont](https://pixijs.download/release/docs/text.BitmapFont.html.md)
@@ -0,0 +1,168 @@
# SplitText
A container that splits a canvas `Text` render into independently-animatable `lines`, `words`, and `chars`; each exposed as its own `Text` instance. Use `SplitText` for per-character intro animations, staggered reveals, or any effect where you need to transform each glyph, word, or line separately.
## Quick Start
```ts
const split = new SplitText({
text: "Animate Me",
style: { fontSize: 48, fill: 0xffffff },
charAnchor: { x: 0.5, y: 1 },
});
app.stage.addChild(split);
split.chars.forEach((char, i) => {
char.alpha = 0;
char.y = -40;
const delay = i * 80;
setTimeout(() => {
app.ticker.add(() => {
char.alpha = Math.min(char.alpha + 0.05, 1);
char.y += (0 - char.y) * 0.1;
});
}, delay);
});
```
`SplitText` is new in v8; API shape may still evolve. It wraps `Text` internally, so the same TextStyle options apply. Every character is a full `Text` instance; use sparingly and prefer `SplitBitmapText` for long strings or many animated instances.
## Construction
```ts
const minimal = new SplitText({
text: "Hello World",
style: { fontSize: 32, fill: 0xffffff },
});
const full = new SplitText({
text: "Animate\nEvery Character",
style: { fontSize: 48, fill: "white", stroke: { color: "black", width: 2 } },
autoSplit: true,
lineAnchor: 0.5,
wordAnchor: { x: 0, y: 0.5 },
charAnchor: { x: 0.5, y: 1 },
x: 100,
y: 200,
alpha: 0.8,
});
```
### SplitTextOptions
`SplitText` is a `Container` (not a `ViewContainer`), so unlike `Text` it does NOT take `anchor`, `resolution`, `roundPixels`, `textureStyle`, or `autoGenerateMipmaps` at the top level. Those belong on the internal per-character `Text` instances. The splitting behavior is controlled by the fields below.
| Option | Type | Default | Description |
| ------------ | ---------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------- |
| `text` | `string` | — | Text content to render and segment. Required. |
| `style` | `TextStyle \| Partial<TextStyleOptions>` | — | TextStyle instance or style options; the same TextStyle used by `Text`. See `references/text.md`. Required. |
| `autoSplit` | `boolean` | `true` | Automatically re-split when `text` or `style` changes; set `false` to batch updates and call `split.split()` manually. |
| `lineAnchor` | `number \| PointData` | `0` | Normalized transform origin (0–1) for each line container; controls the pivot of per-line rotations/scales. |
| `wordAnchor` | `number \| PointData` | `0` | Same as `lineAnchor` but for each word container. |
| `charAnchor` | `number \| PointData` | `0` | Same as `lineAnchor` but for each character container. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
> `SplitText.defaultOptions` overrides the defaults globally for every new `SplitText` instance. The built-in defaults are the values above.
## Core Patterns
### Segment access
```ts
split.lines.forEach((line) => {
line.alpha = 0.8;
});
split.words.forEach((word) => {
word.rotation = 0.1;
});
split.chars.forEach((char) => {
char.scale.set(1.2);
});
```
`lines` and `words` are `Container[]`; `chars` is `Text[]` directly (or `BitmapText[]` for `SplitBitmapText`). All three arrays are refreshed whenever the text or style changes (when `autoSplit` is `true`).
### Transform origins
```ts
const split = new SplitText({
text: "Wave",
style: { fontSize: 64, fill: 0xffffff },
lineAnchor: 0.5,
wordAnchor: { x: 0, y: 0.5 },
charAnchor: { x: 0.5, y: 1 },
});
```
- `lineAnchor`: transform origin for each line container (0–1 normalized).
- `wordAnchor`: transform origin for each word container.
- `charAnchor`: transform origin for each character container.
Setting these once at construction time ensures rotations and scales pivot around the intended point (center, bottom, etc.).
### Animating per character
```ts
split.chars.forEach((char, i) => {
char.onRender = () => {
const t = performance.now() / 200 + i;
char.y = Math.sin(t) * 5;
};
});
```
Using each character's `onRender` hook avoids one global ticker callback. Each char updates itself every render pass.
### Auto-split on change
```ts
split.text = "New text";
```
With `autoSplit = true` (default), reassigning `text` or `style` re-splits and rebuilds the segment arrays. Set `autoSplit = false` to batch multiple changes before calling `split.split()` manually (see `pixijs-scene-text` source).
### Constructing from an existing Text
```ts
const plain = new Text({ text: "Convert me", style: { fontSize: 32 } });
const converted = SplitText.from(plain);
```
`SplitText.from(existingText)` copies content and style, then splits. Useful when you already have a `Text` instance and want to apply per-character animation retroactively.
## Common Mistakes
### [HIGH] Many SplitText instances with long strings
Each character is a full `Text` instance with its own canvas rasterization and GPU texture. A 40-character `SplitText` creates 40 text renders at construction time. For long strings, use `SplitBitmapText`; it wraps `BitmapText` instead, so each character reuses the glyph atlas.
### [MEDIUM] Modifying `chars` array directly
Wrong:
```ts
split.chars.push(extraChar);
```
Correct:
```ts
split.text = split.text + "extra";
```
`chars`, `words`, and `lines` are managed arrays. Pushing to them is ignored and will be overwritten on the next auto-split. Always update via the `text` property and let the class rebuild segments.
### [MEDIUM] Expecting segments before the first render
When `autoSplit` is true, splitting happens lazily on first property read or render. If you need segments immediately after construction, access `chars` (or call `split.split()` manually) once before iterating.
## API Reference
- [SplitText](https://pixijs.download/release/docs/text.SplitText.html.md)
- [AbstractSplitText](https://pixijs.download/release/docs/text.AbstractSplitText.html.md)
- [SplitTextOptions](https://pixijs.download/release/docs/text.SplitTextOptions.html.md)
@@ -0,0 +1,311 @@
# Text (Canvas Text)
The primary text renderer in PixiJS v8. Rasterizes strings to an off-screen canvas via the native Canvas API, then uploads the result as a GPU texture. Use `Text` for high-quality typography, styled labels, UI text, and anything where visual fidelity matters more than update speed. For frequently-changing numeric displays (scores, timers), prefer `BitmapText`.
## Quick Start
```ts
const text = new Text({
text: "Hello PixiJS",
style: {
fontFamily: "Arial",
fontSize: 36,
fill: 0xffffff,
stroke: { color: "#4a1850", width: 5 },
dropShadow: {
color: "#000000",
blur: 4,
distance: 6,
angle: Math.PI / 6,
},
},
anchor: 0.5,
x: 400,
y: 40,
});
app.stage.addChild(text);
```
Text is a leaf (`allowChildren = false`). It uses an options-object constructor; positional `(string, style)` arguments from v7 are no longer supported.
## Construction
```ts
const minimal = new Text({ text: "Hello" });
const styled = new Text({
text: "Styled Text",
style: { fontSize: 24, fill: 0xff1010 },
anchor: 0.5,
resolution: 2,
roundPixels: true,
});
const crisp = new Text({
text: "Crisp Text",
style: { fontSize: 32 },
textureStyle: { scaleMode: "nearest" },
autoGenerateMipmaps: true,
});
```
### CanvasTextOptions
These are the options accepted by `new Text({ ... })`. The concrete `Text` constructor takes `CanvasTextOptions`, which extends the base `TextOptions` with the canvas-specific `textureStyle` and `autoGenerateMipmaps` fields.
| Option | Type | Default | Description |
| --------------------- | ----------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text` | `TextString` (`string \| number \| { toString(): string }`) | `''` | Text content to display; `'\n'` inserts a line break. |
| `style` | `TextStyle \| TextStyleOptions` | `new TextStyle()` | Text style object or options. See the existing TextStyle docs below for field details. |
| `anchor` | `PointData \| number` | `0` | Draw origin in `[0, 1]`; `0.5` is center, `1` is bottom-right. |
| `resolution` | `number` | `null` (auto) | Pixel density of the rasterized texture; `null` follows the renderer's resolution (setting to `null` at runtime enables auto-resolution; the interface type is `number`). |
| `roundPixels` | `boolean` | `false` | Snap rendered x/y to whole pixels to avoid sub-pixel anti-aliasing. |
| `textureStyle` | `TextureStyle \| TextureStyleOptions` | `undefined` | Scale mode for the generated texture (`nearest` or `linear`); every other `TextureStyle` field is ignored. (@advanced) |
| `autoGenerateMipmaps` | `boolean` | `TextureSource.defaultOptions.autoGenerateMipmaps` | Generate mipmaps for the text texture; improves quality when scaled down. |
All `Container` options (`position`, `scale`, `tint`, `label`, `filters`, `zIndex`, etc.) are also valid here — see `skills/pixijs-scene-core-concepts/references/constructor-options.md`.
The `style` field is a rich nested type; the rest of this document covers its key properties.
## Core Patterns
### TextStyle properties
```ts
const styled = new Text({
text: "Styled",
style: {
fontFamily: "Arial",
fontSize: 32,
fontWeight: "bold",
fontStyle: "italic",
fill: 0xff1010,
stroke: { color: "#4a1850", width: 5 },
dropShadow: {
color: "#000000",
blur: 4,
distance: 6,
angle: Math.PI / 6,
alpha: 0.8,
},
align: "center",
wordWrap: true,
wordWrapWidth: 300,
lineHeight: 45,
letterSpacing: 2,
padding: 4,
},
});
```
Key TextStyle properties:
- `fontFamily`, `fontSize`, `fontWeight`, `fontStyle`
- `fill`: color, gradient, or pattern (same `FillInput` as `Graphics`)
- `stroke`: `{ color, width }` object
- `dropShadow`: `{ color, blur, distance, angle, alpha }`
- `wordWrap`, `wordWrapWidth`
- `breakWords`: allow breaking mid-word when wrapping. Requires `wordWrap: true`
- `whiteSpace`: `'normal' | 'pre' | 'pre-line'` whitespace handling for multi-line strings
- `align`: `'left'`, `'center'`, `'right'`, `'justify'`; only affects multi-line text
- `textBaseline`: `'alphabetic' | 'top' | 'hanging' | 'middle' | 'ideographic' | 'bottom'`
- `lineHeight`, `letterSpacing`
- `leading`: additional line spacing in pixels on top of `lineHeight`
- `trim`: boolean; crop transparent padding after rasterization (expensive, use only when needed)
- `padding`: extra space around the rendered texture; increase when a stroke or shadow gets clipped
- `filters`: array of Pixi filters applied to the generated text texture at bake time, cheaper than filters on the `Text` node for static strings
- `tagStyles`: per-tag inline style overrides
### Tagged text
```ts
const alert = new Text({
text: "<red>Warning:</red> system <b>overloaded</b>",
style: {
fontSize: 24,
fill: 0xffffff,
tagStyles: {
red: { fill: 0xff0000 },
b: { fontWeight: "bold" },
},
},
});
```
Tags are parsed only when `tagStyles` has entries; without entries, `<` is treated literally. Nested tags inherit from outer tags via an internal style stack.
### Font loading
```ts
await Assets.load({
src: "my-font.woff2",
data: { family: "MyFont" },
});
const text = new Text({
text: "Custom Font",
style: { fontFamily: "MyFont", fontSize: 36, fill: 0xffffff },
});
```
Supported formats: `woff2` (preferred), `woff`, `ttf`, `otf`. The `data` object is forwarded to `FontFace`; valid fields are `family`, `display`, `style`, `weights` (string array, e.g., `['normal', 'bold']`), `stretch`, `unicodeRange`, `featureSettings`, `variant`.
```ts
await Assets.load({
src: "titan-one.woff",
data: { family: "Titan One", weights: ["normal", "bold"] },
});
```
### Resolution and mipmaps
```ts
const sharp = new Text({
text: "Crisp on retina",
style: { fontSize: 36, fill: 0xffffff },
resolution: 2,
autoGenerateMipmaps: true,
});
```
- `resolution` (default: renderer's resolution): pixel density of the underlying texture. Higher values produce sharper text on high-DPI displays.
- `autoGenerateMipmaps`: improves quality when the text is drawn smaller than its native size.
### Dynamic content
```ts
app.ticker.add(() => {
const next = `Score: ${score}`;
if (scoreText.text !== next) {
scoreText.text = next;
}
});
```
Guard text updates with an equality check when using `Text` for live values. Every assignment triggers a canvas re-render and GPU upload.
### Sharing a TextStyle across instances
```ts
const style = new TextStyle({ fontSize: 24, fill: 0xffffff });
const title = new Text({ text: "Title", style });
const label = new BitmapText({ text: "Label", style });
style.fill = 0xff0000; // both re-render
title.destroy(); // detaches from `style`; `label` keeps using it
```
A `TextStyle` instance can be shared by any number of `Text`, `BitmapText`, and `HTMLText` objects; changing it re-renders all of them. `destroy()` detaches the text from the style without destroying it. Only pass `destroy({ style: true })` (or `destroy(true)`) when no other text object uses that style, since it destroys the shared instance.
### Gradient and pattern fills
```ts
import { FillGradient } from "pixi.js";
const gradient = new FillGradient({
end: { x: 0, y: 1 },
colorStops: [
{ color: 0xff0000, offset: 0 },
{ color: 0x0000ff, offset: 1 },
],
});
const title = new Text({
text: "Gradient",
style: { fontSize: 64, fill: gradient },
});
```
For a texture fill, pass a `FillPattern`. Its constructor takes an options object; the legacy positional form `new FillPattern(texture, repetition)` is also accepted.
```ts
import { Assets, FillPattern } from "pixi.js";
const pattern = new FillPattern({
texture: await Assets.load("bricks.png"),
repetition: "repeat",
});
const label = new Text({
text: "PixiJS",
style: { fontSize: 64, fill: pattern },
});
```
Canvas-rendered text ignores the pattern's `textureSpace`; the texture tiles in the text's pixel space at its native size. Use `pattern.setTransform(matrix)` to scale, rotate, or offset the tiles. A `FillPattern` works for `stroke` too, e.g. `style: { stroke: { fill: pattern, width: 10 } }`.
`fill` accepts any `FillInput` that `Graphics` accepts; gradients, patterns, solid colors, and arrays of stops.
## Common Mistakes
### [HIGH] Updating Text content every frame
Wrong:
```ts
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
```
Correct:
```ts
const scoreText = new BitmapText({ text: "Score: 0", style });
app.ticker.add(() => {
scoreText.text = `Score: ${score}`;
});
```
Every `Text` update re-rasterizes the full string and uploads a new texture. At 60fps this burns frame budget. Use `BitmapText` for values that change per-frame, or at minimum guard with an equality check against the previous string.
### [HIGH] Using positional constructor args
Wrong:
```ts
const text = new Text("Hello", { fontSize: 24 });
```
Correct:
```ts
const text = new Text({ text: "Hello", style: { fontSize: 24 } });
```
v8 `Text` uses an options object. The v7 `(string, style)` signature is not supported.
### [MEDIUM] Stroke or shadow getting clipped at edges
Wrong:
```ts
const text = new Text({
text: "Hello",
style: { stroke: { color: "red", width: 10 } },
});
```
Correct:
```ts
const text = new Text({
text: "Hello",
style: { stroke: { color: "red", width: 10 }, padding: 10 },
});
```
The underlying canvas is sized from the text metrics; heavy strokes or drop-shadows render past those bounds and get clipped. Add `padding` to the style to enlarge the texture.
## API Reference
- [Text](https://pixijs.download/release/docs/scene.Text.html.md)
- [TextStyle](https://pixijs.download/release/docs/text.TextStyle.html.md)
- [TextOptions](https://pixijs.download/release/docs/text.TextOptions.html.md)
- [AbstractText](https://pixijs.download/release/docs/scene.AbstractText.html.md)
+292
View File
@@ -0,0 +1,292 @@
---
name: pixijs-ticker
description: "Use this skill when running per-frame logic or controlling the PixiJS v8 render loop. Covers Ticker.add/addOnce/remove, deltaTime vs deltaMS vs elapsedMS, UPDATE_PRIORITY ordering, maxFPS/minFPS capping, speed scaling, Ticker.shared vs new instances, per-object onRender hook, manual rendering. Triggers on: Ticker, UPDATE_PRIORITY, deltaTime, deltaMS, elapsedMS, onRender, app.ticker, maxFPS, minFPS, Ticker.shared."
license: MIT
---
`app.ticker` runs registered callbacks every frame and drives `app.render()` at `UPDATE_PRIORITY.LOW`. Each callback receives the Ticker instance; read `deltaTime` as a frame-rate-independent multiplier (≈1.0 at 60fps) or `deltaMS` for real-time calculations.
## Quick Start
```ts
app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
sprite.x += (200 / 1000) * ticker.deltaMS;
});
app.ticker.add(
(ticker) => {
updatePhysics(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
app.ticker.maxFPS = 30;
app.ticker.speed = 0.5;
sprite.onRender = () => {
sprite.scale.x = Math.sin(performance.now() / 500);
};
```
**Related skills:** `pixijs-application` (Application setup and sharedTicker option), `pixijs-performance` (frame rate optimization), `pixijs-migration-v8` (v7 ticker signature changes).
## Core Patterns
### Time units
The Ticker exposes three timing values, each for different use cases:
| Property | Type | Scaled by speed? | Capped by minFPS? | Use case |
| ----------- | ----------------------------- | ---------------- | ----------------- | -------------------------------------------- |
| `deltaTime` | dimensionless (~1.0 at 60fps) | yes | yes | Frame-rate-independent animation multipliers |
| `deltaMS` | milliseconds | yes | yes | Time-based calculations (pixels/sec) |
| `elapsedMS` | milliseconds | no | no | Raw measurement, profiling |
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
app.ticker.add((ticker) => {
// deltaTime: dimensionless scalar, ~1.0 at 60fps
sprite.rotation += 0.1 * ticker.deltaTime;
// deltaMS: real milliseconds (speed-scaled, capped)
sprite.x += (200 / 1000) * ticker.deltaMS; // 200 pixels per second
// elapsedMS: raw milliseconds (no scaling, no cap)
console.log(`Raw frame time: ${ticker.elapsedMS}ms`);
});
```
**Tension note:** `deltaTime` is not milliseconds. It is `deltaMS * Ticker.targetFPMS` where targetFPMS is 0.06 (i.e. 1/16.67). At exactly 60fps, deltaTime is 1.0. At 30fps, deltaTime is 2.0. This catches people who treat it as a time value.
### Priority ordering and context binding
```ts
import { Application, UPDATE_PRIORITY } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
// INTERACTION (50) > HIGH (25) > NORMAL (0) > LOW (-25) > UTILITY (-50)
// app.render() is registered at LOW by the TickerPlugin
app.ticker.add(
(ticker) => {
// Physics runs before normal-priority callbacks
updatePhysics(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
app.ticker.add((ticker) => {
// Default priority (NORMAL = 0), runs after HIGH but before render
updateAnimations(ticker.deltaTime);
});
// Pass `this` as the second argument to preserve context on class methods
class GameSystem {
public speed = 5;
public position = 0;
public update(ticker: Ticker): void {
this.position += this.speed * ticker.deltaTime;
}
}
const system = new GameSystem();
app.ticker.add(system.update, system);
app.ticker.remove(system.update, system); // must match both fn and context
```
### Frame rate capping
```ts
import { Ticker } from "pixi.js";
const ticker = new Ticker();
ticker.maxFPS = 30; // Cap at 30fps (skips frames to maintain interval)
ticker.minFPS = 10; // Cap deltaTime so it never exceeds 10fps worth
// If maxFPS < minFPS, minFPS is lowered to match
// If minFPS > maxFPS, maxFPS is raised to match
```
`maxFPS` skips update calls to enforce a ceiling. `minFPS` caps deltaTime/deltaMS so large frame drops don't produce enormous deltas (default minFPS is 10).
### Per-object onRender hook
```ts
import { Sprite, Assets, Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
const texture = await Assets.load("bunny.png");
const sprite = new Sprite(texture);
app.stage.addChild(sprite);
sprite.onRender = (renderer) => {
sprite.rotation += 0.01;
};
```
`onRender` is called during scene graph traversal, before GPU rendering. It is an alternative to a global ticker callback when logic is tied to a specific display object.
### Ticker.shared, Ticker.system, and new Ticker
```ts
import { Ticker, UPDATE_PRIORITY } from "pixi.js";
// Ticker.shared: singleton, autoStart=true, protected from destroy()
const shared = Ticker.shared;
// Ticker.system: separate instance used by engine background tasks,
// independent of the main scene ticker. It's a plain Ticker instance
// (autoStart=true, _protected=true) with no intrinsic priority; listeners
// are typically added at UTILITY priority by convention.
const system = Ticker.system;
// new Ticker(): custom instance, autoStart=false, you manage the lifecycle
const custom = new Ticker();
custom.autoStart = true; // start when first listener is added
custom.add((ticker) => {
console.log(ticker.deltaMS);
});
// One-shot callback that auto-removes after firing
custom.addOnce(() => console.log("fires once"), null, UPDATE_PRIORITY.NORMAL);
// When done:
custom.stop();
custom.destroy();
```
`Application` creates its own Ticker by default. Set `sharedTicker: true` in `app.init()` to use `Ticker.shared` instead. `Ticker.shared` and `Ticker.system` are both `_protected` and will not actually be destroyed if you call `destroy()` on them. Read `ticker.FPS` for the measured frame rate and `ticker.count` for the current listener count.
### App lifecycle and manual rendering
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({ autoStart: false });
// Pause and resume the built-in render loop at any time.
app.start();
app.stop();
// Or drive the loop yourself (headless, visibility-gated, fixed timestep, etc.)
function animate() {
app.ticker.update(); // fires registered callbacks
app.render(); // renders the stage
requestAnimationFrame(animate);
}
animate();
```
`app.start()` and `app.stop()` are added by the `TickerPlugin` and map to `ticker.start()` / `ticker.stop()`. Use `autoStart: false` plus your own frame driver when you need to pause on tab blur, run a fixed-timestep loop, or render offscreen.
### Speed scaling
```ts
import { Application } from "pixi.js";
const app = new Application();
await app.init({ width: 800, height: 600 });
app.ticker.speed = 0.5; // Half speed (slow motion)
app.ticker.speed = 2.0; // Double speed
// speed affects deltaTime and deltaMS, but NOT elapsedMS
```
## Common Mistakes
### [CRITICAL] Ticker callback expects delta as first argument
Wrong:
```ts
app.ticker.add((dt) => {
bunny.rotation += dt;
});
```
Correct:
```ts
app.ticker.add((ticker) => {
bunny.rotation += ticker.deltaTime;
});
```
v8 passes the Ticker instance as the callback argument, not a delta number. The v7 pattern `(dt) => ...` compiles but `dt` is the entire Ticker object, so arithmetic on it produces `NaN`.
### [HIGH] Using updateTransform for per-frame logic
Wrong:
```ts
class MySprite extends Sprite {
updateTransform() {
super.updateTransform();
this.rotation += 0.01;
}
}
```
Correct:
```ts
class MySprite extends Sprite {
constructor() {
super();
this.onRender = this._onRender.bind(this);
}
private _onRender() {
this.rotation += 0.01;
}
}
```
`updateTransform` was removed in v8. Use the `onRender` callback for per-object per-frame logic.
### [MEDIUM] Treating deltaTime as milliseconds
Wrong:
```ts
app.ticker.add((ticker) => {
// Tries to move 100px/sec but deltaTime is ~1.0, not ~16.67
sprite.x += (100 * ticker.deltaTime) / 1000;
});
```
Correct:
```ts
app.ticker.add((ticker) => {
// Using deltaMS for time-based movement
sprite.x += (100 / 1000) * ticker.deltaMS;
// Or using deltaTime as a frame-rate multiplier
sprite.x += 1.5 * ticker.deltaTime;
});
```
`deltaTime` is a dimensionless scalar (~1.0 at 60fps), not milliseconds. Use `deltaMS` for real time calculations. Use `deltaTime` as a simple multiplier when you want "per frame at 60fps" behavior.
## API Reference
- [Ticker](https://pixijs.download/release/docs/ticker.Ticker.html.md)
- [TickerPlugin](https://pixijs.download/release/docs/app.TickerPlugin.html.md)
- [TickerPluginOptions](https://pixijs.download/release/docs/app.TickerPluginOptions.html.md)
+66
View File
@@ -0,0 +1,66 @@
---
name: pixijs
description: "Use this skill first for ANY PixiJS v8 task; it routes to the right specialized skill for the job. Covers the full PixiJS surface: Application setup, the scene graph (Container, Sprite, Graphics, Text, Mesh, ParticleContainer, DOMContainer, GifSprite), rendering (WebGL/WebGPU/Canvas, render loop, custom shaders, filters, blend modes), assets, events, color, math, ticker, accessibility, performance, environments, migration from v7, and project scaffolding. Triggers on: pixi, pixi.js, pixijs, PixiJS, v8, Application, app.init, Sprite, Container, Graphics, Text, Mesh, ParticleContainer, DOMContainer, GifSprite, Assets, Ticker, renderer, WebGL, WebGPU, scene graph, filter, shader, blend mode, texture, 3D texture, depth slice, layer, storage texture, BitmapText, create-pixi, how do I draw, how do I render, how do I animate in pixi."
license: MIT
---
Entry point for the PixiJS v8 skill collection. PixiJS is the fastest library available for the web, working across all devices and allowing you to create rich, interactive graphics and cross-platform applications using WebGL, WebGPU, and Canvas as a fallback.
## How to use this skill
1. Find the specialized skill in the router below that best matches the task.
2. Load that skill's `SKILL.md` and follow its guidance.
3. If no sub-skill fits (the task references a specific class, function, option, or API surface not listed below), **WebFetch `https://pixijs.download/release/docs/llms.txt`**. That file is the auto-generated, always-current index of the full PixiJS API and guides. Each entry links to a `.html.md` page you can WebFetch for the detailed content.
For the long-form description and trigger keywords of every skill, see [references/index.md](references/index.md).
## Skill router
### Foundations
| Skill | Load when... |
|---|---|
| [pixijs-application](../pixijs-application/SKILL.md) | Creating or configuring a PixiJS `Application`, calling `app.init()`, accessing `app.stage`/`renderer`/`canvas`/`screen`, resize/ticker plugins, `app.destroy()`. |
| [pixijs-core-concepts](../pixijs-core-concepts/SKILL.md) | Understanding the renderer pipeline, choosing WebGL/WebGPU/Canvas, render loop internals, systems and pipes, renderer loader extensions, rendering into a `RenderTexture`/`RenderTarget` (`flipY`, `mipLevel`, `layer`, `bind`/`push`/`pop`, depth) or a depth slice of a 3D texture, WebGL context loss and WebGPU device loss. |
| [pixijs-create](../pixijs-create/SKILL.md) | Scaffolding a new project with the `create-pixi` CLI (bundler-vite, creation-web, framework-react templates), adding PixiJS to an existing project, or setting up `tsconfig.json` for TypeScript 5, 6, or 7 (`moduleResolution`, `@webgpu/types`, `@types/web`). |
| [pixijs-environments](../pixijs-environments/SKILL.md) | Running PixiJS in Web Workers, Node/SSR, or strict-CSP contexts (`DOMAdapter`, `WebWorkerAdapter`, `pixi.js/unsafe-eval`). |
| [pixijs-migration-v8](../pixijs-migration-v8/SKILL.md) | Upgrading from v7 to v8 or fixing v7 patterns (`beginFill`/`endFill`, `@pixi/*` packages, `BaseTexture`, `DisplayObject`). |
| [pixijs-scene-core-concepts](../pixijs-scene-core-concepts/SKILL.md) | Understanding the scene graph as a whole: containers vs leaves, transforms, render order, masking, `RenderLayer`. |
### Scene Objects
| Skill | Load when... |
|---|---|
| [pixijs-scene-container](../pixijs-scene-container/SKILL.md) | Working with `Container`: `addChild`/`removeChild`, transforms, `zIndex`, bounds, `toGlobal`/`toLocal`, `destroy`. |
| [pixijs-scene-sprite](../pixijs-scene-sprite/SKILL.md) | Drawing images: `Sprite`, `AnimatedSprite`, `NineSliceSprite`, `TilingSprite`. |
| [pixijs-scene-graphics](../pixijs-scene-graphics/SKILL.md) | Drawing vector shapes or paths: `Graphics`, `GraphicsContext`, `fill`/`stroke`, `FillGradient`, `FillPattern`, `textureSpace`, texture and pattern fills, SVG import (`svg()`, gradients). |
| [pixijs-scene-text](../pixijs-scene-text/SKILL.md) | Rendering text: `Text`, `BitmapText`, `HTMLText`, `SplitText`, `TextStyle`. |
| [pixijs-scene-mesh](../pixijs-scene-mesh/SKILL.md) | Custom geometry: `Mesh`, `MeshSimple`, `MeshPlane`, `MeshRope`, `PerspectiveMesh`. |
| [pixijs-scene-particle-container](../pixijs-scene-particle-container/SKILL.md) | Rendering thousands of lightweight sprites: `ParticleContainer`, `Particle`, `dynamicProperties`. |
| [pixijs-scene-dom-container](../pixijs-scene-dom-container/SKILL.md) | Overlaying HTML elements on the canvas: `DOMContainer`, `pixi.js/dom`. |
| [pixijs-scene-gif](../pixijs-scene-gif/SKILL.md) | Displaying animated GIFs: `GifSprite`, `GifSource`, `pixi.js/gif`. |
| [pixijs-html-source](../pixijs-html-source/SKILL.md) | Rendering live HTML/DOM elements or snapshots as textures (experimental, needs a browser that supports the HTML-in-Canvas spec): `HTMLSource`, `ElementImageSource`, `pixi.js/html-source`, `requestPaint`. |
### Utilities
| Skill | Load when... |
|---|---|
| [pixijs-assets](../pixijs-assets/SKILL.md) | Loading resources: `Assets.init`, `Assets.load`, bundles, manifests, spritesheets, caching. |
| [pixijs-color](../pixijs-color/SKILL.md) | Creating or converting colors: `Color` class, hex/rgb/hsl, `tint`, `premultiply`. |
| [pixijs-events](../pixijs-events/SKILL.md) | Handling pointer/mouse/touch/wheel input: `eventMode`, `FederatedEvent`, `hitArea`, `cursor`, drag. |
| [pixijs-math](../pixijs-math/SKILL.md) | Points, vectors, matrices, shapes, hit testing: `Point`, `Matrix`, `Rectangle`, `Polygon`, `Triangle`, `strokeContains`, `containsRect`, `Matrix.decompose` (mirrored matrices), `toGlobal`/`toLocal`. |
| [pixijs-ticker](../pixijs-ticker/SKILL.md) | Per-frame logic or controlling the render loop: `Ticker`, `deltaTime`, `UPDATE_PRIORITY`, `maxFPS`. |
### Advanced
| Skill | Load when... |
|---|---|
| [pixijs-accessibility](../pixijs-accessibility/SKILL.md) | Screen reader or keyboard navigation: `AccessibilitySystem`, `accessibleTitle`, `tabIndex`. |
| [pixijs-blend-modes](../pixijs-blend-modes/SKILL.md) | Compositing with blend modes: `add`, `multiply`, `screen`, `overlay`, `pixi.js/advanced-blend-modes`. |
| [pixijs-custom-rendering](../pixijs-custom-rendering/SKILL.md) | Writing custom shaders, uniforms, or batchers: `Shader.from`, `GlProgram`/`GpuProgram`, `UniformGroup`, custom `Filter`, WGSL `override` constants, `gpuLayout`, `TextureView`, `Buffer.update`, `TexturePool`, 3D/array textures, storage textures, render bundles, custom pipes. |
| [pixijs-filters](../pixijs-filters/SKILL.md) | Applying visual effects: `BlurFilter`, `ColorMatrixFilter`, `DisplacementFilter`, `Filter.from`, `pixi-filters`. |
| [pixijs-performance](../pixijs-performance/SKILL.md) | Profiling or optimizing FPS, draw calls, GPU memory: culling, `GCSystem`, `cacheAsTexture`, object pooling, transient MSAA render textures, render bundles, filter texture sizing. |
## Fallback: canonical PixiJS docs
If the task references a class, function, option, or API surface not covered by any sub-skill above, **WebFetch `https://pixijs.download/release/docs/llms.txt`**. It's the auto-generated index of the full PixiJS API and guides, regenerated on every release. Each entry links to a `.html.md` page you can WebFetch for the detailed content. Use this fallback whenever the router table doesn't point at an obvious match.
+136
View File
@@ -0,0 +1,136 @@
# PixiJS Skills: Full Index
Detailed routing table for the PixiJS v8 skill collection. Each entry lists the skill's full description and the trigger keywords that should match it. For a scannable short-form table, see the parent `SKILL.md`.
## Foundations
### pixijs-application
Create and configure a PixiJS v8 `Application`. Covers `new Application()` + async `app.init()` options (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas), `app.stage`/`renderer`/`canvas`/`screen` access, `ResizePlugin`, `TickerPlugin`, and `app.destroy()`.
**Triggers:** Application, app.init, app.stage, app.renderer, app.canvas, app.screen, ApplicationOptions, resizeTo, preference, autoStart, sharedTicker, app.destroy.
### pixijs-core-concepts
How PixiJS v8 renders frames: the systems-and-pipes renderer, the render loop, and how the library adapts to different environments. Covers `WebGLRenderer`/`WebGPURenderer`/`CanvasRenderer` selection, `renderer.render()` pipeline, environment detection, and pointers to per-topic deep dives.
**Triggers:** renderer, WebGL, WebGPU, Canvas, render loop, render pipeline, systems, environments, autoDetectRenderer, RenderTexture, RenderTarget, render to texture, flipY, mipLevel, layer, 3D texture, depth slice, renderTarget.bind, copyToTexture, copyDepthTexture, depth-only, WebGLLoader, WebGPULoader, CanvasLoader, RendererLoader, lazy-load renderer systems, context lost, webglcontextlost, device lost, GPUDevice.lost.
### pixijs-create
Scaffold a new PixiJS v8 project with the `create-pixi` CLI or add PixiJS to an existing project. Covers npm/yarn/pnpm/bun create commands, interactive vs non-interactive flows, available template presets (bundler-vite, bundler-webpack, bundler-esbuild, bundler-import-map, creation-web, framework-react, extension-default), Node version requirements, TypeScript 5/6/7 tsconfig setup (`moduleResolution`, `@webgpu/types`, `@types/web`), and post-scaffold dev flow.
**Triggers:** create pixi.js, npm create, scaffold, template, bundler-vite, bundler-webpack, creation-web, framework-react, new project, getting started, TypeScript, tsconfig, moduleResolution, @webgpu/types, @types/web, Cannot find name GPUTextureUsage.
### pixijs-environments
Run PixiJS v8 outside a standard browser: Web Workers, `OffscreenCanvas`, Node/SSR, or CSP-restricted contexts. Covers `DOMAdapter.set`, `BrowserAdapter`, `WebWorkerAdapter`, custom `Adapter` interface, `pixi.js/unsafe-eval` for strict CSP.
**Triggers:** DOMAdapter, BrowserAdapter, WebWorkerAdapter, Web Worker, OffscreenCanvas, Node, headless, SSR, CSP, unsafe-eval, Adapter.
### pixijs-migration-v8
Upgrade a PixiJS project from v7 to v8 or diagnose broken v7 code after an upgrade. Covers async `app.init`, single `pixi.js` package (deprecated `@pixi/*` sub-packages), `Graphics` shape-then-fill, `BaseTexture` -> `TextureSource`, shader/uniform rework, `ParticleContainer`+`Particle`, constructor options objects, `DisplayObject` removal, `settings`/`utils` removal, `Ticker` signature, events rewrite.
**Triggers:** migrate v7, v8 breaking changes, @pixi/ import, DisplayObject, beginFill, endFill, cacheAsBitmap, BaseTexture, deprecated.
### pixijs-scene-core-concepts
The PixiJS v8 scene graph as a whole: how containers, leaves, transforms, and render order fit together. Covers leaf vs container distinction, local/world coordinates, culling, render groups, sortable children, masking, `RenderLayer`, and which leaf skill covers which display object.
**Triggers:** scene graph, display list, Container, Sprite, Graphics, Text, Mesh, ParticleContainer, DOMContainer, GifSprite, masking, mask texture destroyed, MaskFilter, render group, RenderLayer, world transform.
## Scene Objects
### pixijs-scene-container
Group, position, or transform display objects. Covers `Container` constructor options (`isRenderGroup`, `sortableChildren`, `boundsArea`), `addChild`/`removeChild`/`addChildAt`/`swapChildren`/`setChildIndex`, `position`/`scale`/`rotation`/`pivot`/`skew`/`alpha`/`tint`, `getBounds`/`getGlobalPosition`/`toLocal`/`toGlobal`, `zIndex` sorting, `cullable`, `destroy`.
**Triggers:** Container, addChild, removeChild, addChildAt, swapChildren, sortableChildren, zIndex, position, scale, rotation, pivot, getBounds, toGlobal, toLocal, destroy.
### pixijs-scene-dom-container
Overlay HTML elements on the PixiJS v8 canvas. Covers `DOMContainer` with `element`, `anchor`, and scene-graph-driven CSS transforms, the `pixi.js/dom` side-effect import, `DOMPipe` registration, visibility sync, pointer-events handling.
**Triggers:** DOMContainer, pixi.js/dom, DOMPipe, HTML overlay, input on canvas, iframe overlay, DOMContainerOptions, element, anchor.
### pixijs-scene-gif
Display animated GIFs. Covers the `pixi.js/gif` side-effect import, `Assets.load` returning a `GifSource`, `GifSprite` playback (`play`/`stop`/`currentFrame`/`animationSpeed`), `autoPlay`/`loop` options, `onComplete`/`onLoop`/`onFrameChange` callbacks, `GifSource` sharing, `clone`, `destroy`.
**Triggers:** GifSprite, GifSource, pixi.js/gif, animationSpeed, currentFrame, autoPlay, onComplete, onFrameChange.
### pixijs-html-source
Render live HTML/DOM elements or frozen snapshots as PixiJS v8 textures via the HTML-in-Canvas browser APIs. Experimental: requires a browser that supports the HTML-in-Canvas spec (the API must be enabled, or the texture uploader throws on first render). Covers the `pixi.js/html-source` side-effect import, feature detection with `canvas.requestPaint`, `HTMLSource` for a live repainting element (`autoLayout`/`autoUpdate`/`autoRequestPaint`, `requestPaint`, `isReady`, the direct-child-of-canvas + `layoutsubtree` rule), `ElementImageSource` for an immutable `captureElementImage()` snapshot (`autoClose`, ready immediately), using the source on a `Sprite`/`Texture`/`Mesh`, and fallback-only auto-detection via `Texture.from`.
**Triggers:** HTMLSource, ElementImageSource, pixi.js/html-source, requestPaint, captureElementImage, ElementImage, layoutsubtree, autoRequestPaint, autoClose, HTML in canvas, HTML-in-Canvas, render DOM to texture, render HTML to texture, HTMLSourceCanvas, texElementImage2D, copyElementImageToTexture, experimental.
### pixijs-scene-graphics
Draw vector shapes and paths. Covers the `Graphics` shape-then-fill API (`rect`/`circle`/`ellipse`/`poly`/`roundRect`/`star`), path methods (`moveTo`/`lineTo`/`bezierCurveTo`/`arc`), `fill`/`stroke`/`cut`, `FillGradient`, `FillPattern`, `GraphicsContext` sharing, SVG markup.
**Triggers:** Graphics, GraphicsContext, rect, circle, poly, roundRect, fill, stroke, cut, FillGradient, FillPattern, FillPatternOptions, textureSpace, pattern fill, texture fill, spritesheet fill, radialGradient, linearGradient, svg gradient, moveTo, bezierCurveTo, svg.
### pixijs-scene-mesh
Render custom geometry. Covers `Mesh` with `MeshGeometry` (positions, uvs, indices, topology), `MeshSimple` for per-frame vertex animation, `MeshPlane` for subdivided deformation, `MeshRope` for path-following textures, `PerspectiveMesh` for 2.5D corners.
**Triggers:** Mesh, MeshGeometry, MeshSimple, MeshPlane, MeshRope, PerspectiveMesh, positions, uvs, indices, topology, setCorners.
### pixijs-scene-particle-container
Render thousands of lightweight sprites. Covers `ParticleContainer` with `Particle` instances, `addParticle`/`removeParticle`, `particleChildren` array, `dynamicProperties` (vertex, position, rotation, uvs, color), `boundsArea`, `roundPixels`, `update`.
**Triggers:** ParticleContainer, Particle, IParticle, addParticle, particleChildren, dynamicProperties, boundsArea, particle effects, particle alpha, particle tint, fade particles.
### pixijs-scene-sprite
Draw images. Covers `Sprite` with `anchor`/`tint`/`texture`, `AnimatedSprite` for frame animation, `NineSliceSprite` for resizable UI panels, `TilingSprite` for scrolling/repeating backgrounds.
**Triggers:** Sprite, AnimatedSprite, NineSliceSprite, TilingSprite, Sprite.from, anchor, tint, tilePosition, animationSpeed, gotoAndPlay, leftWidth, topHeight.
### pixijs-scene-text
Render text. Covers `Text` for canvas-quality styled labels, `BitmapText` for cheap per-frame updates via glyph atlas, `HTMLText` for HTML/CSS markup via SVG, `SplitText` and `SplitBitmapText` for per-character animation, `TextStyle`, `tagStyles`.
**Triggers:** Text, BitmapText, HTMLText, SplitText, SplitBitmapText, TextStyle, HTMLTextStyle, BitmapFont.install, tagStyles, fontFamily, wordWrap, textureStyle, scaleMode, context loss.
## Utilities
### pixijs-assets
Load and manage resources. Covers `Assets.init`, `Assets.load`/`add`/`unload`, bundles, manifests, background loading, `onProgress`, caching, spritesheets, compressed textures, SVG as texture or Graphics, resolution detection.
**Triggers:** Assets, Assets.load, Assets.init, loadBundle, manifest, backgroundLoad, Spritesheet, Cache, LoadOptions, unload, svg, loadSvg, parseAsGraphicsContext, svg gradient.
### pixijs-color
Create, convert, or manipulate colors. Covers `Color` class input formats (hex, CSS names, RGB/HSL objects, arrays, `Uint8Array`), conversion methods (`toHex`, `toNumber`, `toArray`, `toRgba`), component access, `setAlpha`/`multiply`/`premultiply`, `Color.shared` singleton.
**Triggers:** Color, ColorSource, hex, rgb, hsl, tint, premultiply, Color.shared, color conversion.
### pixijs-events
Handle pointer, mouse, touch, or wheel input. Covers `eventMode` (none, passive, auto, static, dynamic), `FederatedEvent` types, propagation and capture phase, `hitArea`, `interactiveChildren`, `cursor` and `cursorStyles`, global move events for drag, `eventFeatures` config.
**Triggers:** eventMode, FederatedPointerEvent, pointerdown, click, tap, globalpointermove, drag, hitArea, cursor, stopPropagation, persistentDeviceId.
### pixijs-math
Coordinates, vectors, matrices, shapes, and hit testing. Covers `Point`/`ObservablePoint`, `Matrix` (2D affine, decompose, apply), shapes (`Rectangle`, `Circle`, `Ellipse`, `Polygon`, `RoundedRectangle`, `Triangle`), `toGlobal`/`toLocal`, `PointData` types, `DEG_TO_RAD`, and `pixi.js/math-extras` vector helpers.
**Triggers:** Point, ObservablePoint, Matrix, Rectangle, Circle, Polygon, Triangle, RoundedRectangle, strokeContains, containsRect, intersects, isClockwise, winding order, stroke hit test, decompose, mirror, flip, negative scale, setFromMatrix, toGlobal, toLocal, hitArea, math-extras, DEG_TO_RAD, PointData.
### pixijs-ticker
Run per-frame logic or control the render loop. Covers `Ticker.add`/`addOnce`/`remove`, `deltaTime` vs `deltaMS` vs `elapsedMS`, `UPDATE_PRIORITY` ordering, `maxFPS`/`minFPS` capping, speed scaling, `Ticker.shared` vs new instances, per-object `onRender` hook, manual rendering.
**Triggers:** Ticker, UPDATE_PRIORITY, deltaTime, deltaMS, elapsedMS, onRender, app.ticker, maxFPS, minFPS, Ticker.shared.
## Advanced
### pixijs-accessibility
Add screen reader and keyboard navigation to PixiJS v8 apps. Covers `AccessibilitySystem` options (`enabledByDefault`, `debug`, `activateOnTab`, `deactivateOnMouseMove`), per-container accessibility properties, shadow DOM overlay, mobile touch-hook activation.
**Triggers:** accessibility, a11y, screen reader, ARIA, keyboard navigation, tab order, AccessibilitySystem, accessibleTitle, accessibleHint, tabIndex, accessibleChildren.
### pixijs-blend-modes
Composite display objects with blend modes. Covers standard modes (`normal`, `add`, `multiply`, `screen`, `erase`, `min`, `max`), advanced modes via `pixi.js/advanced-blend-modes` (`color-burn`, `overlay`, `hard-light`, etc.), batch-friendly ordering.
**Triggers:** blendMode, additive, multiply, screen, overlay, color-burn, color-dodge, advanced-blend-modes, glow, erase.
### pixijs-custom-rendering
Write custom shaders, uniforms, or batchers. Covers `Shader.from({gl, gpu, resources})`, `GlProgram`/`GpuProgram`, `UniformGroup` with typed uniforms (`f32`, `vec2`, `mat4x4`), UBO mode, textures as resources, 3D and array textures, WebGPU storage textures, custom `Filter`, custom `Batcher` via extensions.
**Triggers:** Shader, GlProgram, GpuProgram, UniformGroup, Batcher, Filter, GLSL, WGSL, UBO, uniform, custom shader, ShaderOverrides, gpuLayout, bind group layout, TextureView, depth texture, 3D texture, sampler3D, texture_3d, storage texture, Buffer.update, vertexCount, indexCount, getSize, clockwiseFrontFace, cullMode, render bundle, beginBundle, executeBundle, RenderBundle, TexturePool, getOptimalTexture, InstructionPipe, destroyInstructionSet.
### pixijs-filters
Apply visual effects to containers via the filter pipeline. Covers built-in filters (`AlphaFilter`, `BlurFilter`, `ColorMatrixFilter`, `DisplacementFilter`, `NoiseFilter`), custom `Filter.from()` with GLSL/WGSL, options (`resolution`, `padding`, `antialias`, `blendRequired`), `filterArea` optimization, `pixi-filters` community package.
**Triggers:** filters, BlurFilter, ColorMatrixFilter, DisplacementFilter, NoiseFilter, Filter.from, GLSL filter, pixi-filters, filterArea.
### pixijs-performance
Profile or optimize a PixiJS v8 app for FPS, draw calls, or GPU memory. Covers destroy patterns (`cacheAsTexture(false)`, `releaseGlobalResources`), `GCSystem` and `TextureGCSystem`, `PrepareSystem`, object pooling, batching rules, `BitmapText` for dynamic text, culling (`Culler`, `CullerPlugin`, `cullable`, `cullArea`), resolution/antialias tradeoffs.
**Triggers:** FPS, jank, draw calls, batching, object pool, GCSystem, PrepareSystem, Culler, cacheAsTexture, memory leak, destroy patterns, render bundle, transient, MSAA, Buffer.update, WebGPU performance, TexturePool, repeatEdgePixels, bind group.
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-accessibility
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-application
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-assets
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-blend-modes
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-color
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-core-concepts
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-create
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-custom-rendering
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-environments
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-events
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-filters
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-html-source
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-math
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-migration-v8
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-performance
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-container
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-core-concepts
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-dom-container
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-gif
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-graphics
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-mesh
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-particle-container
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-sprite
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-scene-text
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/pixijs-ticker
+70
View File
@@ -0,0 +1,70 @@
# Task: PixiJS v8 performance prototype for a virtual tabletop (VTT)
## Goal
Build a throwaway browser prototype that answers one question:
**Can PixiJS v8 render a VTT-sized scene smoothly on modest hardware?**
This is a measurement tool, not the product. Optimise for clear numbers, not polish.
## Before you start
- Use the PixiJS skills (`pixijs-*`) available to you. Load `pixijs-performance`,
`pixijs-scene-graphics`, `pixijs-scene-sprite`, `pixijs-scene-text` and
`pixijs-events` before writing code.
- PixiJS **v8 only**. If you are unsure whether an API is v7 or v8, check the
skills or docs. Do not rely on memory.
- If you want a pan/zoom library (e.g. pixi-viewport), first confirm it supports
PixiJS v8. If it does not, write minimal pan/zoom yourself.
## Stack
Vite + TypeScript + PixiJS v8. No UI framework: plain HTML controls on top of the canvas.
No backend, no multiplayer, no persistence.
The machine runs NixOS: do not install anything globally. Use devbox for the
toolchain: run `devbox init` in the project directory if there is no `devbox.json`,
`devbox add nodejs`, and run every npm command through `devbox run` or inside
`devbox shell`. Commit `devbox.json` and `devbox.lock`.
## Scene to build
1. **Map layer**: one large background map.
- Default: a procedurally generated map (no external assets needed).
- Also a file input to load a real local image.
- Selectable sizes: 2048, 4096, 8192, 16384 px square.
- Read the GPU's max texture size from the renderer. If the map is bigger,
split it into tiles. Show which path is used.
2. **Grid layer**: square grid overlay, cell size adjustable, toggle on/off.
3. **Token layer**: N circular tokens with a short text label (name + HP).
- N adjustable: 50 / 200 / 500 / 1000 / 2000.
- Tokens are draggable with the mouse and touch.
- A "chaos" toggle that moves all tokens every frame (worst case).
- An "HP churn" toggle that changes every label's text every frame.
4. **Drawing layer**: freehand pen tool.
- While drawing, the stroke must update live.
- When the stroke ends, make it cheap to keep around (follow the skills'
guidance: e.g. bake to texture, do not keep re-tessellating).
- A button to auto-generate 200 random finished strokes for stress testing.
5. **Pan and zoom**: mouse wheel + drag, pinch on touch.
## Measurements (always visible overlay)
- FPS and frame time (avg, and worst over the last 2 s).
- Renderer in use (WebGL or WebGPU). Add a URL param to force either one.
- Current settings (map size, N tokens, strokes count, toggles).
- A "Run benchmark" button that runs a fixed scripted scenario
(each combination of map size × token count, 5 s each, chaos on)
and outputs a results table you can copy (markdown).
## Acceptance criteria
- `npm install && npm run dev` works. `npm run dev -- --host` makes it reachable
from a tablet/phone on the LAN.
- Every feature above works and can be toggled from the controls.
- Benchmark produces a markdown table.
- Drawing a long freehand stroke stays responsive, and 200 finished strokes do
not noticeably lower FPS compared with 0 strokes. If not, report why.
## Deliverables
- The prototype source in a new directory.
- `README.md` with: how to run, how to test on mobile, your benchmark table from
your own machine, and a short **Findings** section: what was smooth, what was
slow, which PixiJS technique fixed each slow case, and anything that would
worry you for a real VTT.
## Out of scope (do not build)
Multiplayer, server, fog of war, lighting, saving/loading scenes, UI framework,
character sheets, dice, tests beyond the benchmark.
+161
View File
@@ -0,0 +1,161 @@
{
"version": 1,
"skills": {
"pixijs": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs/SKILL.md",
"computedHash": "d62ec20ca610aeaf3ab0b84b94e218c00cfab9ef422b06e7a3779ed5840caa10"
},
"pixijs-accessibility": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-accessibility/SKILL.md",
"computedHash": "0c5b1d794f1765586e101db129c69925cfdf4debd2d03baad4f27657dd6a46f9"
},
"pixijs-application": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-application/SKILL.md",
"computedHash": "2ff17b8605f67f41d12e2b4f12112c91befe5a096a0a4b29f25dc65f28c4777a"
},
"pixijs-assets": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-assets/SKILL.md",
"computedHash": "2c831499efc3b875a8f0b7d5264b4d7220e51cfeff65fc25e8ca046e74da10c3"
},
"pixijs-blend-modes": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-blend-modes/SKILL.md",
"computedHash": "9d754468113f0f94167c0ad525ebfa0525826b8aa94c6c626d6f87f43d9ee5fc"
},
"pixijs-color": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-color/SKILL.md",
"computedHash": "0901667635f6348bc2642db24dfc1486840f2c8ec9aa687f3b251c25ece55c2c"
},
"pixijs-core-concepts": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-core-concepts/SKILL.md",
"computedHash": "b575ae19070eafd7504dfbee2ffb0c746b8c781c6ecd4b5455d189ba76d4024f"
},
"pixijs-create": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-create/SKILL.md",
"computedHash": "9750f2ac93057dd01de7a245fb7ee484b2c587303ae6565d04ff6f13e611131e"
},
"pixijs-custom-rendering": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-custom-rendering/SKILL.md",
"computedHash": "816dd3b2420731de46e345b58250693823dc467dfaf7165488968308d090442b"
},
"pixijs-environments": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-environments/SKILL.md",
"computedHash": "fd27c1e0d08e291d09cce5d0b0da8b3648851911d960bed8706370c74833e191"
},
"pixijs-events": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-events/SKILL.md",
"computedHash": "ced45cf4dc47caa02a3fac9ec313490d90cc6de4c16248c1984316b67cf24976"
},
"pixijs-filters": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-filters/SKILL.md",
"computedHash": "a144f8d96f351c1836e1635709d862feb05a69c1c95a48f86242794a114d557a"
},
"pixijs-html-source": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-html-source/SKILL.md",
"computedHash": "93abd6be2e693a59673e9613db6ba2f99561ce1ac1eff2ff9684d6f61ac96cfa"
},
"pixijs-math": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-math/SKILL.md",
"computedHash": "54766d37e7332d1cf7d18eef3bfa812e646c8c263c57660f785c36e525cbe03b"
},
"pixijs-migration-v8": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-migration-v8/SKILL.md",
"computedHash": "470545518d4313224d6e57eae57142252f1745474cff7f0991458cd7d525ffd9"
},
"pixijs-performance": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-performance/SKILL.md",
"computedHash": "7da321f498f6f3595397266989898bcc2b02a2d46e154a88efce41766e312206"
},
"pixijs-scene-container": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-container/SKILL.md",
"computedHash": "c5cea512c0aff13d97938dd7fbc5955bc04513e367067455b7fa17583ee31c00"
},
"pixijs-scene-core-concepts": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-core-concepts/SKILL.md",
"computedHash": "95174d1751f715c2efe42ec940837e9974c85d08f0cc29b6bbc3c985f3745392"
},
"pixijs-scene-dom-container": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-dom-container/SKILL.md",
"computedHash": "00de3635d73b0f1679ec0d958e22446566e235d594bc7a087ee6434fe6360276"
},
"pixijs-scene-gif": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-gif/SKILL.md",
"computedHash": "cda195839c1d019a959de47b42aaad86b90ccac7c4b7f312a8d01f60ecc75b9d"
},
"pixijs-scene-graphics": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-graphics/SKILL.md",
"computedHash": "423872ff78d31b77d4486b16f355e9173011fa9f0a9614902b4bb2eca35f15c6"
},
"pixijs-scene-mesh": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-mesh/SKILL.md",
"computedHash": "bb536a8d47a4dc8ba066e5597dc40f0f6805fa2f949d44fb3ef0fef147bc9b7e"
},
"pixijs-scene-particle-container": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-particle-container/SKILL.md",
"computedHash": "837ee0a8aadc14bcbdba308cc36792ff11bbc41f5efe65939a4a4b7d448e089e"
},
"pixijs-scene-sprite": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-sprite/SKILL.md",
"computedHash": "b4b1a983f96a9c06fe62e4a3889938e060c924d94e3ebce4771b07cc56a9dbc4"
},
"pixijs-scene-text": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-scene-text/SKILL.md",
"computedHash": "2dd70ab1dcb026a6512b321b372a4f5030fdbb2e22bf7fcfc2e67a9ce304af75"
},
"pixijs-ticker": {
"source": "pixijs/pixijs-skills",
"sourceType": "github",
"skillPath": "skills/pixijs-ticker/SKILL.md",
"computedHash": "6b3eec30377b1ec013a858301d309f3138eb512e7af8e1e8d0c3a759c8223618"
}
}
}