pixijs-assets
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseThe API is PixiJS's asset loader, resolver, and cache in one singleton. Use it to load textures, video, spritesheets, fonts, JSON, and other resources with format detection, resolution switching, bundle grouping, progress tracking, and GPU cleanup.
AssetsAssetsQuick Start
快速开始
ts
await Assets.init({ basePath: "/static/" });
const texture = await Assets.load("bunny.png");
const sprite = new Sprite(texture);
app.stage.addChild(sprite);
const [hero, enemy] = await Assets.load(["hero.png", "enemy.png"]);
await Assets.load({
alias: "logo",
src: "logo.webp",
});
const logo = new Sprite(Assets.get("logo"));Assets.init()basePathtexturePreferenceAssets.load()UnresolvedAssetAssets.get()ts
await Assets.init({ basePath: "/static/" });
const texture = await Assets.load("bunny.png");
const sprite = new Sprite(texture);
app.stage.addChild(sprite);
const [hero, enemy] = await Assets.load(["hero.png", "enemy.png"]);
await Assets.load({
alias: "logo",
src: "logo.webp",
});
const logo = new Sprite(Assets.get("logo"));Assets.init()basePathtexturePreferenceUnresolvedAssetAssets.load()Assets.get()Supported file types
支持的文件类型
| Type | Extensions | Parser ID | Loader |
|---|---|---|---|
| Textures | | | |
| SVG | | | |
| Video textures | | | |
| Sprite sheets | | | |
| Bitmap fonts | | | |
| Web fonts | | | |
| JSON | | | |
| Text | | | |
| Compressed textures | | | See |
| Animated GIFs | | | Requires |
The Parser ID column is the value you pass to the top-level field on an asset descriptor to force a specific loader. See "Forcing a parser" below.
parser| 类型 | 扩展名 | 解析器ID | 加载器 |
|---|---|---|---|
| 纹理 | | | |
| SVG | | | |
| 视频纹理 | | | |
| 精灵表 | | | |
| 位图字体 | | | |
| 网页字体 | | | |
| JSON | | | |
| 文本 | | | |
| 压缩纹理 | | | 详见 |
| GIF动图 | | | 需引入 |
解析器ID列的值是你在资源描述符的顶级字段中传入的内容,用于强制指定加载器。请查看下方“强制指定解析器”部分。
parserForcing a parser with parser
parser使用parser
强制指定解析器
parserBy default, PixiJS picks a loader by matching the file extension or MIME type. When your URL lacks an extension (CDN signed URLs, blob URLs, API endpoints, content-hashed paths), the resolver can't tell the loader what to do. Set the top-level field on the asset descriptor to force a specific loader:
parserts
// Signed CDN URL with no extension
const texture = await Assets.load({
src: "https://cdn.example.com/signed/abc123?token=xyz",
parser: "texture",
});
// API endpoint that returns JSON
const data = await Assets.load({
alias: "config",
src: "https://api.example.com/v1/config",
parser: "json",
});
// Extension-less font URL with explicit family
await Assets.load({
src: "https://cdn.example.com/fonts/hero-v2",
parser: "web-font",
data: { family: "Hero", weights: ["400", "700"] },
});
// Video stream without a file extension
const clipTexture = await Assets.load({
src: "https://cdn.example.com/stream/xyz",
parser: "video",
data: { mime: "video/mp4", muted: true, playsinline: true },
});The field goes at the top level of the asset descriptor (alongside and ), not inside . It takes any parser ID from the "Supported file types" table above:
parsersrcdatadata- ,
'texture','svg': image, SVG, and video textures'video' - ,
'json': JSON and plain text'text' - ,
'web-font': web and bitmap fonts'bitmap-font' - : texture atlas JSON
'spritesheet' - : animated GIFs (requires
'gif')'pixi.js/gif' - ,
'basis','dds','ktx': compressed textures (each requires its side-effect import)'ktx2'
默认情况下,PixiJS会通过匹配文件扩展名或MIME类型选择加载器。当你的URL没有扩展名时(如CDN签名URL、Blob URL、API端点、带内容哈希的路径),解析器无法确定使用哪个加载器。此时可在资源描述符的顶级字段中设置值,强制指定特定加载器:
parserts
// 无扩展名的CDN签名URL
const texture = await Assets.load({
src: "https://cdn.example.com/signed/abc123?token=xyz",
parser: "texture",
});
// 返回JSON的API端点
const data = await Assets.load({
alias: "config",
src: "https://api.example.com/v1/config",
parser: "json",
});
// 无扩展名且指定字体族的字体URL
await Assets.load({
src: "https://cdn.example.com/fonts/hero-v2",
parser: "web-font",
data: { family: "Hero", weights: ["400", "700"] },
});
// 无文件扩展名的视频流
const clipTexture = await Assets.load({
src: "https://cdn.example.com/stream/xyz",
parser: "video",
data: { mime: "video/mp4", muted: true, playsinline: true },
});parsersrcdatadata- ,
'texture','svg':图片、SVG和视频纹理'video' - ,
'json':JSON和纯文本'text' - ,
'web-font':网页字体和位图字体'bitmap-font' - :纹理图集JSON
'spritesheet' - :GIF动图(需引入
'gif')'pixi.js/gif' - ,
'basis','dds','ktx':压缩纹理(每种都需引入对应的副作用模块)'ktx2'
When you need it
适用场景
- Signed CDN URLs: has no extension the loader can test against.
https://cdn.example.com/get?id=abc123 - Blob or ObjectURL: produces
URL.createObjectURL(blob)URLs with no extension.blob:... - Custom routing: where the server decides the content type.
/api/assets/hero-v2 - Content-hashed paths without suffix: some build pipelines produce names like instead of
/static/abc123def./static/abc123def.png
If the URL does have an extension, you don't need ; let auto-detection do its job. Only set when detection can't work.
parserparser- CDN签名URL:没有加载器可识别的扩展名。
https://cdn.example.com/get?id=abc123 - Blob或ObjectURL:生成的
URL.createObjectURL(blob)URL无扩展名。blob:... - 自定义路由:由服务器决定内容类型。
/api/assets/hero-v2 - 无后缀的内容哈希路径:部分构建工具生成的文件名类似,而非
/static/abc123def。/static/abc123def.png
如果URL有扩展名,则无需设置;让自动检测机制处理即可。仅当检测无法生效时才设置。
parserparserloadParser
is deprecated
loadParserloadParser
已废弃
loadParserThe v7 field still works but emits a deprecation warning. Use for new code.
loadParserparserts
// Old (deprecated)
await Assets.load({ src: "...", loadParser: "loadTextures" });
// New
await Assets.load({ src: "...", parser: "texture" });v7版本的字段仍可使用,但会触发废弃警告。新代码请使用。
loadParserparserts
// 旧写法(已废弃)
await Assets.load({ src: "...", loadParser: "loadTextures" });
// 新写法
await Assets.load({ src: "...", parser: "texture" });Topics
相关主题
Every asset workflow is covered in a reference file. Pick the one that matches the question:
| Topic | Reference | When |
|---|---|---|
| Texture atlases and animations | references/spritesheet.md | Loading sprite sheets with |
| Video textures | references/video.md | |
| Web and bitmap fonts | references/fonts.md | |
| Animated GIFs | references/gif.md | |
| Grouping assets by feature | references/bundles.md | |
| Declaring everything upfront | references/manifests.md | |
| Cache lookups and cleanup | references/caching.md | |
| Priming future assets | references/background.md | |
| Loading screens | references/progress.md | |
| GPU-compressed formats | references/compressed-textures.md | |
| Vector vs raster SVG | references/svg.md | |
| Retina + format detection | references/resolution.md | |
每个资源工作流都在参考文档中有详细说明。请根据需求选择对应的文档:
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| 纹理图集与动画 | references/spritesheet.md | 使用 |
| 视频纹理 | references/video.md | |
| 网页字体与位图字体 | references/fonts.md | |
| GIF动图 | references/gif.md | |
| 按功能分组资源 | references/bundles.md | |
| 预先声明所有资源 | references/manifests.md | |
| 缓存查询与清理 | references/caching.md | |
| 预加载未来资源 | references/background.md | |
| 加载进度屏 | references/progress.md | |
| GPU压缩格式 | references/compressed-textures.md | |
| 矢量与光栅SVG | references/svg.md | |
| Retina屏+格式检测 | references/resolution.md | |
Decision guide
决策指南
- Need to load a single image? Use . No setup required.
Assets.load(url) - Loading many assets grouped by level/scene? Use a bundle. See .
references/bundles.md - Know all assets at build time? Use a manifest in . See
Assets.init.references/manifests.md - Need a loading bar? Pass a progress callback to . See
Assets.load.references/progress.md - Smooth transitions between levels? Background-load the next level. See .
references/background.md - Memory budget matters? Use compressed textures and between screens. See
Assets.unloadandreferences/compressed-textures.md.references/caching.md - Need crisp SVG icons at any size? Load as Graphics, not texture. See .
references/svg.md - Retina + WebP/AVIF? Configure and use format patterns. See
texturePreference.references/resolution.md
- 需要加载单张图片? 使用。无需额外配置。
Assets.load(url) - 需要按关卡/场景分组加载大量资源? 使用资源包。详见。
references/bundles.md - 构建时已明确所有资源? 在中使用资源清单。详见
Assets.init。references/manifests.md - 需要加载进度条? 给传入进度回调。详见
Assets.load。references/progress.md - 需要关卡间平滑过渡? 后台加载下一关资源。详见。
references/background.md - 内存预算有限? 使用压缩纹理,并在切换场景时调用。详见
Assets.unload和references/compressed-textures.md。references/caching.md - 需要任意尺寸都清晰的SVG图标? 以Graphics形式加载,而非纹理。详见。
references/svg.md - Retina屏+WebP/AVIF格式? 配置并使用格式模板。详见
texturePreference。references/resolution.md
Load options and error handling
加载选项与错误处理
There are two separate "options" concepts when loading assets:
- : the second argument to
LoadOptions/Assets.load. Controls error recovery, retries, progress, and completion callbacks across a whole load.loadBundle - : a field on each asset descriptor. Forwards parser-specific options (scale mode, resolution, font family, autoplay flags, etc.) to the specific loader for that asset.
data
加载资源时有两个独立的“选项”概念:
- :
LoadOptions/Assets.load的第二个参数。控制整个加载过程中的错误恢复、重试、进度和完成回调。loadBundle - :每个资源描述符的字段。将解析器特定选项(缩放模式、分辨率、字体族、自动播放标记等)传递给对应资源的加载器。
data
LoadOptions (per call)
LoadOptions(单次调用级)
ts
await Assets.load(["hero.png", "enemy.png"], {
onProgress: (p) => updateBar(p),
onError: (err, url) => {
const src = typeof url === "string" ? url : url.src;
console.warn("failed:", src, err);
},
strategy: "retry",
retryCount: 3,
retryDelay: 250,
});- :
onProgress(progress)as assets in the call complete.[0, 1] - :
onError(error, url)isurl. Guard before readingstring | ResolvedAsset; when.srcis a string,urlis undefined..src - — default
strategy: 'throw' | 'skip' | 'retry'.'throw'resolves with any successful assets;'skip'reattempts the failed ones.'retry' - — default
retryCount, retries per asset when3isstrategy.'retry' - — default
retryDelayms between retries.250
Global defaults live on , or pass to .
Loader.defaultOptionsloadOptionsAssets.init()ts
await Assets.load(["hero.png", "enemy.png"], {
onProgress: (p) => updateBar(p),
onError: (err, url) => {
const src = typeof url === "string" ? url : url.src;
console.warn("加载失败:", src, err);
},
strategy: "retry",
retryCount: 3,
retryDelay: 250,
});- :加载完成度,范围
onProgress(progress)。[0, 1] - :
onError(error, url)类型为url。读取string | ResolvedAsset前需判断;当.src为字符串时,url未定义。.src - — 默认值
strategy: 'throw' | 'skip' | 'retry'。'throw'会返回所有加载成功的资源;'skip'会重新尝试加载失败的资源。'retry' - — 默认值
retryCount,当3为strategy时,每个资源的重试次数。'retry' - — 默认值
retryDelay毫秒,重试间隔时间。250
全局默认配置在上,也可在中传入设置。
Loader.defaultOptionsAssets.init()loadOptionsdata
options (per asset)
datadata
选项(单资源级)
dataEach loader parser reads its own options from the field on the asset descriptor. Use the table below to pick the right options for each asset type:
data| Asset type | | Key options | Reference |
|---|---|---|---|
| Texture (image) | | | |
| SVG | | | |
| Video | | | |
| Web font | | | |
| Bitmap font | (none; auto-configured) | Distance-field detection sets scale mode and mipmaps | |
| Spritesheet | | | |
| GIF | | | |
| Compressed texture | | | |
| JSON / Text | (none) | Returned as-is | — |
Example combining and :
LoadOptionsdatats
await Assets.load(
{
alias: "hero",
src: "hero.png",
data: { scaleMode: "nearest", resolution: 2 },
},
{ strategy: "retry", retryCount: 3 },
);Inside a manifest or bundle, every entry can carry its own :
datats
await Assets.init({
manifest: {
bundles: [
{
name: "level1",
assets: [
{ alias: "tiles", src: "tiles.png", data: { scaleMode: "nearest" } },
{ alias: "font", src: "hero.woff2", data: { family: "Hero" } },
{
alias: "clip",
src: "intro.mp4",
data: { autoPlay: false, muted: true },
},
],
},
],
},
});每个加载器解析器会从资源描述符的字段读取专属选项。请使用下表为每种资源类型选择正确的选项:
data| 资源类型 | | 核心选项 | 参考文档 |
|---|---|---|---|
| 纹理(图片) | | | |
| SVG | | | |
| 视频 | | | |
| 网页字体 | | | |
| 位图字体 | 无;自动配置 | 距离场检测会设置缩放模式和多级纹理 | |
| 精灵表 | | | |
| GIF | | | |
| 压缩纹理 | | | |
| JSON / 文本 | 无 | 原样返回 | — |
结合和的示例:
LoadOptionsdatats
await Assets.load(
{
alias: "hero",
src: "hero.png",
data: { scaleMode: "nearest", resolution: 2 },
},
{ strategy: "retry", retryCount: 3 },
);在资源清单或资源包中,每个条目都可携带自己的:
datats
await Assets.init({
manifest: {
bundles: [
{
name: "level1",
assets: [
{ alias: "tiles", src: "tiles.png", data: { scaleMode: "nearest" } },
{ alias: "font", src: "hero.woff2", data: { family: "Hero" } },
{
alias: "clip",
src: "intro.mp4",
data: { autoPlay: false, muted: true },
},
],
},
],
},
});Runtime configuration
运行时配置
Assets.init(options)basePathmanifest- — string or
defaultSearchParamsappended to every resolved URL. Useful for cache busting.Record<string, any> - — bypass browser format detection for faster init. Requires explicit
skipDetections: boolean.texturePreference.format - — customize how bundle keys resolve so the same alias can live in multiple bundles.
bundleIdentifier: BundleIdentifierOptions - — set the default
loadOptions: Partial<LoadOptions>,strategy,retryCount, and callbacks for every subsequentretryDelaycall.Assets.load - —
preferences: Partial<AssetsPreferences>,crossOrigin,preferWorkers,preferCreateImageBitmap.parseAsGraphicsContext
After init, preferences can still be tuned:
ts
Assets.setPreferences({
crossOrigin: "anonymous",
preferCreateImageBitmap: false,
});
for (const detection of Assets.detections) {
console.log(detection.extension);
}
Assets.reset();- — push new preferences to every parser that supports them.
Assets.setPreferences(preferences) - — getter exposing the registered
Assets.detectionslist; use when inspecting what formats the current environment advertises.FormatDetectionParser - — internal full reset (resolver + loader + cache). Intended for tests so a fresh
Assets.reset()can run.Assets.init
Assets.init(options)basePathmanifest- — 字符串或
defaultSearchParams,会追加到每个解析后的URL中。适用于缓存刷新。Record<string, any> - — 跳过浏览器格式检测,加快初始化速度。需显式设置
skipDetections: boolean。texturePreference.format - — 自定义资源包键的解析方式,使同一别名可存在于多个资源包中。
bundleIdentifier: BundleIdentifierOptions - — 为后续所有
loadOptions: Partial<LoadOptions>调用设置默认的Assets.load、strategy、retryCount和回调函数。retryDelay - —
preferences: Partial<AssetsPreferences>,crossOrigin,preferWorkers,preferCreateImageBitmap。parseAsGraphicsContext
初始化后,仍可调整偏好设置:
ts
Assets.setPreferences({
crossOrigin: "anonymous",
preferCreateImageBitmap: false,
});
for (const detection of Assets.detections) {
console.log(detection.extension);
}
Assets.reset();- — 将新的偏好设置推送给所有支持的解析器。
Assets.setPreferences(preferences) - — 获取已注册的
Assets.detections列表;用于检查当前环境支持的格式。FormatDetectionParser - — 内部完全重置(解析器+加载器+缓存)。主要用于测试,以便重新执行
Assets.reset()。Assets.init
Common Mistakes
常见错误
[CRITICAL] Using Texture.from(url)
to load
Texture.from(url)[严重] 使用Texture.from(url)
加载资源
Texture.from(url)Wrong:
ts
const texture = Texture.from("https://example.com/image.png");Correct:
ts
const texture = await Assets.load("https://example.com/image.png");In v8, only reads the cache. It does not fetch from a URL. Use first; the return value is the texture itself.
Texture.from()Assets.load()错误写法:
ts
const texture = Texture.from("https://example.com/image.png");正确写法:
ts
const texture = await Assets.load("https://example.com/image.png");在v8版本中,仅读取缓存,不会从URL获取资源。请先使用;其返回值就是纹理本身。
Texture.from()Assets.load()[HIGH] Using positional Assets.add
signature
Assets.add[高危] 使用Assets.add
的位置参数签名
Assets.addWrong:
ts
Assets.add("bunny", "bunny.png");Correct:
ts
Assets.add({ alias: "bunny", src: "bunny.png" });The positional form was removed in v8. Use the options object with and properties.
Assets.add(key, url)aliassrc错误写法:
ts
Assets.add("bunny", "bunny.png");正确写法:
ts
Assets.add({ alias: "bunny", src: "bunny.png" });Assets.add(key, url)aliassrc[HIGH] Not unloading textures between levels
[高危] 关卡切换时未卸载纹理
Assets.load()Assets.unloadBundle()Assets.load()Assets.unloadBundle()