Skip to main content

在不同环境中使用 PixiJS

¥Using PixiJS in Different Environments

PixiJS 是一个高度适应性的库,可以在各种环境中运行,包括浏览器、Web Workers 和自定义执行上下文(如 Node.js)。本指南解释 PixiJS 如何处理不同的环境,以及如何配置它以满足你的应用需求。

¥PixiJS is a highly adaptable library that can run in a variety of environments, including browsers, Web Workers, and custom execution contexts like Node.js. This guide explains how PixiJS handles different environments and how you can configure it to suit your application's needs.

在浏览器中运行 PixiJS

¥Running PixiJS in the Browser

对于浏览器环境,PixiJS 默认使用 BrowserAdapter,你无需进行任何配置。

¥For browser environments, PixiJS uses the BrowserAdapter by default, you should not need to configure anything

示例:

¥Example:

import { Application } from 'pixi.js';

const app = new Application();

await app.init({
width: 800,
height: 600,
});

document.body.appendChild(app.canvas);

在 Web Workers 中运行 PixiJS

¥Running PixiJS in Web Workers

Web Workers 提供并行执行环境,非常适合卸载渲染任务。PixiJS 使用 WebWorkerAdapter 支持 Web Workers:

¥Web Workers provide a parallel execution environment, ideal for offloading rendering tasks. PixiJS supports Web Workers using the WebWorkerAdapter:

示例:

¥Example:

import { DOMAdapter, WebWorkerAdapter } from 'pixi.js';

// Must be set before creating anything in PixiJS
DOMAdapter.set(WebWorkerAdapter);

const app = new Application();

await app.init({
width: 800,
height: 600,
});

app.canvas // OffscreenCanvas

自定义环境

¥Custom Environments

对于非标准环境,你可以通过实现 Adapter 接口来创建自定义适配器。这使得 PixiJS 能够在 Node.js 或无头测试设置等环境中运行。

¥For non-standard environments, you can create a custom adapter by implementing the Adapter interface. This allows PixiJS to function in environments like Node.js or headless testing setups.

自定义适配器示例:

¥Example Custom Adapter:

import { DOMAdapter } from 'pixi.js';

const CustomAdapter = {
createCanvas: (width, height) => {/* custom implementation */},
getCanvasRenderingContext2D: () => {/* custom implementation */},
getWebGLRenderingContext: () => {/* custom implementation */},
getNavigator: () => ({ userAgent: 'Custom', gpu: null }),
getBaseUrl: () => 'custom://',
fetch: async (url, options) => {/* custom fetch */},
parseXML: (xml) => {/* custom XML parser */},
};

DOMAdapter.set(CustomAdapter);