opción
HogarHogar Skill Otros pixijs-application

pixijs-application

pixijs/pixijs pixijs/pixijs

Utiliza esta habilidad al crear y configurar una aplicación PixiJS v8. Abarca las nuevas opciones de Application() y app.init() asíncrono (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, opciones de WebGL/WebGPU/canvas con anulaciones específicas por renderizador), acceso a app.stage/renderer/canvas/screen/domContainerRoot, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), creación personalizada de ApplicationPlugin mediante ExtensionType.Application, ciclo de vida de inicio/parada y app.destroy() con releaseGlobalResources. Desencadenadores en: Application, app.init, app.stage, app.renderer, app.canvas, app.screen, app.domContainerRoot, ApplicationOptions, ApplicationPlugin, ExtensionType.Application, resizeTo, preference, autoStart, sharedTicker, useBackBuffer, powerPreference, skipExtensionImports, preferWebGLVersion, preserveDrawingBuffer, cullable, CullerPlugin, app.start, app.stop, app.destroy, rele

...Expandir todo
50
Tiempo actualizado 4 de agosto de 2026

La aplicación es el envoltorio de conveniencia que contiene un renderizador, un contenedor de etapa raíz, un lienzo y los complementos Ticker y Resize. En la versión 8, el constructor no admite argumentos; toda la configuración se pasa a la llamada asíncrona app.init(), que instancia el renderizador mediante autoDetectRenderer.

Inicio rápido

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);

Conocimientos relacionados: pixijs-core-concepts (renderizadores, canal de renderizado), pixijs-ticker (detalles del bucle de renderizado), pixijs-scene-container (cómo trabajar con app.stage), pixijs-environments (configuraciones fuera del navegador).

Patrones básicos

Ciclo de vida: construct, init, render, destroy

import { Application } from "pixi.js";const app = new Application();await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);// ... ejecutar la escena; el ticker activa app.render() automáticamente ...app.destroy(
  { removeView: true, releaseGlobalResources: true },
  { children: true, texture: true, textureSource: true },
);
  • new Application() asigna la instancia, pero no crea nada. Las opciones pasadas aquí se ignoran y se muestra una advertencia de obsolescencia de V8.
  • app.init(options) es asíncrono. Crea el renderizador, configura los complementos y debe completarse antes de que puedas utilizar app.canvas, app.renderer o app.screen.
  • El TickerPlugin llama a app.render() en cada fotograma una vez que se resuelve init (a menos que autoStart: false).
  • app.destroy(rendererDestroyOptions, stageDestroyOptions): el primer argumento se reenvía a renderer.destroy(). Pasa true o { removeView: true } para eliminar el lienzo del DOM. Añade releaseGlobalResources: true para liberar los recursos globales (lotes, cachés de texturas) al desmontar y volver a crear una aplicación en la misma pestaña; omitirlo suele ser la causa habitual del parpadeo y de las texturas obsoletas tras una reinicialización (véase pixijs-performance).

Opciones clave de inicialización

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,
});

Para cada opción — vista/lienzo, fondo, preferencia del renderizador (incluida la forma de matriz), contador, redimensionamiento, filtro de objetos, eventos, accesibilidad, indicadores de contexto de WebGL/WebGPU, suavidad de Bézier de los gráficos, GC y anulaciones por renderizador (webgl / webgpu / canvasOptions)—, consulta references/application-options.md.

Propiedades de la aplicación

app.stage; // contenedor raíz; añade aquí todos los objetos de visualización
app.renderer; // la instancia del renderizador WebGL/WebGPU/Canvas
app.canvas; // el HTMLCanvasElement (insértalo tú mismo en el DOM)
app.screen; // rectángulo que describe el área visible en píxeles CSS
app.domContainerRoot; // HTMLDivElement que contiene las superposiciones de DOMContainer

app.stage es un contenedor simple. Para obtener detalles sobre el grafo de escena (transformaciones, addChild, destroy), consulta pixijs-scene-container. Para operaciones a nivel del renderizador (extract, generateTexture, sistemas personalizados), consulta pixijs-core-concepts y pixijs-custom-rendering. app.domContainerRoot es el

