選項
首頁首頁 Skill 其他 pixijs-application

pixijs-application

pixijs/pixijs pixijs/pixijs

在建立及設定 PixiJS v8 應用程式時,請運用此技巧。內容涵蓋新的 Application() 及 async 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)、透過 ExtensionType.Application 建立自訂 ApplicationPlugin、啟動/停止生命週期,以及搭配 releaseGlobalResources 的 app.destroy()。 觸發條件: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

...展開全部
50
更新時間 2026-08-04

Application是一個便利封裝物件,其擁有渲染器、根舞台容器、畫布以及 Ticker/Resize 外掛程式。在 v8 中,其建構函式不接受任何參數;所有設定皆透過非同步的app.init()呼叫傳遞,該呼叫會透過autoDetectRenderer 來實例化渲染器。

快速入門

import{Application}from "pixi.js";constapp =new Application();awaitapp.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-containerapp.stage 的操作)、pixijs-environments(非瀏覽器環境設定)。

核心模式

生命週期:construct、init、render、destroy

import{Application}from "pixi.js";constapp =new Application();awaitapp.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.canvasapp.rendererapp.screen
  • 當 init 解析完成後,TickerPlugin 會在每個幀中呼叫app.render()一次(除非autoStart: false)。
  • app.destroy(rendererDestroyOptions, stageDestroyOptions)— 第一個參數會轉交給renderer.destroy()。傳入true{ removeView: true }可將畫布從 DOM 中移除。 若要在同一分頁中拆除並重新建立應用程式時釋放全域資源池(批次、紋理快取),請加入releaseGlobalResources: true;省略此參數通常是重新初始化後出現閃爍與紋理過時的主因(參見pixijs-performance)。

主要初始化選項

awaitapp.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 上下文標誌、 圖形貝塞爾曲線平滑度、GC,以及各渲染器專屬的覆寫設定(webgl/webgpu/canvasOptions)——請參閱references/application-options.md

應用程式屬性

app.stage;// 根容器;請在此處新增所有顯示物件
app.renderer;// WebGL/WebGPU/Canvas 渲染器實例
app.canvas;// HTMLCanvasElement (請自行將其插入 DOM)
app.screen// 以 CSS 像素為單位描述可見區域的矩形
app.domContainerRoot// 用於容納 DOMContainer 疊加層的 HTMLDivElement

app.stage是一個普通的Container。有關場景圖的詳細資訊(變換、addChild、destroy),請參閱pixijs-scene-container。 關於渲染器層級的操作(extract、generateTexture、自訂系統),請參閱pixijs-core-conceptspixijs-custom-renderingapp.domContainerRoot

渲染器用來容納DOMContainer疊加層的元素;當您需要將 DOM 元素固定到場景節點時,請將其附加在app.canvas旁邊(請參閱pixijs-scene-dom-container)。

ResizePlugin

請在初始化時設定resizeTo(或稍後重新指派app.resizeTo),讓外掛程式監聽resize事件,並使用目標元素的客戶端尺寸呼叫renderer.resize()。若要產生高 DPI 輸出,請搭配autoDensity: trueresolution: window.devicePixelRatio使用。

awaitapp.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 基礎知識

TickerPlugin 會建立app.ticker,並以UPDATE_PRIORITY.LOW 優先級將app.render()註冊至其中。可透過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以取得與幀率無關的倍數(60fps 時約為 1.0)、ticker.deltaMS以取得實際毫秒數,或ticker.FPS以取得當前幀率。 有關優先級、FPS 上限、onRender、共用與私有計時器,以及 V8 回呼簽名變更,請參閱pixijs-ticker

手動渲染迴圈

awaitapp.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.render() 之前,先呼叫app.ticker.update()

CullerPlugin(需手動啟用)

CullerPlugin 會跳過渲染位於app.renderer.screen 範圍外的容器。此外掛程式預設未註冊;請在建立應用程式前將其加入:

import{
  Application,
  Container,
  Sprite,
  extensions,
  CullerPlugin,
  Rectangle,
}from "pixi.js";extensions.add(CullerPlugin);constapp =new Application();
awaitapp.init({width:800,height:600});constworld =new Container();
world.cullable=true;// 當此容器的邊界超出螢幕範圍時,將被剔除
world.cullableChildren=true;// 預設值;設定為 `false` 可跳過對子節點的 遞迴檢查consttile =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

自訂應用程式外掛程式

透過註冊一個具備static initstatic destroystatic extension = ExtensionType.Application 的類別來擴充Application。這兩種方法在呼叫時,this會綁定至 Application 實例,因此可存取this.rendererthis.stage

import{
  Application,
  ExtensionType,
  extensions,
  type ApplicationOptions,
}from "pixi.js";class FpsOverlay{
 public staticextension =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};
    }
  }
}awaitapp.init({fpsOverlay: {visible:true} });

內建的ResizePluginTickerPlugin 以及需手動啟用的CullerPlugin均採用此相同合約。若您將skipExtensionImports 設為 true,請自行註冊所需的內建外掛程式(extensions.add(ResizePlugin, TickerPlugin))。

常見錯誤

[嚴重] 將選項傳遞給建構函式

錯誤示例:

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

正確:

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

在 V8 中,Application建構函式不接受任何參數。傳入的選項將被忽略並記錄為已廢棄警告;渲染器僅會在 asyncinit()呼叫內部建立。

[高風險] 使用 app.view 代替 app.canvas

錯誤:

document.body.appendChild(app.view);

正確:

document.body.appendChild(app.canvas);

在 v8 版本中,app.view已更名為app.canvas。舊的 getter 雖然仍可運作,但會觸發廢棄警告。

[中級] 在 init 解析完成前存取 app.canvas 或 app.renderer

錯誤:

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

正確寫法:

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

app.rendererapp.canvasapp.screen僅會在init()承諾解析後才會被初始化。若在該時點之前存取,將返回undefined

API 參考

在 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

所有檔案

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/

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/,Claude 會自動偵測並使用該技能
儲存庫 pixijs/pixijs

相關技能

tilemaps
更新時間 2026-08-04
multica-creating-agents
更新時間 2026-08-12
v4-new-features
更新時間 2026-08-04
agent-github-pr-manager
更新時間 2026-08-03
OR