选项
首页首页 Skill 其他 pixijs-application

pixijs-application

pixijs/pixijs 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),通过 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);// ... 运行场景,ticker 会自动触发 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是一个普通的容器。有关场景图的详细信息(变换、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()。结合autoDensity: trueresolution: window.devicePixelRatio可实现高 DPI 输出。

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会相应更新;请在调整大小后读取这些属性以布局 UI。

  • 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获取当前帧率。 有关优先级、帧率限制、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

自定义应用程序插件

通过注册一个具有静态初始化方法静态销毁方法以及静态 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构造函数不接受任何参数。传递给它的选项会被忽略,并记录一条弃用警告;渲染器仅在异步的init()调用内部创建。

[高危] 使用 app.view 代替 app.canvas

错误:

document.body.appendChild(app.view);

正确:

document.body.appendChild(app.canvas);

在 V8 版本中,app.view已重命名为app.canvas。旧的获取器虽然仍可正常工作,但会触发弃用警告。

[MEDIUM] 在 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