PixiJS Documentation

website·Indexed 39 days ago

https://pixijs.com

A fast, lightweight 2D library for the web that works across all devices. The documentation covers core architecture, the scene graph, render loops, asset management, and performance optimization. It includes detailed guides on using WebGL and WebGPU renderers, managing textures, and a migration guide for transitioning from v7 to v8.

Tokens
96K
Snippets
581
Records
666
Agent score
74%

What's inside PixiJS

  1. Overview of SplitText and SplitBitmapText

    The SplitText and SplitBitmapText classes allow developers to break a string into individual lines, words, and characters, where each segment becomes its own display object. This enables per-segment animations and complex typography effects.

    • SplitText: Based on Text, best for richly styled text.
    • SplitBitmapText: Based on BitmapText, best for high-performance dynamic text.

    Note: These features are experimental and may evolve. Splitting text removes browser or font kerning, which may cause slight spacing differences compared to standard text.

  2. Overview of PixiJS Major Components

    PixiJS is composed of several core systems that manage the rendering and lifecycle of a graphical application:

    • Renderer: The core system that draws the scene graph to the screen. It automatically selects between WebGPU, WebGL, or Canvas.
    • Container: The base object for the scene graph, allowing for a tree structure of renderable objects (sprites, graphics, text).
    • Assets: A system for asynchronously loading resources like images and audio.
    • Ticker: Provides periodic callbacks (usually once per frame) for game update logic.
    • Application: A convenience wrapper that bundles the Loader, Ticker, and Renderer into one object for rapid prototyping.
    • Events: Handles pointer-based interactions such as clicks and hover events.
    • Accessibility: Tools for integrating keyboard and screen-reader support.
    • Filters: Supports custom shaders and effects applied to renderable objects.
  3. Overview of PixiJS Core Ecosystem Libraries

    PixiJS is a 2D rendering engine that supports WebGL and WebGPU. To extend its functionality, a set of core ecosystem libraries are available for specific tasks:

    • DevTools: Browser extension for real-time performance insights, rendering hierarchies, and texture management.
    • React Integration: Bindings to manage PixiJS components as React elements (Requires React 19+).
    • Layout: Provides flexbox-style layouting powered by the Yoga engine, allowing CSS-like rules for positioning, alignment, and sizing. Supports objectFit, objectPosition, and overflow scrolling.
    • Spine Integration: Integration for skeletal-based animations using Spine.
    • Filters: High-performance visual effects such as blur, glow, and color adjustments.
    • Sound: WebAudio API playback library with filter support.
    • UI: Pre-built interactive components including Buttons, Sliders, Progress bars, Lists, Scrollbox, Radio Groups, Checkboxes, and Switches.
    • AssetPack: Tool for organizing, packaging, and efficiently loading assets.
  4. Overview of PixiJS Render Layers

    RenderLayers allow you to control the draw order of objects independently of their logical parent-child relationships in the scene graph. This is particularly useful for:

    • Ensuring UI elements (like health bars or score counters) always appear on top of the world.
    • Highlighting specific objects by placing them in a foreground layer while pushing other elements to a background layer.

    Key behaviors include:

    • Logical Parenting: Objects maintain transformations (position, scale, rotation) from their logical parent even when attached to a RenderLayer.
    • Dynamic Sorting: Within a layer, objects can still be reordered using zIndex and sortChildren.
    • Explicit Management: Objects must be manually re-attached to a layer if they are removed and then re-added to the scene graph.
  5. Manage spatial boundaries with the Bounds class

    The Bounds class provides utilities for calculating, expanding, and manipulating rectangular bounding areas. It is commonly used for hit testing, viewport clipping, and calculating the total area occupied by multiple objects.
  6. Use TextStyle to decorate PixiJS Text objects

    The TextStyle class defines the visual appearance of Text objects. A single TextStyle instance can be shared across multiple Text objects; updating a property on the shared style instance will automatically update all associated text objects. It supports rich formatting including gradients, patterns, drop shadows, and strokes.
    // Create a shared style
    const richStyle = new TextStyle({
        fontFamily: 'Arial',
        fontSize: 32,
        fill: 'white',
        stroke: {
            color: '#4a1850',
            width: 5
        },
        dropShadow: {
            color: '#000000',
            blur: 4,
            distance: 6,
            angle: Math.PI / 6
        },
        wordWrap: true,
        wordWrapWidth: 440,
        lineHeight: 40,
        align: 'center'
    });
    
    // Apply to multiple objects
    const text1 = new Text({ text: 'Hello', style: richStyle });
    const text2 = new Text({ text: 'World', style: richStyle });
    
    // Dynamic update affects both text1 and text2
    richStyle.fontSize = 48;
    richStyle.fill = 0x00ff00;
  7. Load and manage assets using the Assets class

    The Assets singleton manages the loading, caching, and unloading of resources. It supports various asset types including textures, video, sprite sheets, bitmap fonts, web fonts, JSON, and compressed textures. Assets are automatically cached to prevent duplicate loads.
    import { Assets } from 'pixi.js';
    
    // Load a single asset
    const texture = await Assets.load('images/sprite.png');
    
    // Load multiple assets
    const assets = await Assets.load([
        'images/bg.png',
        'images/character.png'
    ]);
    
    // Load using aliases and multiple format fallbacks
    await Assets.load({ alias: 'hero', src: 'images/hero.{webp,png}' });
    
    // Background loading (non-blocking)
    Assets.backgroundLoad(['images/level1.json', 'images/level2.json']);
    
    // Load a bundle defined in the manifest
    const levelAssets = await Assets.loadBundle('gameAssets');
    
    // Unload assets to free memory
    await Assets.unload('hero');
    await Assets.unloadBundle('levelOne');
  8. Use ParticleContainer for high-performance particle rendering

    The ParticleContainer is a specialized container optimized to render thousands of particles at high speed. To achieve this performance, it imposes several constraints: particles are lightweight objects that only support basic properties (position, scale, rotation, and color) and cannot have children, filters, or masks. All particles in a ParticleContainer must share the same base texture (e.g., using a sprite sheet).

    Performance is further tuned by defining which properties are 'static' (updated only on add/remove or when update() is called) and which are 'dynamic' (updated every frame). By default, only position is dynamic.

    import { ParticleContainer, Particle } from 'pixi.js';
    
    const container = new ParticleContainer();
    
    for (let i = 0; i < 100; ++i)
    {
        let particle = new Particle(texture);
        container.addParticle(particle);
    }
  9. Use the Ellipse class for graphics and hit areas

    The Ellipse class defines an ellipse based on its center coordinates (x, y) and half-dimensions (halfWidth, halfHeight). It is commonly used for drawing graphics or specifying a hitArea for containers. The total width is halfWidth * 2 and the total height is halfHeight * 2.
    // Basic ellipse creation
    const ellipse = new Ellipse(100, 100, 20, 10);
    
    // Use as a hit area
    container.hitArea = new Ellipse(0, 0, 50, 25);
    
    // Check point containment
    const isInside = ellipse.contains(mouseX, mouseY);
    
    // Get bounding box
    const bounds = ellipse.getBounds();
  10. Choose the right text system for PixiJS

    PixiJS provides three different text rendering systems depending on the requirements for fidelity, performance, and styling:

    1. Text: High-quality raster text using the browser's native engine. Best for detailed font control and occasional updates where fidelity is prioritized over speed.
    2. BitmapText: GPU-optimized glyph rendering using pre-baked bitmap fonts. Best for high-performance needs, such as rendering thousands of dynamic labels.
    3. HTMLText: Renders HTML markup (e.g., <b>, <i>, <span>) within the scene. Best for complex document-like layouts, emojis, and RTL text.
  11. Understand the PixiJS Texture Lifecycle

    The PixiJS texture system separates raw pixel data from the view used for rendering.

    • TextureSource: Represents the actual pixel source (e.g., an image, canvas, or video) and handles GPU uploads.
    • Texture: A lightweight view into a TextureSource. It contains metadata like sub-rectangles, trims, and UV mapping.

    Multiple Texture instances can share a single TextureSource, which is the fundamental mechanism for sprite sheets.

  12. Use GraphicsContext for shared geometry

    The GraphicsContext class stores drawing instructions. By sharing a single GraphicsContext instance across multiple Graphics objects, PixiJS avoids repeating the expensive process of converting instructions into GPU-ready geometry, similar to how multiple sprites share a single texture.