pixijs-environments

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
DOMAdapter
abstracts every piece of DOM access PixiJS does (canvas creation, Image loading, fetch, XML parsing) so the library can run in non-browser contexts. Call
DOMAdapter.set(...)
before
app.init()
to swap in a different adapter.
DOMAdapter
抽象了PixiJS所有的DOM访问操作(画布创建、图片加载、fetch、XML解析),因此该库可以在非浏览器环境中运行。请在
app.init()
之前调用
DOMAdapter.set(...)
来切换为不同的适配器。

Quick Start

快速开始

ts
// worker.ts — OffscreenCanvas posted from main thread
DOMAdapter.set(WebWorkerAdapter);

self.onmessage = async (event) => {
  const app = new Application();
  await app.init({
    canvas: event.data.canvas,
    width: 800,
    height: 600,
  });
};
For CSP contexts that block
unsafe-eval
, import the polyfill before any renderer init:
ts
import "pixi.js/unsafe-eval";
Related skills:
pixijs-application
(standard browser init),
pixijs-migration-v8
(settings removal, adapter changes).
ts
// worker.ts — 从主线程传递的OffscreenCanvas
DOMAdapter.set(WebWorkerAdapter);

self.onmessage = async (event) => {
  const app = new Application();
  await app.init({
    canvas: event.data.canvas,
    width: 800,
    height: 600,
  });
};
对于阻止
unsafe-eval
的CSP上下文,请在任何渲染器初始化之前导入polyfill:
ts
import "pixi.js/unsafe-eval";
相关技能:
pixijs-application
(标准浏览器初始化)、
pixijs-migration-v8
(设置移除、适配器变更)。

Core Patterns

核心模式

Web Worker with OffscreenCanvas

结合OffscreenCanvas的Web Worker

Transfer an OffscreenCanvas from the main thread, then initialize PixiJS in the worker:
ts
// main.ts
const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.ts", { type: "module" });
worker.postMessage({ canvas: offscreen }, [offscreen]);
ts
// worker.ts
import { Application, DOMAdapter, WebWorkerAdapter } from "pixi.js";

DOMAdapter.set(WebWorkerAdapter);

self.onmessage = async (event) => {
  const app = new Application();
  await app.init({
    canvas: event.data.canvas,
    width: 800,
    height: 600,
  });
};
DOMAdapter.set(WebWorkerAdapter)
must happen before
new Application()
. The WebWorkerAdapter uses
OffscreenCanvas
instead of
document.createElement('canvas')
and
@xmldom/xmldom
for XML parsing.
Features that do not work inside a Web Worker (no DOM access):
  • DOMContainer
    — there is no real DOM node to overlay.
  • AccessibilitySystem
    — depends on live DOM focus and screen reader hooks.
  • FontFace
    loading via the Font Loading API — use pre-converted bitmap fonts (
    BitmapFont.install
    or
    .fnt
    assets) instead.
从主线程传递OffscreenCanvas,然后在Worker中初始化PixiJS:
ts
// main.ts
const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.ts", { type: "module" });
worker.postMessage({ canvas: offscreen }, [offscreen]);
ts
// worker.ts
import { Application, DOMAdapter, WebWorkerAdapter } from "pixi.js";

DOMAdapter.set(WebWorkerAdapter);

self.onmessage = async (event) => {
  const app = new Application();
  await app.init({
    canvas: event.data.canvas,
    width: 800,
    height: 600,
  });
};
DOMAdapter.set(WebWorkerAdapter)
必须在
new Application()
之前执行。WebWorkerAdapter使用
OffscreenCanvas
替代
document.createElement('canvas')
,并使用
@xmldom/xmldom
进行XML解析。
在Web Worker中无法使用的功能(无DOM访问权限):
  • DOMContainer
    — 没有真实的DOM节点可用于叠加。
  • AccessibilitySystem
    — 依赖实时DOM焦点和屏幕阅读器钩子。
  • 通过Font Loading API加载
    FontFace
    — 请改用预转换的位图字体(
    BitmapFont.install
    .fnt
    资源)。

Environment-specific subpath imports

环境专属子路径导入

Instead of importing
pixi.js
, you can pull in a curated bundle for each environment:
ts
import "pixi.js/browser"; // accessibility, dom, events, spritesheet, rendering, filters
import "pixi.js/webworker"; // spritesheet, rendering, filters (no DOM-only modules)
pixi.js/webworker
deliberately omits
accessibility
,
dom
, and
events
because they require the DOM. Use these subpath entries when you want static, synchronous module registration instead of relying on
loadEnvironmentExtensions
to dynamic-import the right set at renderer init.
除了导入
pixi.js
,你还可以为每个环境引入特定的打包文件:
ts
import "pixi.js/browser"; // 无障碍、dom、事件、精灵表、渲染、滤镜
import "pixi.js/webworker"; // 精灵表、渲染、滤镜(无仅DOM模块)
pixi.js/webworker
刻意省略了
accessibility
dom
events
,因为这些模块需要DOM。当你希望使用静态同步模块注册,而非依赖
loadEnvironmentExtensions
在渲染器初始化时动态导入合适的模块集时,可以使用这些子路径入口。

