Namespace: assets

assets

A one stop shop for all Pixi resource management! Super modern and easy to use, with enough flexibility to customize and do what you need!

Use the singleton class Assets to easily load and manage all your assets.

import { Assets, Texture } from 'pixi.js';

const bunnyTexture = await Assets.load<Texture>('bunny.png');
const sprite = new Sprite(bunnyTexture);

Check out the sections below for more information on how to deal with assets.

Asset Loading

Do not be afraid to load things multiple times - under the hood, it will NEVER load anything more than once.

For example:

import { Assets } from 'pixi.js';

promise1 = Assets.load('bunny.png')
promise2 = Assets.load('bunny.png')

// promise1 === promise2

Here both promises will be the same. Once resolved... Forever resolved! It makes for really easy resource management!

Out of the box Pixi supports the following files:

Textures
  • Textures are loaded as ImageBitmap on a worker thread where possible. Leading to much less janky load + parse times.
  • By default, we will prefer to load AVIF and WebP image files if you specify them. But if the browser doesn't support AVIF or WebP we will fall back to png and jpg.
  • Textures can also be accessed via Texture.from() (see Texture.from) and now use this asset manager under the hood!
  • Don't worry if you set preferences for textures that don't exist (for example you prefer 2x resolutions images but only 1x is available for that texture, the Assets manager will pick that up as a fallback automatically)

Sprite sheets

  • It's hard to know what resolution a sprite sheet is without loading it first, to address this there is a naming convention we have added that will let Pixi understand the image format and resolution of the spritesheet via its file name: my-spritesheet{resolution}.{imageFormat}.json

    For example:
    • my-spritesheet@2x.webp.json* // 2x resolution, WebP sprite sheet*
    • my-spritesheet@0.5x.png.json* // 0.5x resolution, png sprite sheet*
  • This is optional! You can just load a sprite sheet as normal. This is only useful if you have a bunch of different res / formatted spritesheets.
Fonts

Web fonts will be loaded with all weights. It is possible to load only specific weights by doing the following:

import { Assets } from 'pixi.js';

// Load specific weights..
await Assets.load({
    data: {
        weights: ['normal'], // Only loads the weight
    },
    src: `outfit.woff2`,
});

// Load everything...
await Assets.load(`outfit.woff2`);
Background Loading

Background loading will load stuff for you passively behind the scenes. To minimize jank, it will only load one asset at a time. As soon as a developer calls Assets.load(...) the background loader is paused and requested assets are loaded as a priority. Don't worry if something is in there that's already loaded, it will just get skipped!

You still need to call Assets.load(...) to get an asset that has been loaded in the background. It's just that this promise will resolve instantly if the asset has already been loaded.

Manifest and Bundles
  • Manifest is a descriptor that contains a list of all assets and their properties.
  • Bundles are a way to group assets together.
import { Assets } from 'pixi.js';

// Manifest Example
const manifest = {
    bundles: [
        {
            name: 'load-screen',
            assets: [
                {
                    alias: 'background',
                    src: 'sunset.png',
                },
                {
                    alias: 'bar',
                    src: 'load-bar.{png,webp}',
                },
            ],
        },
        {
            name: 'game-screen',
            assets: [
                {
                    alias: 'character',
                    src: 'robot.png',
                },
                {
                    alias: 'enemy',
                    src: 'bad-guy.png',
                },
            ],
        },
    ]
};

await Assets.init({ manifest });

// Load a bundle...
loadScreenAssets = await Assets.loadBundle('load-screen');
// Load another bundle...
gameScreenAssets = await Assets.loadBundle('game-screen');

Classes

Assets
BackgroundLoader
Cache
Loader
Resolver
Spritesheet

Interface Definitions

AssetExtension

This developer convenience object allows developers to group together the various asset parsers into a single object.

