opção
LarLar Skill Outros pixijs-application

pixijs-application

pixijs/pixijs pixijs/pixijs

Utilize esta habilidade ao criar e configurar um aplicativo PixiJS v8. Abrange as novas opções do Application() e do app.init() assíncrono (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, substituições por renderizador para webgl/webgpu/canvasOptions), acesso a app.stage/renderer/canvas/screen/domContainerRoot, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), criação personalizada de ApplicationPlugin via ExtensionType.Application, ciclo de vida de início/parada e app.destroy() com releaseGlobalResources. Gatilhos em: 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 tudo
50
Tempo atualizado 4 de Agosto de 2026

O Application é o wrapper de conveniência que contém um renderizador, um Container de estágio raiz, uma tela e os plug-ins Ticker/Resize. Na versão 8, o construtor não recebe argumentos; toda a configuração é passada para a chamada assíncrona de app.init(), que instancia o renderizador por meio de autoDetectRenderer.

Introdução rápida

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

Habilidades relacionadas: pixijs-core-concepts (renderizadores, pipeline de renderização), pixijs-ticker (detalhes do ciclo de renderização), pixijs-scene-container (trabalho com app.stage), pixijs-environments (configurações fora do navegador).

Padrões 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);// ... executar a cena; o ticker aciona app.render() automaticamente ...app.destroy(
  { removeView: true, releaseGlobalResources: true },
  { children: true, texture: true, textureSource: true },
);
  • new Application() aloca a instância, mas não cria nada. As opções passadas aqui são ignoradas, gerando um aviso de obsolescência do V8.
  • app.init(options) é assíncrono. Ele constrói o renderizador, conecta os plug-ins e deve ser concluído antes que você possa usar app.canvas, app.renderer ou app.screen.
  • O TickerPlugin chama app.render() a cada quadro assim que init for resolvido (a menos que autoStart: false).
  • app.destroy(rendererDestroyOptions, stageDestroyOptions) — o primeiro argumento é encaminhado para renderer.destroy(). Passe true ou { removeView: true } para remover o canvas do DOM. Adicione releaseGlobalResources: true para esvaziar os pools globais (lotes, caches de textura) ao desmontar e recriar um aplicativo na mesma aba; omitir isso é a causa comum de tremulação e texturas desatualizadas após uma reinicialização (consulte pixijs-performance).

Principais opções de inicialização

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 opção — view/canvas, fundo, preferência de renderizador (incluindo a forma de matriz), ticker, redimensionamento, culler, eventos, acessibilidade, sinalizadores de contexto WebGL/WebGPU, suavização Bézier de gráficos, GC e substituições por renderizador (webgl / webgpu / canvasOptions) — consulte references/application-options.md.

Propriedades do aplicativo

app.stage; // contêiner raiz; adicione todos os objetos de exibição aqui
app.renderer; // a instância do renderizador WebGL/WebGPU/Canvas
app.canvas; // o HTMLCanvasElement (insira-o no DOM por conta própria)
app.screen; // retângulo que descreve a área visível em pixels CSS
app.domContainerRoot; // HTMLDivElement que contém as sobreposições do DOMContainer

app.stage é um Container simples. Para detalhes sobre o grafo de cena (transformações, addChild, destroy), consulte pixijs-scene-container. Para operações no nível do renderizador (extract, generateTexture, sistemas personalizados), consulte pixijs-core-concepts e pixijs-custom-rendering. app.domContainerRoot é o

que o renderizador usa para hospedar sobreposições do DOMContainer; acrescente-o ao lado de app.canvas quando precisar de elementos DOM fixados aos nós da cena (consulte pixijs-scene-dom-container).

ResizePlugin

Defina resizeTo na inicialização (ou reatribua app.resizeTo posteriormente) para que o plugin escute o evento de redimensionamento e chame renderer.resize() com o tamanho do cliente do elemento de destino. Combine com autoDensity: true e resolution: window.devicePixelRatio para saída em alta resolução (DPI).

await app.init({ resizeTo: window });app.resizeTo = document.querySelector("#game-container") as HTMLElement;app.resize(); // redimensionamento imediato para o tamanho atual do alvo
app.queueResize(); // adia o redimensionamento para o próximo quadro da animação
app.cancelResize(); // cancela um `queueResize` pendente

O plug-in mantém a tela (canvas) alinhada ao alvo. app.screen e app.canvas.width/height são atualizados em resposta; leia-os após o redimensionamento para posicionar a interface do usuário.

  • app.resize() — redimensionamento síncrono imediato.
  • app.queueResize() — agrupa chamadas rápidas adiando-as para o próximo quadro; usado internamente pelo ouvinte window.resize para evitar trabalho redundante.
  • app.cancelResize() — cancela um redimensionamento na fila. Chame isso antes de desmontar seu próprio código de layout que acionou o queueResize.

Noções básicas sobre o Ticker