que utiliza el renderizador para alojar las superposiciones de DOMContainer; añádelo junto a app.canvas cuando necesites elementos DOM anclados a nodos de la escena (consulta pixijs-scene-dom-container).

ResizePlugin

Establece resizeTo en la inicialización (o reasigna app.resizeTo más tarde) para que el complemento escuche el evento de cambio de tamaño y llame a renderer.resize() con el tamaño de cliente del elemento de destino. Combínalo con autoDensity: true y resolution: window.devicePixelRatio para obtener una salida de alto DPI.

await app.init({ resizeTo: window });app.resizeTo = document.querySelector("#game-container") as HTMLElement;app.resize(); // cambio de tamaño inmediato al tamaño actual del elemento de destino
app.queueResize(); // aplaza el cambio de tamaño hasta el siguiente fotograma de animación
app.cancelResize(); // cancela una llamada a queueResize pendiente

El complemento mantiene el lienzo alineado con el objetivo. app.screen y app.canvas.width/height se actualizan en consecuencia; léelos tras el redimensionamiento para colocar la interfaz de usuario.

  • app.resize() — redimensionamiento sincrónico inmediato.
  • app.queueResize() — agrupa las llamadas rápidas aplazándolas al siguiente fotograma; lo utiliza internamente el oyente window.resize para evitar trabajo redundante.
  • app.cancelResize() — cancela un cambio de tamaño en cola. Llama a esta función antes de desmontar tu propio código de diseño que haya activado queueResize.

Conceptos básicos de Ticker

El TickerPlugin crea app.ticker y registra app.render() en él con la prioridad UPDATE_PRIORITY.LOW. Controla el bucle con app.start()/app.stop() y añade callbacks con app.ticker.add / app.ticker.addOnce:

app.ticker.add((ticker) => {
  sprite.rotation += 0.01 * ticker.deltaTime;
});app.ticker.addOnce(() => {
 console.log("se ejecuta una vez en el siguiente fotograma y, a continuación, se elimina");
});app.stop(); // pausa el bucle de renderizado (p. ej., pestaña oculta)
app.start(); // reanuda

La función de devolución de llamada recibe la instancia de Ticker; consulta ticker.deltaTime para obtener un multiplicador independiente de la frecuencia de fotogramas (~1,0 a 60 fps), ticker.deltaMS para obtener milisegundos reales, o ticker.FPS para conocer la frecuencia de fotogramas actual. Consulta pixijs-ticker para obtener información sobre prioridades, limitación de FPS, onRender, tickers compartidos frente a privados y el cambio en la firma de la función de llamada de V8.

Bucle de renderizado manual

await app.init({ autoStart: false, width: 800, height: 600 });
document.body.appendChild(app.canvas);function frame() {
  updateScene();
  app.render();
 requestAnimationFrame(frame);
}
frame();

autoStart: false impide que TickerPlugin inicie el ticker automáticamente. Llama tú mismo a app.render() (o a app.renderer.render({ container: app.stage }) para obtener el mismo efecto). Si aún así quieres que se ejecuten las funciones de devolución de llamada registradas del ticker, llama a app.ticker.update() dentro de tu bucle antes de app.render().

CullerPlugin (opcional)

El CullerPlugin omite la representación de los contenedores que quedan fuera de app.renderer.screen. No está registrado por defecto; añádelo antes de crear tu aplicación:

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; // este contenedor se omite cuando sus límites salen de la pantalla
world.cullableChildren = true; // por defecto; establece `false` para evitar la recursividad enlos hijosconst tile = Sprite.from("tile.png");
tile.cullable = true;
world.addChild(tile);
app.stage.addChild(world);

