pixijs-application
pixijs/pixijs
Utilisez cette compétence lors de la création et de la configuration d’une application PixiJS v8. Couvre les nouvelles options de Application() et de app.init() asynchrone (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, les options webgl/webgpu/canvasOptions pour les remplacements par rendu), l’accès à app.stage/renderer/canvas/screen/domContainerRoot, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), création d’un ApplicationPlugin personnalisé via ExtensionType.Application, cycle de vie start/stop, et app.destroy() avec releaseGlobalResources. Déclencheurs sur : 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
...Développer toutL'application est une couche d'abstraction qui gère un moteur de rendu, un conteneur « root stage », un canevas et les plugins Ticker/Resize. Dans la version 8, le constructeur ne prend aucun argument ; toute la configuration est transmise à l'appel asynchrone app.init(), qui instancie le moteur de rendu via autoDetectRenderer.
Démarrage rapide
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);
Compétences associées : pixijs-core-concepts (renderers, pipeline de rendu), pixijs-ticker (détails de la boucle de rendu), pixijs-scene-container (utilisation de app.stage), pixijs-environments (configurations hors navigateur).
Modèles de base
Cycle de vie : 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);// ... exécuter la scène, le ticker déclenche automatiquement app.render() ...app.destroy(
{ removeView: true, releaseGlobalResources: true },
{ children: true, texture: true, textureSource: true },
);
new Application()alloue l'instance mais ne crée rien. Les options passées ici sont ignorées et génèrent un avertissement de dépréciation V8.app.init(options)est asynchrone. Il construit le moteur de rendu, connecte les plugins et doit s’exécuter entièrement avant que vous puissiez utiliserapp.canvas,app.rendererouapp.screen.- Le TickerPlugin appelle
app.render()à chaque image une fois que init s'est exécuté (sauf siautoStart: false). app.destroy(rendererDestroyOptions, stageDestroyOptions)— le premier argument est transmis àrenderer.destroy(). Passeztrueou{ removeView: true }pour supprimer le canvas du DOM. AjoutezreleaseGlobalResources: truepour vider les pools globaux (lots, caches de textures) lors de la destruction et de la recréation d’une application dans le même onglet ; omettre cette option est la cause habituelle de scintillements et de textures obsolètes après une réinitialisation (voirpixijs-performance).
Options d’initialisation clés
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,
});
Pour chaque option — vue/canvas, arrière-plan, préférence de rendu (y compris sous forme de tableau), compteur, redimensionnement, culler, événements, accessibilité, indicateurs de contexte WebGL/WebGPU, la fluidité des courbes de Bézier, le GC et les remplacements par rendu (webgl / webgpu / canvasOptions) — voir references/application-options.md.
Propriétés de l’application
app.stage; // conteneur racine ; ajoutez tous les objets d’affichage ici
app.renderer; // l’instance du moteur de rendu WebGL/WebGPU/Canvas
app.canvas; // l’élément HTMLCanvasElement (à insérer vous-même dans le DOM)
app.screen; // rectangle décrivant la zone visible en pixels CSS
app.domContainerRoot; // élément HTMLDivElement contenant les superpositions DOMContainer
Définissez Le plugin maintient le canvas aligné sur la cible. Le TickerPlugin crée La fonction de rappel reçoit l’instance La valeur ` Le CullerPlugin ignore le rendu des conteneurs situés en dehors de Les conteneurs ne sont pas cullés à moins que Étendez Les plugins s’initialisent dans l’ordre d’enregistrement et se désactivent dans l’ordre inverse. Pour ajouter des options typées à votre plugin, étendez Les plugins intégrés Incorrect : Correct : Dans V8, le constructeur Incorrect : Correct : Incorrect : Correct : Related skills: 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 ( Set The plugin keeps the canvas matched to the target. The TickerPlugin creates The callback receives the The CullerPlugin skips rendering containers that fall outside Containers are not culled unless Extend Plugins initialize in registration order and destroy in reverse. To add typed options for your plugin, extend The built-in Wrong: Correct: In v8 the Wrong: Correct: Wrong: Correct:app.stage est un conteneur simple. Pour plus de détails sur le graphe de scène (transformations, addChild, destroy), consultez pixijs-scene-container. Pour les opérations au niveau du moteur de rendu (extract, generateTexture, systèmes personnalisés), consultez pixijs-core-concepts et pixijs-custom-rendering. app.domContainerRoot est le DOMContainer; ajoutez-le à côté de app.canvas lorsque vous avez besoin d’éléments DOM épinglés à des nœuds de scène (voir pixijs-scene-dom-container).
ResizePlugin
resizeTo lors de l’initialisation (ou réattribuez app.resizeTo ultérieurement) pour que le plugin écoute l’événement resize et appelle renderer.resize() avec la taille client de l’élément cible. À combiner avec autoDensity: true et resolution: window.devicePixelRatio pour une sortie haute résolution (DPI).await app.init({ resizeTo: window });app.resizeTo = document.querySelector("#game-container") as HTMLElement;app.resize(); // redimensionnement immédiat à la taille actuelle de la cible
app.queueResize(); // reporte le redimensionnement à la prochaine image d’animation
app.cancelResize(); // annule une opération queueResize en attente
Les propriétés app.screen et app.canvas.width/height sont mises à jour en conséquence ; lisez-les après le redimensionnement pour positionner l’interface utilisateur.
app.resize() — redimensionnement synchrone immédiat.app.queueResize() — regroupe les appels rapides en les reportant à l’image suivante ; utilisé en interne par l’écouteur window.resize pour éviter les opérations redondantes.app.cancelResize() — annule un redimensionnement mis en file d’attente. Appelez cette méthode avant de désactiver votre propre code de mise en page qui a déclenché queueResize.Principes de base du Ticker
app.ticker et y enregistre app.render() avec la priorité UPDATE_PRIORITY.LOW. Contrôlez la boucle avec app.start()/app.stop() et ajoutez des callbacks avec app.ticker.add / app.ticker.addOnce:app.ticker.add((ticker) => {
sprite.rotation += 0,01 * ticker.deltaTime;
});app.ticker.addOnce(() => {
console.log("s'exécute une fois à la prochaine image, puis se supprime") ;
});app.stop(); // met la boucle de rendu en pause (par ex. onglet masqué)
app.start(); // reprend
Ticker; consultez ticker.deltaTime pour obtenir un multiplicateur indépendant de la fréquence d’images (~1,0 à 60 images par seconde), ticker.deltaMS pour les millisecondes réelles, ou ticker.FPS pour la fréquence d’images actuelle. Consultez pixijs-ticker pour en savoir plus sur les priorités, la limitation du FPS, onRender, les tickers partagés vs privés, et le changement de signature de la fonction de rappel v8.Boucle de rendu manuelle
await app.init({ autoStart: false, width: 800, height: 600 });
document.body.appendChild(app.canvas);function frame() {
updateScene();
app.render();
requestAnimationFrame(frame);
}
frame();
autoStart: false ` empêche le TickerPlugin de démarrer automatiquement le ticker. Appelez vous-même app.render() (ou app.renderer.render({ container: app.stage }) pour obtenir le même effet). Si vous souhaitez tout de même que les callbacks du ticker enregistrés se déclenchent, appelez app.ticker.update() à l'intérieur de votre boucle avant app.render().CullerPlugin (à activer manuellement)
app.renderer.screen. Il n’est pas enregistré par défaut ; ajoutez-le avant de créer votre application :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; // ce conteneur est masqué lorsque ses limites sortent de l'écran
world.cullableChildren = true; // par défaut ; définir `false` pour éviter la récursivité surles enfantsconst tile = Sprite.from("tile.png");
tile.cullable = true;
world.addChild(tile);
app.stage.addChild(world);
la propriété `cullable` ne soit définie. Remplacez la vérification des limites par défaut par ` container.cullArea = new Rectangle(x, y, w, h)` lorsque le calcul des limites des enfants est trop coûteux. Le plugin encapsule la méthode ` app.render() ` afin que `Culler.shared.cull(app.stage, app.renderer.screen) ` s'exécute avant chaque image. Consultez pixijs-performance pour savoir dans quels cas le culling est bénéfique.Plugins d’application personnalisés
l’interface Application en enregistrant une classe dotée des méthodes statiques init, destroy et extension = ExtensionType.Application. Ces deux méthodes sont appelées avec `this` lié à l’instance Application, ce qui rend `this.renderer ` et `this.stage ` 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>) {
// s'exécute à l'intérieur de app.init() après la création du rendu
// associe des propriétés/méthodes à `this` pour les exposer dans l’application
} public static destroy(this: Application) {
// s’exécute à l’intérieur de app.destroy() — supprime tout ce que vous avez associé
}
}extensions.add(FpsOverlay);
PixiMixins.ApplicationOptions:declare global {
namespace PixiMixins {
interface ApplicationOptions {
fpsOverlay?: { visible?: boolean };
}
}
}await app.init({ fpsOverlay: { visible: true } });
ResizePlugin, TickerPlugin et CullerPlugin (en option) utilisent tous ce même contrat. Si vous définissez skipExtensionImports: true, enregistrez vous-même les plugins intégrés dont vous avez besoin (extensions.add(ResizePlugin, TickerPlugin)).Erreurs courantes
[CRITIQUE] Transmission d’options au constructeur
const app = new Application({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
Application ne prend aucun argument. Les options qui y sont transmises sont ignorées et génèrent un avertissement de dépréciation ; le moteur de rendu n'est créé qu'à l'intérieur de l'appel asynchrone à init().[HIGH] Utilisation de app.view au lieu de app.canvas
document.body.appendChild(app.view);
document.body.appendChild(app.canvas);
app.view a été renommé en app.canvas dans la version 8. L'ancien getter fonctionne toujours, mais génère un avertissement de dépréciation.[MOYEN] Accès à app.canvas ou app.renderer avant la résolution de init
const app = new Application();
document.body.appendChild(app.canvas);
app.init({ width: 800, height: 600 });
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
app.renderer, app.canvas et app.screen ne sont initialisés qu’une fois que la promesse init() est résolue. Les accéder plus tôt renvoie « undefined ».Référence de l'API
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);
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.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,
});
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
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
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
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
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)
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);
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
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);
PixiMixins.ApplicationOptions:declare global {
namespace PixiMixins {
interface ApplicationOptions {
fpsOverlay?: { visible?: boolean };
}
}
}await app.init({ fpsOverlay: { visible: true } });
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
const app = new Application({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
const app = new Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
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
document.body.appendChild(app.view);
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
const app = new Application();
document.body.appendChild(app.canvas);
app.init({ width: 800, height: 600 });
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
Tous les fichiers
0 fichiersInstaller pixijs-application
Téléchargez et décompressez les fichiers de compétences dans votre répertoire .claude/skills/.
Télécharger le ZIPClonez le dépôt et copiez les fichiers de compétence dans votre projet.
git clone https://github.com/pixijs/pixijs/tree/dev/skills/pixijs-application # Copy the skill folder to .claude/skills/ or .codex/skills/
Copier
Compétences similaires





Maison