O TickerPlugin cria app.ticker e registra app.render() nele com prioridade UPDATE_PRIORITY.LOW. Controle o loop com app.start()/app.stop() e adicione callbacks com app.ticker.add / app.ticker.addOnce:

app.ticker.add((ticker) => {
  sprite.rotation += 0,01 * ticker.deltaTime;
});app.ticker.addOnce(() => {
 console.log("é executado uma vez no próximo quadro e, em seguida, se remove");
});app.stop(); // pausa o loop de renderização (por exemplo, ao ocultar a aba)
app.start(); // retoma

A função de retorno recebe a instância do Ticker; consulte ticker.deltaTime para obter um multiplicador independente da taxa de quadros (~1,0 a 60 fps), ticker.deltaMS para milissegundos reais ou ticker.FPS para a taxa de quadros atual. Consulte pixijs-ticker para saber mais sobre prioridades, limitação de FPS, onRender, tickers compartilhados versus privados e a mudança na assinatura da callback do V8.

Ciclo de renderização 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 impede que o TickerPlugin inicie o ticker automaticamente. Chame app.render() manualmente (ou app.renderer.render({ container: app.stage }) para obter o mesmo efeito). Se você ainda quiser que os callbacks registrados do ticker sejam acionados, chame app.ticker.update() dentro do seu loop antes de app.render().

CullerPlugin (opcional)

O CullerPlugin ignora a renderização de contêineres que ficam fora de app.renderer.screen. Ele não vem registrado por padrão; adicione-o antes de criar seu aplicativo:

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 contêiner é descartado quando seus limites saem da tela
world.cullableChildren = true; // padrão; defina como `false` para evitar a recursão nosfilhosconst tile = Sprite.from("tile.png");
tile.cullable = true;
world.addChild(tile);
app.stage.addChild(world);

Os contêineres não são eliminados a menos que a propriedade `cullable` esteja definida. Substitua a verificação de limites padrão por `container.cullArea = new Rectangle(x, y, w, h)` quando o cálculo dos limites dos filhos for dispendioso. O plug-in envolve o `app.render() ` para que `Culler.shared.cull(app.stage, app.renderer.screen) ` seja executado antes de cada quadro. Consulte ` pixijs-performance ` para saber quando o culling vale a pena.

Plug-ins de aplicativos personalizados

Estenda a classe `Application` registrando uma classe com `static init`, `static destroy` e `static extension = ExtensionType.Application`. Ambos os métodos são chamados com `this` vinculado à instância de `Application`, portanto, `this.renderer ` e `this.stage ` estão disponíveis.

import {
  Application,
  ExtensionType,
  extensions,
  type ApplicationOptions,
} from "pixi.js";class FpsOverlay {
 public static extension = ExtensionType.Application;  public static init(this: Application, options: Partial<ApplicationOptions>) {
    // é executado dentro de app.init() após a criação do renderizador
   // anexa propriedades/métodos a `this` para expô-los no aplicativo
  }  public static destroy(this: Application) {
    // é executado dentro de app.destroy() — desativa tudo o que você anexou
  }
}extensions.add(FpsOverlay);

Os plug-ins são inicializados na ordem de registro e destruídos na ordem inversa. Para adicionar opções tipadas ao seu plug-in, estenda PixiMixins.ApplicationOptions:

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

Os plug-ins integrados ResizePlugin, TickerPlugin e o opcional CullerPlugin utilizam todos esse mesmo contrato. Se você definir skipExtensionImports: true, registre você mesmo os plug-ins integrados de que precisar (extensions.add(ResizePlugin, TickerPlugin)).

Erros comuns

[CRÍTICO] Passar opções para o construtor

Errado:

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

Correto:

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

No V8, o construtor Application não aceita argumentos. As opções passadas a ele são ignoradas e geram um aviso de obsolescência; o renderizador só é criado dentro da chamada assíncrona de init().

[ALTO] Usar app.view em vez de app.canvas

Errado:

document.body.appendChild(app.view);

Correto:

document.body.appendChild(app.canvas);

app.view foi renomeado para app.canvas na versão 8. O getter antigo ainda funciona, mas gera um aviso de obsolescência.

[MÉDIO] Acessar app.canvas ou app.renderer antes que a inicialização seja concluída

Errado:

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

Correto:

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

app.renderer, app.canvas e app.screen só são preenchidos depois que a promessa de init() for resolvida. Acessá-los antes retorna undefined.

Referência da API

Ver no 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 os arquivos

0 arquivos

Instalar pixijs-application

Baixe e extraia os arquivos de habilidades para o diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

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

Copiar Copiar
Configuração rápida: Copie a pasta da habilidade para .claude/skills/. O Claude detectará e utilizará automaticamente a habilidade
Repositório pixijs/pixijs

Habilidades relacionadas

multica-creating-agents
Tempo atualizado 12 de Agosto de 2026
tilemaps
Tempo atualizado 4 de Agosto de 2026
v4-new-features
Tempo atualizado 4 de Agosto de 2026
agent-github-pr-manager
Tempo atualizado 3 de Agosto de 2026
OR