Los contenedores no se eliminan a menos que se establezca `cullable`. Sobrescribe la comprobación de límites predeterminada con `container.cullArea = new Rectangle(x, y, w, h)` cuando el cálculo de los límites de los elementos hijos resulte muy costoso. El complemento envuelve app.render(), de modo que Culler.shared.cull(app.stage, app.renderer.screen) se ejecuta antes de cada fotograma. Consulta pixijs-performance para saber cuándo merece la pena aplicar el culling.

Complementos de aplicación personalizados

Amplía la clase `Application` registrando una clase con `static init`, `static destroy` y `static extension = ExtensionType.Application`. Ambos métodos se invocan con `this` vinculado a la instancia de `Application`, por lo que `this.renderer ` y `this.stage ` están disponibles.

import {
  Application,
  ExtensionType,
  extensions,
  type ApplicationOptions,
} from "pixi.js";class FpsOverlay {
 public static extension = ExtensionType.Application;  public static init(this: Application, options: Partial<ApplicationOptions>) {
    // se ejecuta dentro de app.init() después de crear el renderizador
   // adjunta propiedades/métodos a `this` para exponerlos en la aplicación
  }  public static destroy(this: Application) {
    // se ejecuta dentro de app.destroy() — desmonta todo lo que hayas adjuntado
  }
}extensions.add(FpsOverlay);

Los complementos se inicializan en el orden de registro y se destruyen en orden inverso. Para añadir opciones tipadas a tu complemento, extiende PixiMixins.ApplicationOptions:

declare global {
  namespace PixiMixins {
    interface ApplicationOptions {
      fpsOverlay?: { visible?: boolean };
    }
  }
}await app.init({ fpsOverlay: { visible: true } });

Los complementos integrados ResizePlugin, TickerPlugin y CullerPlugin (opcional) utilizan todos este mismo contrato. Si estableces skipExtensionImports: true, registra tú mismo los complementos integrados que necesites (extensions.add(ResizePlugin, TickerPlugin)).

Errores comunes

[CRÍTICO] Pasar opciones al constructor

Incorrecto:

const app = new Application({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

Correcto:

const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

En V8, el constructor de Application no admite argumentos. Las opciones que se le pasen se ignoran y generan una advertencia de obsolescencia; el renderizador solo se crea dentro de la llamada asíncrona a init().

[ALTO] Usar app.view en lugar de app.canvas

Incorrecto:

document.body.appendChild(app.view);

Correcto:

document.body.appendChild(app.canvas);

app.view pasó a llamarse app.canvas en la versión 8. El antiguo getter sigue funcionando, pero genera una advertencia de obsolescencia.

[MEDIO] Acceder a app.canvas o app.renderer antes de que se resuelva init

Incorrecto:

const app = new Application();
document.body.appendChild(app.canvas);
app.init({ width: 800, height: 600 });

Correcto:

const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

app.renderer, app.canvas y app.screen solo se rellenan una vez que se resuelve la promesa de init(). Si se accede a ellos antes, devuelven undefined.

Referencia de la API

Ver en GitHub

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

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

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

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.

Application properties

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.

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:

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

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:

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 childrenconst 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.

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:

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:

const app = new Application({ width: 800, height: 600 });
document.body.appendChild(app.canvas);

Correct:

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:

document.body.appendChild(app.view);

Correct:

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:

const app = new Application();
document.body.appendChild(app.canvas);
app.init({ width: 800, height: 600 });

Correct:

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

Todos los archivos

0 archivos

Instalar pixijs-application

Descarga y descomprime los archivos de las habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

git clone https://github.com/pixijs/pixijs/tree/dev/skills/pixijs-application # Copy the skill folder to .claude/skills/ or .codex/skills/

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/. Claude la detectará automáticamente y la utilizará.
Repositorio pixijs/pixijs

Habilidades relacionadas

multica-creating-agents
Tiempo actualizado 12 de agosto de 2026
tilemaps
Tiempo actualizado 4 de agosto de 2026
v4-new-features
Tiempo actualizado 4 de agosto de 2026
agent-github-pr-manager
Tiempo actualizado 3 de agosto de 2026
OR