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),通过 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
...展开全部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-container(app.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.canvas、app.renderer或app.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
在初始化时设置 该插件会保持画布与目标区域的匹配。 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叠加层的容器;当需要将 DOM 元素固定到场景节点时,请将其附加在app.canvas旁边(参见pixijs-scene-dom-container)。
ResizePlugin
resizeTo(或稍后重新赋值app.resizeTo),使插件监听resize事件,并使用目标元素的客户端尺寸调用renderer.resize()。结合autoDensity: true和resolution: 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 基础知识
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(需手动启用)
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.renderer和this.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} });
ResizePlugin、TickerPlugin 以及可选的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);
中,Application构造函数不接受任何参数。传递给它的选项会被忽略,并记录一条弃用警告;渲染器仅在异步的init()调用内部创建。[高危] 使用 app.view 代替 app.canvas
document.body.appendChild(app.view);
document.body.appendChild(app.canvas);
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.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 个文件相关技能





首页