loadEnvironmentExtensions

loadEnvironmentExtensions

ts
import { loadEnvironmentExtensions } from "pixi.js";

await loadEnvironmentExtensions(false); // false = load defaults; true = skip
loadEnvironmentExtensions(skip)
replaces the deprecated
autoDetectEnvironment
helper (since 8.1.6). Pass
true
to opt out of auto-loading the default browser extensions when you are bootstrapping a custom environment.
autoDetectEnvironment(add)
still exists as a shim that forwards to
loadEnvironmentExtensions(!add)
.
ts
import { loadEnvironmentExtensions } from "pixi.js";

await loadEnvironmentExtensions(false); // false = 加载默认项; true = 跳过加载
loadEnvironmentExtensions(skip)
替代了已弃用的
autoDetectEnvironment
工具(从8.1.6版本开始)。当你在自定义环境中启动时,传入
true
可选择退出自动加载默认浏览器扩展。
autoDetectEnvironment(add)
仍作为兼容层存在,会转发到
loadEnvironmentExtensions(!add)

CSP-compliant setup

符合CSP规范的设置

PixiJS uses
new Function()
internally for shader compilation and uniform syncing. In Content Security Policy environments that block
unsafe-eval
, import the polyfill:
ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";

const app = new Application();
await app.init({ width: 800, height: 600 });
The
pixi.js/unsafe-eval
import replaces eval-based code generation with static polyfills for shader sync, UBO sync, uniform sync, and particle buffer updates. The import must come before any PixiJS renderer initialization.
Tension note: The name
pixi.js/unsafe-eval
is counterintuitive. It does not enable unsafe eval; it removes the need for it. The name refers to the CSP directive it works around.
PixiJS在内部使用
new Function()
进行着色器编译和同步统一变量。在阻止
unsafe-eval
的内容安全策略(CSP)环境中,请导入polyfill:
ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";

const app = new Application();
await app.init({ width: 800, height: 600 });
pixi.js/unsafe-eval
导入会将基于eval的代码生成替换为静态polyfill,用于着色器同步、UBO同步、统一变量同步和粒子缓冲区更新。该导入必须在任何PixiJS渲染器初始化之前完成。
注意事项:
pixi.js/unsafe-eval
的名称有违直觉。它并非启用不安全的eval,而是消除对它的需求。这个名称指的是它所规避的CSP指令。

Custom adapter

自定义适配器

For non-standard environments (Node.js, headless testing, SSR), implement the full Adapter interface:
ts
import { DOMAdapter } from "pixi.js";
import type { Adapter } from "pixi.js";
import { createCanvas, Image } from "canvas";
import { DOMParser } from "@xmldom/xmldom";

const HeadlessAdapter: Adapter = {
  createCanvas: (width, height) => createCanvas(width ?? 0, height ?? 0),
  createImage: () => new Image(),
  getCanvasRenderingContext2D: () => CanvasRenderingContext2D,
  getWebGLRenderingContext: () => WebGLRenderingContext,
  getNavigator: () => ({ userAgent: "HeadlessAdapter", gpu: null }),
  getBaseUrl: () => "file://",
  getFontFaceSet: () => null,
  fetch: (url, options) => fetch(url, options),
  parseXML: (xml) => new DOMParser().parseFromString(xml, "text/xml"),
};

DOMAdapter.set(HeadlessAdapter);
The Adapter interface requires these methods:
createCanvas
,
createImage
,
getCanvasRenderingContext2D
,
getWebGLRenderingContext
,
getNavigator
,
getBaseUrl
,
getFontFaceSet
,
fetch
,
parseXML
.
对于非标准环境(Node.js、无头测试、SSR),请实现完整的Adapter接口:
ts
import { DOMAdapter } from "pixi.js";
import type { Adapter } from "pixi.js";
import { createCanvas, Image } from "canvas";
import { DOMParser } from "@xmldom/xmldom";

const HeadlessAdapter: Adapter = {
  createCanvas: (width, height) => createCanvas(width ?? 0, height ?? 0),
  createImage: () => new Image(),
  getCanvasRenderingContext2D: () => CanvasRenderingContext2D,
  getWebGLRenderingContext: () => WebGLRenderingContext,
  getNavigator: () => ({ userAgent: "HeadlessAdapter", gpu: null }),
  getBaseUrl: () => "file://",
  getFontFaceSet: () => null,
  fetch: (url, options) => fetch(url, options),
  parseXML: (xml) => new DOMParser().parseFromString(xml, "text/xml"),
};

DOMAdapter.set(HeadlessAdapter);
Adapter接口需要以下方法:
createCanvas
createImage
getCanvasRenderingContext2D
getWebGLRenderingContext
getNavigator
getBaseUrl
getFontFaceSet
fetch
parseXML

Checking the current adapter

检查当前适配器

ts
import { DOMAdapter } from "pixi.js";

