pixijs-application
pixijs/pixijs
Используйте этот навык при создании и настройке приложения PixiJS v8. Рассматриваются новые параметры метода Application() и асинхронного app.init() (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, переопределения параметров webgl/webgpu/canvasOptions для каждого рендерера), доступ к app.stage/renderer/canvas/screen/domContainerRoot, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), создание пользовательского ApplicationPlugin с помощью ExtensionType.Application, жизненный цикл start/stop и app.destroy() с releaseGlobalResources. Триггеры для: 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
...Расширить всеПриложение представляет собой удобный «обёртку», которая управляет рендерером, корневым контейнером сцены, холстом и плагинами Ticker/Resize. В версии v8 конструктор не принимает аргументов; вся конфигурация передаётся в асинхронный вызов app.init(), который создаёт экземпляр рендерера с помощью autoDetectRenderer.
Быстрый старт
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 (рендереры, конвейер рендеринга), pixijs-ticker (подробности цикла рендеринга), pixijs-scene-container (работа с app.stage), pixijs-environments (настройки вне браузера).
Основные шаблоны
Жизненный цикл: 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);// ... запуск сцены, тикер автоматически запускает app.render() ...app.destroy(
{ removeView: true, releaseGlobalResources: true },
{ children: true, texture: true, textureSource: true },
);
new Application()выделяет экземпляр, но ничего не создаёт. Переданные здесь параметры игнорируются с предупреждением о прекращении поддержки в V8.app.init(options)является асинхронным. Он создаёт рендер, подключает плагины и должен завершиться, прежде чем вы сможете использоватьapp.canvas,app.rendererилиapp.screen.- TickerPlugin вызывает
app.render()в каждом кадре после завершения инициализации (еслиautoStart не установлен в false). app.destroy(rendererDestroyOptions, stageDestroyOptions)— первый аргумент передаётся вrenderer.destroy(). Передайтеtrueили{ removeView: true }, чтобы удалить холст из DOM. ДобавьтеreleaseGlobalResources: true, чтобы освободить глобальные пулы (пакеты, кэши текстур) при сносе и повторном создании приложения в той же вкладке; его отсутствие — обычная причина мерцания и устаревших текстур после повторной инициализации (см.pixijs-performance).
Ключевые параметры инициализации
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,
});
Для каждого параметра — view/canvas, background, настройки рендерера (включая массив), тикер, изменение размера, куллер, события, доступность, флаги контекста WebGL/WebGPU, сглаживание кривых Безье, GC и переопределения для каждого рендерера (webgl / webgpu / canvasOptions) — см. references/application-options.md.
Свойства приложения
app.stage; // корневой контейнер; добавляйте сюда все объекты отображения
app.renderer; // экземпляр рендерера WebGL/WebGPU/Canvas
app.canvas; // HTMLCanvasElement (вставьте его в DOM самостоятельно)
app.screen; // прямоугольник, описывающий видимую область в пикселях CSS
app.domContainerRoot; // HTMLDivElement, содержащий наложения DOMContainer
Установите Плагин поддерживает соответствие холста целевому объекту. Значения TickerPlugin создаёт Обратный вызов получает экземпляр Параметр ` CullerPlugin пропускает рендеринг контейнеров, выходящих за пределы Контейнеры не подвергаются отсечению, если не установлен Расширьте Плагины инициализируются в порядке регистрации и уничтожаются в обратном порядке. Чтобы добавить типизированные опции для вашего плагина, расширьте Встроенные плагины Неправильно: Правильно: В V8 конструктор Неправильно: Правильно: В версии v8 Неправильно: Правильно: 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 — это простой контейнер. Подробности о графе сцены (трансформации, addChild, destroy) см. в pixijs-scene-container. Операции на уровне рендерера (extract, generateTexture, пользовательские системы) описаны в pixijs-core-concepts и pixijs-custom-rendering. app.domContainerRoot — это DOMContainer; добавьте его рядом с app.canvas, если вам нужно привязать элементы DOM к узлам сцены (см. pixijs-scene-dom-container).
ResizePlugin
resizeTo при инициализации (или переназначьте app.resizeTo позже), чтобы плагин отслеживал событие resize и вызывал renderer.resize() с клиентским размером целевого элемента. Используйте вместе с autoDensity: true и resolution: window.devicePixelRatio для вывода с высоким DPI.await app.init({ resizeTo: window });app.resizeTo = document.querySelector("#game-container") as HTMLElement;app.resize(); // немедленное изменение размера до текущего размера целевого элемента
app.queueResize(); // отложить изменение размера до следующего кадра анимации
app.cancelResize(); // отменить ожидающий вызов queueResize
app.screen и app.canvas.width/height обновляются в соответствии с этим; считывайте их после изменения размера для размещения элементов пользовательского интерфейса.
app.resize() — немедленное синхронное изменение размера.app.queueResize() — объединяет быстрые вызовы, откладывая их до следующего кадра; используется внутренне слушателем window.resize для предотвращения избыточной работы.app.cancelResize() — отменяет изменение размера, находящееся в очереди. Вызывайте эту функцию перед сбросом собственного кода верстки, который инициировал вызов queueResize.Основы работы с Ticker
app.ticker и регистрирует на нём app.render() с приоритетом UPDATE_PRIORITY.LOW. Управляйте циклом с помощью app.start()/app.stop() и добавляйте обратные вызовы с помощью app.ticker.add / app.ticker.addOnce:app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
});app.ticker.addOnce(() => {
console.log("выполняется один раз в следующем кадре, затем удаляется");
});app.stop(); // приостановить цикл рендеринга (например, при скрытии вкладки)
app.start(); // возобновить
Ticker; используйте ticker.deltaTime для множителя, не зависящего от частоты кадров (~1,0 при 60 кадрах в секунду), ticker.deltaMS для реальных миллисекунд или ticker.FPS для текущей частоты кадров. См. pixijs-ticker для получения информации о приоритетах, ограничении частоты кадров, onRender, общих и частных тикерах, а также об изменении сигнатуры обратного вызова в V8.Ручной цикл рендеринга
await app.init({ autoStart: false, width: 800, height: 600 });
document.body.appendChild(app.canvas);function frame() {
updateScene();
app.render();
requestAnimationFrame(frame);
}
frame();
autoStart: false ` предотвращает автоматический запуск тикера плагином TickerPlugin. Вызовите app.render() самостоятельно (или app.renderer.render({ container: app.stage }) для достижения того же эффекта). Если вы всё же хотите, чтобы зарегистрированные обратные вызовы тикера срабатывали, вызовите app.ticker.update() внутри вашего цикла перед вызовом app.render().CullerPlugin (включается по желанию)
app.renderer.screen. По умолчанию он не зарегистрирован; добавьте его перед созданием приложения: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; // этот контейнер отсекается, когда его границы выходят за пределы экрана
world.cullableChildren = true; // по умолчанию; установите `false`, чтобы не выполнять рекурсию подочерним элементамconst tile = Sprite.from("tile.png");
tile.cullable = true;
world.addChild(tile);
app.stage.addChild(world);
флаг `cullable`. Переопределите проверку границ по умолчанию с помощью ` container.cullArea = new Rectangle(x, y, w, h)`, если вычисление границ дочерних элементов требует значительных ресурсов. Плагин обертывает метод app.render(), поэтому перед каждым кадром выполняется вызов Culler.shared.cull(app.stage, app.renderer.screen). См. pixijs-performance, чтобы узнать, в каких случаях отсечение оправдывает себя.Пользовательские плагины приложения
класс `Application`, зарегистрировав класс со статическими методами `init`, `destroy` и статическим свойством `extension = ExtensionType.Application`. Оба метода вызываются с переменной `this`, привязанной к экземпляру `Application`, поэтому доступны `this.renderer ` и `this.stage `.import {
Application,
ExtensionType,
extensions,
type ApplicationOptions,
} from "pixi.js";class FpsOverlay {
public static extension = ExtensionType.Application; public static init(this: Application, options: Partial<ApplicationOptions>) {
// выполняется внутри app.init() после создания рендерера
// присоединяем свойства/методы к `this`, чтобы сделать их доступными в приложении
} public static destroy(this: Application) {
// выполняется внутри app.destroy() — освобождаем все, что было присоединено
}
}extensions.add(FpsOverlay);
PixiMixins.ApplicationOptions:declare global {
namespace PixiMixins {
interface ApplicationOptions {
fpsOverlay?: { visible?: boolean };
}
}
}await app.init({ fpsOverlay: { visible: true } });
ResizePlugin, TickerPlugin и опциональный CullerPlugin используют один и тот же контракт. Если вы установили skipExtensionImports: true, зарегистрируйте необходимые встроенные плагины самостоятельно (extensions.add(ResizePlugin, TickerPlugin)).Распространённые ошибки
[КРИТИЧЕСКАЯ] Передача опций в конструктор
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 не принимает аргументов. Переданные туда параметры игнорируются и вызывают предупреждение об устаревании; рендер создается только внутри асинхронного вызова init().[HIGH] Использование app.view вместо app.canvas
document.body.appendChild(app.view);
document.body.appendChild(app.canvas);
app.view было переименовано в app.canvas. Старый геттер по-прежнему работает, но выдает предупреждение об устаревании.[СРЕДНЯЯ СЛОЖНОСТЬ] Обращение к app.canvas или app.renderer до завершения инициализации
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 и app.screen заполняются только после выполнения обещания init(). Доступ к ним раньше этого момента возвращает undefined.Справочник по 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
Все файлы
0 файловУстановить pixijs-application
Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.
Скачать ZIPКлонируйте репозиторий и скопируйте файлы навыка в свой проект.
git clone https://github.com/pixijs/pixijs/tree/dev/skills/pixijs-application # Copy the skill folder to .claude/skills/ or .codex/skills/
Копировать
Похожие навыки





Дом