Example
 import { AssetExtension, extensions } from 'pixi.js';

 // create the CacheParser
 const cache = {
    test(asset: item): boolean {
       // Gets called by the cache when a dev caches an asset
    },
    getCacheableAssets(keys: string[], asset: item): Record<string, any> {
       // If the test passes, this function is called to get the cacheable assets
       // an example may be that a spritesheet object will return all the sub textures it has so they can
       // be cached.
    },
 };

 // create the ResolveURLParser
 const resolver = {
    test(value: string): boolean {
       // the test to perform on the url to determine if it should be parsed
    },
    parse(value: string): ResolvedAsset {
       // the function that will convert the url into an object
    },
 };

 // create the LoaderParser
 const loader = {
    name: 'itemLoader',
    extension: {
       type: ExtensionType.LoadParser,
    },
    async testParse(asset: any, options: ResolvedAsset) {
       // This function is used to test if the parse function should be run on the asset
    },
    async parse(asset: any, options: ResolvedAsset, loader: Loader) {
       // Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
    },
    unload(item: any) {
       // If an asset is parsed using this parser, the unload function will be called when the user requests an asset
       // to be unloaded. This is useful for things like sounds or textures that can be unloaded from memory
    },
 };

 // put it all together and create the AssetExtension
 extensions.add({
     extension: ExtensionType.Asset,
     cache,
     resolver,
     loader,
 }

AssetExtensionAdvanced

A more verbose version of the AssetExtension, allowing you to set the cached, loaded, parsed, and unloaded asset separately

Properties:
Name Type Description
cache Partial<CACHE_ASSET<CacheParser>>

the asset cache parser

detection Partial<FormatDetectionParser>

the asset format detection parser

extension Asset

The type of extension

loader LoaderParserAdvanced<META_DATA, ASSET, PARSED_ASSET, UNLOAD_ASSET>

the asset loader

resolver Partial<ResolveURLParser>

the asset resolve parser

AssetInitOptions

Initialization options object for the Assets Class.

Properties:
Name Type Description
basePath string

a base path for any assets loaded

bundleIdentifier BundleIdentifierOptions

advanced - override how bundlesIds are generated

defaultSearchParams string | Record<string, any>

a default URL parameter string to append to all assets loaded

manifest string | AssetsManifest

a manifest to tell the asset loader upfront what all your assets are this can be the manifest object itself, or a URL to the manifest.

preferences Partial<AssetsPreferences>

Optional loader preferences

skipDetections boolean

If true, don't attempt to detect whether browser has preferred formats available. May result in increased performance as it skips detection step.

texturePreference {
   resolution?: number | number[],
   format?: ArrayOr<string>
}

optional preferences for which textures preferences you have when resolving assets for example you might set the resolution to 0.5 if the user is on a rubbish old phone or you might set the resolution to 2 if the user is on a retina display

AssetsBundle

Structure of a bundle found in a Manifest file

Properties:
Name Type Description
assets UnresolvedAsset[] | UnresolvedAsset<string, ArrayOr<string> | Record>

The assets in the bundle

name string

The name of the bundle

AssetsManifest

The expected format of a manifest. This could be auto generated or hand made

Properties:
Name Type Description
bundles AssetsBundle[]

array of bundles

AssetsPreferences

Extensible preferences that can be used, for instance, when configuring loaders.

Since:
  • 7.2.0

BundleIdentifierOptions

Options for how the resolver deals with generating bundle ids

Properties:
Name Type Description
connector string

The character that is used to connect the bundleId and the assetId when generating a bundle asset id key

createBundleAssetId (bundleId: string, assetId: string) => string

A function that generates a bundle asset id key from a bundleId and an assetId

extractAssetIdFromBundle (bundleId: string, assetBundleId: string) => string

A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId

CacheParser

For every asset that is cached, it will call the parsers test function the flow is as follows:

  1. cacheParser.test(): Test the asset.
  2. cacheParser.getCacheableAssets(): If the test passes call the getCacheableAssets function with the asset

Useful if you want to add more than just a raw asset to the cache (for example a spritesheet will want to make all its sub textures easily accessible in the cache)

Properties:
Name Type Description
config Record<string, any>

A config to adjust the parser

extension ExtensionMetadata

The extension type of this cache parser

getCacheableAssets (keys: string[], asset: T) => Record<string, any>

If the test passes, this function is called to get the cacheable assets an example may be that a spritesheet object will return all the sub textures it has so they can be cached.

test (asset: T) => boolean

Gets called by the cache when a dev caches an asset

FormatDetectionParser

Format detection is useful for detecting feature support on the current platform.

Properties:
Name Type Description
add (formats: string[]) => Promise<string[]>

Add formats (file extensions) to the existing list of formats. Return an new array with added formats, do not mutate the formats argument.

extension ExtensionMetadata

Should be ExtensionType.DetectionParser

remove (formats: string[]) => Promise<string[]>

Remove formats (file extensions) from the list of supported formats. This is used when uninstalling this DetectionParser. Return an new array with filtered formats, do not mutate the formats argument.

test () => Promise<boolean>

Browser/platform feature detection supported if return true

LoaderParser

The interface to define a loader parser (all functions are optional).

When you create a parser object, the flow for every asset loaded is:

  1. parser.test() - Each URL to load will be tested here, if the test is passed the assets are loaded using the load function below. Good place to test for things like file extensions!
  2. parser.load() - This is the promise that loads the URL provided resolves with a loaded asset if returned by the parser.
  3. parser.testParse() - This function is used to test if the parse function should be run on the asset If this returns true then parse is called with the asset
  4. parse.parse() - Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful

Some loaders may only be used for parsing, some only for loading, and some for both!

LoadSVGConfig

Configuration for the loadSVG plugin.

Properties:
Name Type Default Description
crossOrigin HTMLImageElement["crossOrigin"] 'anonymous'

The crossOrigin value to use for loading the SVG as an image.

parseAsGraphicsContext boolean false

When set to true, loading and decoding images will happen with new Image(),

See:
  • assets.loadSVG

LoadTextureConfig

Configuration for the loadTextures plugin.

Properties:
Name Type Default Description
crossOrigin HTMLImageElement["crossOrigin"] 'anonymous'

The crossOrigin value to use for images when preferCreateImageBitmap is false.

preferCreateImageBitmap boolean true

When set to true, loading and decoding images will happen with createImageBitmap, otherwise it will use new Image().

preferWorkers boolean true

When set to true, loading and decoding images will happen with Worker thread, if available on the browser. This is much more performant as network requests and decoding can be expensive on the CPU. However, not all environments support Workers, in some cases it can be helpful to disable by setting to false.

See:

PreferOrder

A prefer order lets the resolver know which assets to prefer depending on the various parameters passed to it.

Properties:
Name Type Description
priority string[]

the importance order of the params

PromiseAndParser

A promise and parser pair

Properties:
Name Type Description
parser LoaderParser

the parser that is loading the asset

promise Promise<any>

the promise that is loading the asset

ResolvedAsset

A fully resolved asset, with all the information needed to load it.

Properties:
Name Type Description
alias string[]

Aliases associated with asset

data T

Optional data

format string

Format, usually the file extension

loadParser LoadParserName

An override that will ensure that the asset is loaded with a specific parser

src string

The URL or relative path to the asset

ResolveURLParser

Format for url parser, will test a string and if it pass will then parse it, turning it into an ResolvedAsset

Properties:
Name Type Description
config Record<string, any>

A config to adjust the parser

parse (value: string) => ResolvedAsset & { [key: string]: any }

the function that will convert the url into an object

test (url: string) => boolean

the test to perform on the url to determine if it should be parsed

SpritesheetData

Atlas format.

Properties:
Name Type Description
animations Dict<string[]>

The animations of the atlas.

frames Dict<SpritesheetFrameData>

The frames of the atlas.

meta {
   app?: string,
   format?: string,
      frameTags?: {
      from: number,
      name: string,
      to: number,
      direction: string
   }[],
   image?: string,
      layers?: {
      blendMode: string,
      name: string,
      opacity: number
   }[],
   scale: number | string,
      size?: {
      h: number,
      w: number
   },
      slices?: {
      color: string,
      name: string,
         keys: {
         frame: number,
            bounds: {
            x: number,
            y: number,
            w: number,
            h: number
         }
      }[]
   }[],
   related_multi_packs?: string[],
   version?: string
}

The meta data of the atlas.

SpritesheetFrameData

Represents the JSON data for a spritesheet atlas.

Properties:
Name Type Description
anchor PointData

The anchor point of the texture.

borders TextureBorders

The 9-slice borders of the texture.

frame {
   x: number,
   y: number,
   w: number,
   h: number
}

The frame rectangle of the texture.

rotated boolean

Whether the texture is rotated.

sourceSize {
   w: number,
   h: number
}

The source size of the texture.

spriteSourceSize {
   h?: number,
   w?: number,
   x: number,
   y: number
}

The sprite source size.

trimmed boolean

Whether the texture is trimmed.

Members

cacheTextureArray readonly

Returns an object of textures from an array of textures to be cached

detectAvif readonly

Detects if the browser supports the AVIF image format.

detectDefaults readonly

Adds some default image formats to the detection parser

detectMp4 readonly

Detects if the browser supports the MP4 video format.

detectOgv readonly

Detects if the browser supports the OGV video format.

detectWebm readonly

Detects if the browser supports the WebM video format.

detectWebp readonly

Detects if the browser supports the WebP image format.

loadJson readonly

A simple loader plugin for loading json data

loadSvg readonly

A simple loader plugin for loading json data

loadTextures readonly

A simple plugin to load our textures! This makes use of imageBitmaps where available. We load the ImageBitmap on a different thread using workers if possible. We can then use the ImageBitmap as a source for a Pixi texture

You can customize the behavior of this loader by setting the config property. Which can be found here

// Set the config
import { loadTextures } from 'pixi.js';

loadTextures.config = {
   // If true we will use a worker to load the ImageBitmap
   preferWorkers: true,
   // If false we will use new Image() instead of createImageBitmap,
   // we'll also disable the use of workers as it requires createImageBitmap
   preferCreateImageBitmap: true,
   crossOrigin: 'anonymous',
};

loadTxt readonly

A simple loader plugin for loading text data

loadVideoTextures readonly

A simple plugin to load video textures.

You can pass VideoSource options to the loader via the .data property of the asset descriptor when using Asset.load().

// Set the data
const texture = await Assets.load({
    src: './assets/city.mp4',
    data: {
        preload: true,
        autoPlay: true,
    },
});

loadWebFont readonly

A loader plugin for handling web fonts

Example
 import { Assets } from 'pixi.js';

 Assets.load({
   alias: 'font',
   src: 'fonts/titan-one.woff',
   data: {
     family: 'Titan One',
     weights: ['normal', 'bold'],
   }
 })

resolveJsonUrl readonly

A parser that will resolve a json urls resolution for spritesheets e.g. assets/spritesheet@1x.json

resolveTextureUrl readonly

A parser that will resolve a texture url

spritesheetAsset AssetExtension readonly

Asset extension for loading spritesheets

Example
 import { Assets } from 'pixi.js';

 Assets.load({
     alias: 'spritesheet',
     src: 'path/to/spritesheet.json',
     data: {
         ignoreMultiPack: true,
         textureOptions: {
             scaleMode: "nearest"
         }
     }
 })

Type Definitions

AssetSrc

A valid asset src. This can be a string, or a ResolvedSrc, or an array of either.

LoadFontData

Data for loading a font

Properties:
Name Type Description
display string

A set of optional descriptors passed as an object. It can contain any of the descriptors available for @font-face:

family string

Font family name

featureSettings string

The featureSettings property of the FontFace interface retrieves or sets infrequently used font features that are not available from a font's variant properties.

stretch string

The stretch property of the FontFace interface retrieves or sets how the font stretches.

style string

The style property of the FontFace interface retrieves or sets the font's style.

unicodeRange string

The unicodeRange property of the FontFace interface retrieves or sets the range of unicode code points encompassing the font.

variant string

The variant property of the FontFace interface programmatically retrieves or sets font variant values.

weights string[]

The weight property of the FontFace interface retrieves or sets the weight of the font.

LoadParserName

Names of the parsers that are built into PixiJS. Can be any of the following defaults:

  • loadJson
  • loadSVG
  • loadTextures
  • loadTxt
  • loadVideo
  • loadWebFont or a custom parser name.

ProgressCallback

Callback for when progress on asset loading is made. The function is passed a single parameter, progress, which represents the percentage (0.0 - 1.0) of the assets loaded.

Name Type Description
progress number

The percentage (0.0 - 1.0) of the assets loaded.

Example
(progress) => console.log(progress * 100 + '%')

ResolvedSrc

A fully resolved src, Glob patterns will not work here, and the src will be resolved to a single file.

Properties:
Name Type Description
data any

Optional data

format string

Format, usually the file extension

loadParser string

An override that will ensure that the asset is loaded with a specific parser

src string

The URL or relative path to the asset

UnresolvedAsset

An asset that has not been resolved yet.

Properties:
Name Type Description
alias ArrayOr<string>

Aliases associated with asset

src AssetSrc

The URL or relative path to the asset

Methods

crossOrigin (element, url, crossorigin) void

Set cross origin based detecting the url and the crossorigin

Name Type Attributes Description
element HTMLImageElement | HTMLVideoElement

Element to apply crossOrigin

url string

URL to check

crossorigin boolean | string <optional>

Cross origin value to use

getFontFamilyName (url) string

Return font face name from a file name Ex.: 'fonts/titan-one.woff' turns into 'Titan One'

Name Type Description
url string

File url

Returns:
Type Description
string