const adapter = DOMAdapter.get();
const canvas = adapter.createCanvas(256, 256);
const img = adapter.createImage();
DOMAdapter.get()
returns whatever adapter is currently set. Use this for any DOM access within PixiJS-adjacent code instead of calling
document
or
Image
directly.
ts
import { DOMAdapter } from "pixi.js";

const adapter = DOMAdapter.get();
const canvas = adapter.createCanvas(256, 256);
const img = adapter.createImage();
DOMAdapter.get()
返回当前设置的适配器。在PixiJS相关代码中,任何DOM访问都应使用此方法,而非直接调用
document
Image

Common Mistakes

常见错误

[CRITICAL] Not setting adapter before app.init()

[严重] 未在app.init()前设置适配器

Wrong:
ts
const app = new Application();
await app.init({ width: 800, height: 600 });
DOMAdapter.set(WebWorkerAdapter); // too late; adapter already read during init
Correct:
ts
DOMAdapter.set(WebWorkerAdapter);
const app = new Application();
await app.init({ width: 800, height: 600 });
DOMAdapter.set()
must be called before
app.init()
in non-browser environments. PixiJS reads the adapter during
app.init()
when the renderer is created.
new Application()
itself only creates the stage Container and does not read the adapter.
错误示例:
ts
const app = new Application();
await app.init({ width: 800, height: 600 });
DOMAdapter.set(WebWorkerAdapter); // 太晚了;初始化期间已读取适配器
正确示例:
ts
DOMAdapter.set(WebWorkerAdapter);
const app = new Application();
await app.init({ width: 800, height: 600 });
在非浏览器环境中,
DOMAdapter.set()
必须在
app.init()
之前调用。PixiJS在创建渲染器的
app.init()
过程中读取适配器。
new Application()
本身仅创建舞台容器,不会读取适配器。

[HIGH] Using document or Image directly

[高风险] 直接使用document或Image

Wrong:
ts
const img = new Image();
img.src = "texture.png";
Correct:
ts
import { DOMAdapter } from "pixi.js";

const img = DOMAdapter.get().createImage();
img.src = "texture.png";
All DOM access in PixiJS goes through DOMAdapter. Direct use of
document
,
Image
, or other browser globals breaks Web Worker and SSR compatibility.
错误示例:
ts
const img = new Image();
img.src = "texture.png";
正确示例:
ts
import { DOMAdapter } from "pixi.js";

const img = DOMAdapter.get().createImage();
img.src = "texture.png";
PixiJS中的所有DOM访问都通过DOMAdapter进行。直接使用
document
Image
或其他浏览器全局对象会破坏Web Worker和SSR的兼容性。

[HIGH] CSP unsafe-eval import name confusion

[高风险] 混淆CSP unsafe-eval导入名称

Wrong:
ts
// CSP environment, omitting the import
import { Application } from "pixi.js";
// Throws: "Current environment does not allow unsafe-eval,
// please use pixi.js/unsafe-eval module to enable support."
Correct:
ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";
The
pixi.js/unsafe-eval
import removes the need for
eval()
/
new Function()
in shader compilation. Despite the name suggesting it enables unsafe eval, it does the opposite: it installs static polyfills so PixiJS works under strict CSP.
PixiJS detects CSP blocking at renderer init and throws the error above. The browser may also log its own CSP violation before PixiJS reports; both point to the same fix.
错误示例:
ts
// CSP环境,省略了导入
import { Application } from "pixi.js";
// 抛出错误:"当前环境不允许unsafe-eval,
// 请使用pixi.js/unsafe-eval模块来启用支持。"
正确示例:
ts
import "pixi.js/unsafe-eval";
import { Application } from "pixi.js";
pixi.js/unsafe-eval
导入消除了着色器编译中对
eval()
/
new Function()
的需求。尽管名称看起来像是启用不安全的eval,但实际上恰好相反:它安装静态polyfill,使PixiJS能在严格的CSP下运行。
PixiJS会在渲染器初始化时检测CSP阻止情况并抛出上述错误。浏览器也可能在PixiJS报告之前记录自身的CSP违规信息,两者指向相同的修复方案。

[HIGH] Using old settings.ADAPTER pattern

[高风险] 使用旧版settings.ADAPTER模式

Wrong:
ts
import { settings, WebWorkerAdapter } from "pixi.js";
settings.ADAPTER = WebWorkerAdapter;
Correct:
ts
import { DOMAdapter, WebWorkerAdapter } from "pixi.js";
DOMAdapter.set(WebWorkerAdapter);
The
settings
object was removed in v8. All adapter configuration uses
DOMAdapter.set()
.
错误示例:
ts
import { settings, WebWorkerAdapter } from "pixi.js";
settings.ADAPTER = WebWorkerAdapter;
正确示例:
ts
import { DOMAdapter, WebWorkerAdapter } from "pixi.js";
DOMAdapter.set(WebWorkerAdapter);
v8版本中已移除
settings
对象。所有适配器配置均使用
DOMAdapter.set()

API Reference

API参考