pixi.js
Version:
<p align="center"> <a href="https://pixijs.com" target="_blank" rel="noopener noreferrer"> <img height="150" src="https://files.pixijs.download/branding/pixijs-logo-transparent-dark.svg?v=1" alt="PixiJS logo"> </a> </p> <br/> <p align="center">
45,384 lines • 1.54 MB
TypeScript
// Generated by dts-bundle-generator v9.5.1
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*/
export declare class EventEmitter<EventTypes extends EventEmitter.ValidEventTypes = string | symbol, Context extends any = any> {
static prefixed: string | boolean;
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*/
eventNames(): Array<EventEmitter.EventNames<EventTypes>>;
/**
* Return the listeners registered for a given event.
*/
listeners<T extends EventEmitter.EventNames<EventTypes>>(event: T): Array<EventEmitter.EventListener<EventTypes, T>>;
/**
* Return the number of listeners listening to a given event.
*/
listenerCount(event: EventEmitter.EventNames<EventTypes>): number;
/**
* Calls each of the listeners registered for a given event.
*/
emit<T extends EventEmitter.EventNames<EventTypes>>(event: T, ...args: EventEmitter.EventArgs<EventTypes, T>): boolean;
/**
* Add a listener for a given event.
*/
on<T extends EventEmitter.EventNames<EventTypes>>(event: T, fn: EventEmitter.EventListener<EventTypes, T>, context?: Context): this;
addListener<T extends EventEmitter.EventNames<EventTypes>>(event: T, fn: EventEmitter.EventListener<EventTypes, T>, context?: Context): this;
/**
* Add a one-time listener for a given event.
*/
once<T extends EventEmitter.EventNames<EventTypes>>(event: T, fn: EventEmitter.EventListener<EventTypes, T>, context?: Context): this;
/**
* Remove the listeners of a given event.
*/
removeListener<T extends EventEmitter.EventNames<EventTypes>>(event: T, fn?: EventEmitter.EventListener<EventTypes, T>, context?: Context, once?: boolean): this;
off<T extends EventEmitter.EventNames<EventTypes>>(event: T, fn?: EventEmitter.EventListener<EventTypes, T>, context?: Context, once?: boolean): this;
/**
* Remove all listeners, or those of the specified event.
*/
removeAllListeners(event?: EventEmitter.EventNames<EventTypes>): this;
}
export declare namespace EventEmitter {
export interface ListenerFn<Args extends any[] = any[]> {
(...args: Args): void;
}
export interface EventEmitterStatic {
new <EventTypes extends ValidEventTypes = string | symbol, Context = any>(): EventEmitter<EventTypes, Context>;
}
/**
* `object` should be in either of the following forms:
* ```
* interface EventTypes {
* 'event-with-parameters': any[]
* 'event-with-example-handler': (...args: any[]) => void
* }
* ```
*/
export type ValidEventTypes = string | symbol | object;
export type EventNames<T extends ValidEventTypes> = T extends string | symbol ? T : keyof T;
export type ArgumentMap<T extends object> = {
[K in keyof T]: T[K] extends (...args: any[]) => void ? Parameters<T[K]> : T[K] extends any[] ? T[K] : any[];
};
export type EventListener<T extends ValidEventTypes, K extends EventNames<T>> = T extends string | symbol ? (...args: any[]) => void : (...args: ArgumentMap<Exclude<T, string | symbol>>[Extract<K, keyof T>]) => void;
export type EventArgs<T extends ValidEventTypes, K extends EventNames<T>> = Parameters<EventListener<T, K>>;
export const EventEmitter: EventEmitterStatic;
}
declare type RgbColor = {
r: number;
g: number;
b: number;
};
declare type HslColor = {
h: number;
s: number;
l: number;
};
declare type HsvColor = {
h: number;
s: number;
v: number;
};
declare type WithAlpha<O> = O & {
a: number;
};
declare type RgbaColor = WithAlpha<RgbColor>;
declare type HslaColor = WithAlpha<HslColor>;
declare type HsvaColor = WithAlpha<HsvColor>;
/**
* Array of RGBA color components, where each component is a number between 0 and 1.
* The array must contain exactly 4 numbers in the order: red, green, blue, alpha.
* @example
* ```ts
* // Full white (opaque)
* const white: RgbaArray = [1, 1, 1, 1];
*
* // Semi-transparent red
* const transparentRed: RgbaArray = [1, 0, 0, 0.5];
* ```
* @remarks
* - All components must be between 0 and 1
* - Array must contain exactly 4 values
* - Order is [red, green, blue, alpha]
* @see {@link Color} For the main color utility class
* @category color
* @standard
*/
export type RgbaArray = [
number,
number,
number,
number
];
/**
* Valid color formats supported by PixiJS. These types extend from [colord](https://www.npmjs.com/package/colord)
* with additional PixiJS-specific formats.
*
* Common Formats:
* ```ts
* // CSS Color Names
* new Color('red');
* new Color('blue');
* new Color('green');
*
* // Hex Values
* new Color(0xff0000); // RGB integer
* new Color('#ff0000'); // 6-digit hex
* new Color('#f00'); // 3-digit hex
* new Color('#ff0000ff'); // 8-digit hex (with alpha)
* new Color('#f00f'); // 4-digit hex (with alpha)
*
* // RGB/RGBA Objects
* new Color({ r: 255, g: 0, b: 0 });
* new Color({ r: 255, g: 0, b: 0, a: 0.5 });
*
* // RGB/RGBA Strings
* new Color('rgb(255, 0, 0)');
* new Color('rgba(255, 0, 0, 0.5)');
* new Color('rgb(100% 0% 0%)');
* new Color('rgba(100% 0% 0% / 50%)');
*
* // Arrays (normalized 0-1)
* new Color([1, 0, 0]); // RGB
* new Color([1, 0, 0, 0.5]); // RGBA
* new Color(new Float32Array([1, 0, 0, 0.5]));
*
* // Arrays (0-255)
* new Color(new Uint8Array([255, 0, 0]));
* new Color(new Uint8ClampedArray([255, 0, 0, 128]));
*
* // HSL/HSLA
* new Color({ h: 0, s: 100, l: 50 });
* new Color({ h: 0, s: 100, l: 50, a: 0.5 });
* new Color('hsl(0, 100%, 50%)');
* new Color('hsla(0deg 100% 50% / 50%)');
*
* // HSV/HSVA
* new Color({ h: 0, s: 100, v: 100 });
* new Color({ h: 0, s: 100, v: 100, a: 0.5 });
* ```
* @remarks
* - All color values are normalized internally to 0-1 range
* - Alpha is always between 0-1
* - Invalid colors will throw an error
* - Original format is preserved when possible
* @see {@link Color} For the main color utility class
* @see {@link https://www.w3.org/TR/css-color-4} CSS Color Level 4 Specification
* @since 7.2.0
* @category color
* @standard
*/
export type ColorSource = string | number | number[] | Float32Array | Uint8Array | Uint8ClampedArray | HslColor | HslaColor | HsvColor | HsvaColor | RgbColor | RgbaColor | Color | number;
/**
* Color utility class for managing colors in various formats. Provides a unified way to work
* with colors across your PixiJS application.
*
* Features:
* - Accepts multiple color formats (hex, RGB, HSL, etc.)
* - Automatic format conversion
* - Color manipulation methods
* - Component access (r,g,b,a)
* - Chainable operations
* @example
* ```js
* import { Color } from 'pixi.js';
*
* new Color('red').toArray(); // [1, 0, 0, 1]
* new Color(0xff0000).toArray(); // [1, 0, 0, 1]
* new Color('ff0000').toArray(); // [1, 0, 0, 1]
* new Color('#f00').toArray(); // [1, 0, 0, 1]
* new Color('0xff0000ff').toArray(); // [1, 0, 0, 1]
* new Color('#f00f').toArray(); // [1, 0, 0, 1]
* new Color({ r: 255, g: 0, b: 0, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]
* new Color('rgb(255, 0, 0, 0.5)').toArray(); // [1, 0, 0, 0.5]
* new Color([1, 1, 1]).toArray(); // [1, 1, 1, 1]
* new Color([1, 0, 0, 0.5]).toArray(); // [1, 0, 0, 0.5]
* new Color(new Float32Array([1, 0, 0, 0.5])).toArray(); // [1, 0, 0, 0.5]
* new Color(new Uint8Array([255, 0, 0, 255])).toArray(); // [1, 0, 0, 1]
* new Color(new Uint8ClampedArray([255, 0, 0, 255])).toArray(); // [1, 0, 0, 1]
* new Color({ h: 0, s: 100, l: 50, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]
* new Color('hsl(0, 100%, 50%, 50%)').toArray(); // [1, 0, 0, 0.5]
* new Color({ h: 0, s: 100, v: 100, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]
*
* // Convert between formats
* const color = new Color('red');
* color.toHex(); // "#ff0000"
* color.toRgbString(); // "rgb(255,0,0,1)"
* color.toNumber(); // 0xff0000
*
* // Access components
* color.red; // 1
* color.green; // 0
* color.blue; // 0
* color.alpha; // 1
*
* // Chain operations
* color
* .setAlpha(0.5)
* .multiply([0.5, 0.5, 0.5])
* .premultiply(0.8);
* ```
* @remarks
* The Color class automatically normalizes all color values internally:
* - RGB components are stored as floats between 0-1
* - Alpha is always between 0-1
* - Color operations clamp values to valid ranges
* - Original input format is preserved when possible
* @since 7.2.0
* @category color
* @standard
*/
export declare class Color {
/**
* Static shared Color instance used for utility operations. This is a singleton color object
* that can be reused to avoid creating unnecessary Color instances.
* > [!IMPORTANT] You should be careful when using this shared instance, as it is mutable and can be
* > changed by any code that uses it.
* >
* > It is best used for one-off color operations or temporary transformations.
* > For persistent colors, create your own Color instance instead.
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Use shared instance for one-off color operations
* Color.shared.setValue(0xff0000);
* const redHex = Color.shared.toHex(); // "#ff0000"
* const redRgb = Color.shared.toRgbArray(); // [1, 0, 0]
*
* // Temporary color transformations
* const colorNumber = Color.shared
* .setValue('#ff0000') // Set to red
* .setAlpha(0.5) // Make semi-transparent
* .premultiply(0.8) // Apply premultiplication
* .toNumber(); // Convert to number
*
* // Chain multiple operations
* const result = Color.shared
* .setValue(someColor)
* .multiply(tintColor)
* .toPremultiplied(alpha);
* ```
* @remarks
* - This is a shared instance - be careful about multiple code paths using it simultaneously
* - Use for temporary color operations to avoid allocating new Color instances
* - The value is preserved between operations, so reset if needed
* - For persistent colors, create your own Color instance instead
*/
static readonly shared: Color;
/**
* Temporary Color object for static uses internally.
* As to not conflict with Color.shared.
* @ignore
*/
private static readonly _temp;
/** Pattern for hex strings */
private static readonly HEX_PATTERN;
/** Internal color source, from constructor or set value */
private _value;
/** Normalized rgba component, floats from 0-1 */
private _components;
/** Cache color as number */
private _int;
/** An array of the current Color. Only populated when `toArray` functions are called */
private _arrayRgba;
private _arrayRgb;
/**
* @param {ColorSource} value - Optional value to use, if not provided, white is used.
*/
constructor(value?: ColorSource);
/**
* Get the red component of the color, normalized between 0 and 1.
* @example
* ```ts
* const color = new Color('red');
* console.log(color.red); // 1
*
* const green = new Color('#00ff00');
* console.log(green.red); // 0
* ```
*/
get red(): number;
/**
* Get the green component of the color, normalized between 0 and 1.
* @example
* ```ts
* const color = new Color('lime');
* console.log(color.green); // 1
*
* const red = new Color('#ff0000');
* console.log(red.green); // 0
* ```
*/
get green(): number;
/**
* Get the blue component of the color, normalized between 0 and 1.
* @example
* ```ts
* const color = new Color('blue');
* console.log(color.blue); // 1
*
* const yellow = new Color('#ffff00');
* console.log(yellow.blue); // 0
* ```
*/
get blue(): number;
/**
* Get the alpha component of the color, normalized between 0 and 1.
* @example
* ```ts
* const color = new Color('red');
* console.log(color.alpha); // 1 (fully opaque)
*
* const transparent = new Color('rgba(255, 0, 0, 0.5)');
* console.log(transparent.alpha); // 0.5 (semi-transparent)
* ```
*/
get alpha(): number;
/**
* Sets the color value and returns the instance for chaining.
*
* This is a chainable version of setting the `value` property.
* @param value - The color to set. Accepts various formats:
* - Hex strings/numbers (e.g., '#ff0000', 0xff0000)
* - RGB/RGBA values (arrays, objects)
* - CSS color names
* - HSL/HSLA values
* - HSV/HSVA values
* @returns The Color instance for chaining
* @example
* ```ts
* // Basic usage
* const color = new Color();
* color.setValue('#ff0000')
* .setAlpha(0.5)
* .premultiply(0.8);
*
* // Different formats
* color.setValue(0xff0000); // Hex number
* color.setValue('#ff0000'); // Hex string
* color.setValue([1, 0, 0]); // RGB array
* color.setValue([1, 0, 0, 0.5]); // RGBA array
* color.setValue({ r: 1, g: 0, b: 0 }); // RGB object
*
* // Copy from another color
* const red = new Color('red');
* color.setValue(red);
* ```
* @throws {Error} If the color value is invalid or null
* @see {@link Color.value} For the underlying value property
*/
setValue(value: ColorSource): this;
/**
* The current color source. This property allows getting and setting the color value
* while preserving the original format where possible.
* @remarks
* When setting:
* - Setting to a `Color` instance copies its source and components
* - Setting to other valid sources normalizes and stores the value
* - Setting to `null` throws an Error
* - The color remains unchanged if normalization fails
*
* When getting:
* - Returns `null` if color was modified by {@link Color.multiply} or {@link Color.premultiply}
* - Otherwise returns the original color source
* @example
* ```ts
* // Setting different color formats
* const color = new Color();
*
* color.value = 0xff0000; // Hex number
* color.value = '#ff0000'; // Hex string
* color.value = [1, 0, 0]; // RGB array
* color.value = [1, 0, 0, 0.5]; // RGBA array
* color.value = { r: 1, g: 0, b: 0 }; // RGB object
*
* // Copying from another color
* const red = new Color('red');
* color.value = red; // Copies red's components
*
* // Getting the value
* console.log(color.value); // Returns original format
*
* // After modifications
* color.multiply([0.5, 0.5, 0.5]);
* console.log(color.value); // Returns null
* ```
* @throws {Error} When attempting to set `null`
*/
set value(value: ColorSource | null);
get value(): Exclude<ColorSource, Color> | null;
/**
* Copy a color source internally.
* @param value - Color source
*/
private _cloneSource;
/**
* Equality check for color sources.
* @param value1 - First color source
* @param value2 - Second color source
* @returns `true` if the color sources are equal, `false` otherwise.
*/
private _isSourceEqual;
/**
* Convert to a RGBA color object with normalized components (0-1).
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Convert colors to RGBA objects
* new Color('white').toRgba(); // returns { r: 1, g: 1, b: 1, a: 1 }
* new Color('#ff0000').toRgba(); // returns { r: 1, g: 0, b: 0, a: 1 }
*
* // With transparency
* new Color('rgba(255,0,0,0.5)').toRgba(); // returns { r: 1, g: 0, b: 0, a: 0.5 }
* ```
* @returns An RGBA object with normalized components
*/
toRgba(): RgbaColor;
/**
* Convert to a RGB color object with normalized components (0-1).
*
* Alpha component is omitted in the output.
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Convert colors to RGB objects
* new Color('white').toRgb(); // returns { r: 1, g: 1, b: 1 }
* new Color('#ff0000').toRgb(); // returns { r: 1, g: 0, b: 0 }
*
* // Alpha is ignored
* new Color('rgba(255,0,0,0.5)').toRgb(); // returns { r: 1, g: 0, b: 0 }
* ```
* @returns An RGB object with normalized components
*/
toRgb(): RgbColor;
/**
* Convert to a CSS-style rgba string representation.
*
* RGB components are scaled to 0-255 range, alpha remains 0-1.
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Convert colors to RGBA strings
* new Color('white').toRgbaString(); // returns "rgba(255,255,255,1)"
* new Color('#ff0000').toRgbaString(); // returns "rgba(255,0,0,1)"
*
* // With transparency
* new Color([1, 0, 0, 0.5]).toRgbaString(); // returns "rgba(255,0,0,0.5)"
* ```
* @returns A CSS-compatible rgba string
*/
toRgbaString(): string;
/**
* Convert to an [R, G, B] array of clamped uint8 values (0 to 255).
* @param {number[]|Uint8Array|Uint8ClampedArray} [out] - Optional output array. If not provided,
* a cached array will be used and returned.
* @returns Array containing RGB components as integers between 0-255
* @example
* ```ts
* // Basic usage
* new Color('white').toUint8RgbArray(); // returns [255, 255, 255]
* new Color('#ff0000').toUint8RgbArray(); // returns [255, 0, 0]
*
* // Using custom output array
* const rgb = new Uint8Array(3);
* new Color('blue').toUint8RgbArray(rgb); // rgb is now [0, 0, 255]
*
* // Using different array types
* new Color('red').toUint8RgbArray(new Uint8ClampedArray(3)); // [255, 0, 0]
* new Color('red').toUint8RgbArray([]); // [255, 0, 0]
* ```
* @remarks
* - Output values are always clamped between 0-255
* - Alpha component is not included in output
* - Reuses internal cache array if no output array provided
*/
toUint8RgbArray<T extends number[] | Uint8Array | Uint8ClampedArray = number[]>(out?: T): T;
/**
* Convert to an [R, G, B, A] array of normalized floats (numbers from 0.0 to 1.0).
* @param {number[]|Float32Array} [out] - Optional output array. If not provided,
* a cached array will be used and returned.
* @returns Array containing RGBA components as floats between 0-1
* @example
* ```ts
* // Basic usage
* new Color('white').toArray(); // returns [1, 1, 1, 1]
* new Color('red').toArray(); // returns [1, 0, 0, 1]
*
* // With alpha
* new Color('rgba(255,0,0,0.5)').toArray(); // returns [1, 0, 0, 0.5]
*
* // Using custom output array
* const rgba = new Float32Array(4);
* new Color('blue').toArray(rgba); // rgba is now [0, 0, 1, 1]
* ```
* @remarks
* - Output values are normalized between 0-1
* - Includes alpha component as the fourth value
* - Reuses internal cache array if no output array provided
*/
toArray<T extends number[] | Float32Array = number[]>(out?: T): T;
/**
* Convert to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0).
* @param {number[]|Float32Array} [out] - Optional output array. If not provided,
* a cached array will be used and returned.
* @returns Array containing RGB components as floats between 0-1
* @example
* ```ts
* // Basic usage
* new Color('white').toRgbArray(); // returns [1, 1, 1]
* new Color('red').toRgbArray(); // returns [1, 0, 0]
*
* // Using custom output array
* const rgb = new Float32Array(3);
* new Color('blue').toRgbArray(rgb); // rgb is now [0, 0, 1]
* ```
* @remarks
* - Output values are normalized between 0-1
* - Alpha component is omitted from output
* - Reuses internal cache array if no output array provided
*/
toRgbArray<T extends number[] | Float32Array = number[]>(out?: T): T;
/**
* Convert to a hexadecimal number.
* @returns The color as a 24-bit RGB integer
* @example
* ```ts
* // Basic usage
* new Color('white').toNumber(); // returns 0xffffff
* new Color('red').toNumber(); // returns 0xff0000
*
* // Store as hex
* const color = new Color('blue');
* const hex = color.toNumber(); // 0x0000ff
* ```
*/
toNumber(): number;
/**
* Convert to a BGR number.
*
* Useful for platforms that expect colors in BGR format.
* @returns The color as a 24-bit BGR integer
* @example
* ```ts
* // Convert RGB to BGR
* new Color(0xffcc99).toBgrNumber(); // returns 0x99ccff
*
* // Common use case: platform-specific color format
* const color = new Color('orange');
* const bgrColor = color.toBgrNumber(); // Color with swapped R/B channels
* ```
* @remarks
* This swaps the red and blue channels compared to the normal RGB format:
* - RGB 0xRRGGBB becomes BGR 0xBBGGRR
*/
toBgrNumber(): number;
/**
* Convert to a hexadecimal number in little endian format (e.g., BBGGRR).
*
* Useful for platforms that expect colors in little endian byte order.
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Convert RGB color to little endian format
* new Color(0xffcc99).toLittleEndianNumber(); // returns 0x99ccff
*
* // Common use cases:
* const color = new Color('orange');
* const leColor = color.toLittleEndianNumber(); // Swaps byte order for LE systems
*
* // Multiple conversions
* const colors = {
* normal: 0xffcc99,
* littleEndian: new Color(0xffcc99).toLittleEndianNumber(), // 0x99ccff
* backToNormal: new Color(0x99ccff).toLittleEndianNumber() // 0xffcc99
* };
* ```
* @remarks
* - Swaps R and B channels in the color value
* - RGB 0xRRGGBB becomes 0xBBGGRR
* - Useful for systems that use little endian byte order
* - Can be used to convert back and forth between formats
* @returns The color as a number in little endian format (BBGGRR)
* @see {@link Color.toBgrNumber} For BGR format without byte swapping
*/
toLittleEndianNumber(): number;
/**
* Multiply with another color.
*
* This action is destructive and modifies the original color.
* @param {ColorSource} value - The color to multiply by. Accepts any valid color format:
* - Hex strings/numbers (e.g., '#ff0000', 0xff0000)
* - RGB/RGBA arrays ([1, 0, 0], [1, 0, 0, 1])
* - Color objects ({ r: 1, g: 0, b: 0 })
* - CSS color names ('red', 'blue')
* @returns this - The Color instance for chaining
* @example
* ```ts
* // Basic multiplication
* const color = new Color('#ff0000');
* color.multiply(0x808080); // 50% darker red
*
* // With transparency
* color.multiply([1, 1, 1, 0.5]); // 50% transparent
*
* // Chain operations
* color
* .multiply('#808080')
* .multiply({ r: 1, g: 1, b: 1, a: 0.5 });
* ```
* @remarks
* - Multiplies each RGB component and alpha separately
* - Values are clamped between 0-1
* - Original color format is lost (value becomes null)
* - Operation cannot be undone
*/
multiply(value: ColorSource): this;
/**
* Converts color to a premultiplied alpha format.
*
* This action is destructive and modifies the original color.
* @param alpha - The alpha value to multiply by (0-1)
* @param {boolean} [applyToRGB=true] - Whether to premultiply RGB channels
* @returns {Color} The Color instance for chaining
* @example
* ```ts
* // Basic premultiplication
* const color = new Color('red');
* color.premultiply(0.5); // 50% transparent red with premultiplied RGB
*
* // Alpha only (RGB unchanged)
* color.premultiply(0.5, false); // 50% transparent, original RGB
*
* // Chain with other operations
* color
* .multiply(0x808080)
* .premultiply(0.5)
* .toNumber();
* ```
* @remarks
* - RGB channels are multiplied by alpha when applyToRGB is true
* - Alpha is always set to the provided value
* - Values are clamped between 0-1
* - Original color format is lost (value becomes null)
* - Operation cannot be undone
*/
premultiply(alpha: number, applyToRGB?: boolean): this;
/**
* Returns the color as a 32-bit premultiplied alpha integer.
*
* Format: 0xAARRGGBB
* @param {number} alpha - The alpha value to multiply by (0-1)
* @param {boolean} [applyToRGB=true] - Whether to premultiply RGB channels
* @returns {number} The premultiplied color as a 32-bit integer
* @example
* ```ts
* // Convert to premultiplied format
* const color = new Color('red');
*
* // Full opacity (0xFFRRGGBB)
* color.toPremultiplied(1.0); // 0xFFFF0000
*
* // 50% transparency with premultiplied RGB
* color.toPremultiplied(0.5); // 0x7F7F0000
*
* // 50% transparency without RGB premultiplication
* color.toPremultiplied(0.5, false); // 0x7FFF0000
* ```
* @remarks
* - Returns full opacity (0xFF000000) when alpha is 1.0
* - Returns 0 when alpha is 0.0 and applyToRGB is true
* - RGB values are rounded during premultiplication
*/
toPremultiplied(alpha: number, applyToRGB?: boolean): number;
/**
* Convert to a hexadecimal string (6 characters).
* @returns A CSS-compatible hex color string (e.g., "#ff0000")
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Basic colors
* new Color('red').toHex(); // returns "#ff0000"
* new Color('white').toHex(); // returns "#ffffff"
* new Color('black').toHex(); // returns "#000000"
*
* // From different formats
* new Color(0xff0000).toHex(); // returns "#ff0000"
* new Color([1, 0, 0]).toHex(); // returns "#ff0000"
* new Color({ r: 1, g: 0, b: 0 }).toHex(); // returns "#ff0000"
* ```
* @remarks
* - Always returns a 6-character hex string
* - Includes leading "#" character
* - Alpha channel is ignored
* - Values are rounded to nearest hex value
*/
toHex(): string;
/**
* Convert to a hexadecimal string with alpha (8 characters).
* @returns A CSS-compatible hex color string with alpha (e.g., "#ff0000ff")
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // Fully opaque colors
* new Color('red').toHexa(); // returns "#ff0000ff"
* new Color('white').toHexa(); // returns "#ffffffff"
*
* // With transparency
* new Color('rgba(255, 0, 0, 0.5)').toHexa(); // returns "#ff00007f"
* new Color([1, 0, 0, 0]).toHexa(); // returns "#ff000000"
* ```
* @remarks
* - Returns an 8-character hex string
* - Includes leading "#" character
* - Alpha is encoded in last two characters
* - Values are rounded to nearest hex value
*/
toHexa(): string;
/**
* Set alpha (transparency) value while preserving color components.
*
* Provides a chainable interface for setting alpha.
* @param alpha - Alpha value between 0 (fully transparent) and 1 (fully opaque)
* @returns The Color instance for chaining
* @example
* ```ts
* // Basic alpha setting
* const color = new Color('red');
* color.setAlpha(0.5); // 50% transparent red
*
* // Chain with other operations
* color
* .setValue('#ff0000')
* .setAlpha(0.8) // 80% opaque
* .premultiply(0.5); // Further modify alpha
*
* // Reset to fully opaque
* color.setAlpha(1);
* ```
* @remarks
* - Alpha value is clamped between 0-1
* - Can be chained with other color operations
*/
setAlpha(alpha: number): this;
/**
* Normalize the input value into rgba
* @param value - Input value
*/
private _normalize;
/** Refresh the internal color rgb number */
private _refreshInt;
/**
* Clamps values to a range. Will override original values
* @param value - Value(s) to clamp
* @param min - Minimum value
* @param max - Maximum value
*/
private _clamp;
/**
* Check if a value can be interpreted as a valid color format.
* Supports all color formats that can be used with the Color class.
* @param value - Value to check
* @returns True if the value can be used as a color
* @example
* ```ts
* import { Color } from 'pixi.js';
*
* // CSS colors and hex values
* Color.isColorLike('red'); // true
* Color.isColorLike('#ff0000'); // true
* Color.isColorLike(0xff0000); // true
*
* // Arrays (RGB/RGBA)
* Color.isColorLike([1, 0, 0]); // true
* Color.isColorLike([1, 0, 0, 0.5]); // true
*
* // TypedArrays
* Color.isColorLike(new Float32Array([1, 0, 0])); // true
* Color.isColorLike(new Uint8Array([255, 0, 0])); // true
* Color.isColorLike(new Uint8ClampedArray([255, 0, 0])); // true
*
* // Object formats
* Color.isColorLike({ r: 1, g: 0, b: 0 }); // true (RGB)
* Color.isColorLike({ r: 1, g: 0, b: 0, a: 0.5 }); // true (RGBA)
* Color.isColorLike({ h: 0, s: 100, l: 50 }); // true (HSL)
* Color.isColorLike({ h: 0, s: 100, l: 50, a: 0.5 }); // true (HSLA)
* Color.isColorLike({ h: 0, s: 100, v: 100 }); // true (HSV)
* Color.isColorLike({ h: 0, s: 100, v: 100, a: 0.5 });// true (HSVA)
*
* // Color instances
* Color.isColorLike(new Color('red')); // true
*
* // Invalid values
* Color.isColorLike(null); // false
* Color.isColorLike(undefined); // false
* Color.isColorLike({}); // false
* Color.isColorLike([]); // false
* Color.isColorLike('not-a-color'); // false
* ```
* @remarks
* Checks for the following formats:
* - Numbers (0x000000 to 0xffffff)
* - CSS color strings
* - RGB/RGBA arrays and objects
* - HSL/HSLA objects
* - HSV/HSVA objects
* - TypedArrays (Float32Array, Uint8Array, Uint8ClampedArray)
* - Color instances
* @see {@link ColorSource} For supported color format types
* @see {@link Color.setValue} For setting color values
* @category utility
*/
static isColorLike(value: unknown): value is ColorSource;
}
/**
* Common interface for points. Both Point and ObservablePoint implement it.
* Provides a standard way to represent 2D coordinates.
*
* Many PixiJS methods accept PointData for transformations,
* making it easy to work with different point types interchangeably.
* @example
* ```ts
* // Create an object implementing PointData
* const point: PointData = { x: 100, y: 200 };
*
* // Use with matrix transformations
* const matrix = new Matrix();
* matrix.translate(50, 50).apply(point);
*
* // Mix with other point types
* const observablePoint = new ObservablePoint(() => {}, null, 0, 0);
* const regularPoint = new Point(0, 0);
* // All are PointData compatible
* ```
* @remarks
* - Basic x,y coordinate interface
* - Used by Point and ObservablePoint
* @see {@link Point} For standard point implementation
* @see {@link ObservablePoint} For observable point implementation
* @category maths
* @standard
*/
export interface PointData {
/** X coordinate */
x: number;
/** Y coordinate */
y: number;
}
/**
* Common interface for points with manipulation methods.
*
* Extends PointData to add operations for copying, comparison and setting values.
* @example
* ```ts
* // Basic point manipulation
* const point: PointLike = new Point(10, 20);
* point.set(30, 40);
*
* // Copy between points
* const other = new Point();
* point.copyTo(other);
*
* // Compare points
* const same = point.equals(other); // true
* ```
* @see {@link PointData} For basic x,y interface
* @see {@link Point} For standard implementation
* @see {@link ObservablePoint} For observable implementation
* @category maths
* @standard
*/
export interface PointLike extends PointData {
/**
* Copies x and y from the given point
* @param {PointData} p - The point to copy from
* @returns {this} Returns itself.
* @example
* ```ts
* const point1: PointLike = new Point(10, 20);
* const point2: PointLike = new Point(30, 40);
* point1.copyFrom(point2);
* console.log(point1.x, point1.y); // 30, 40
* ```
*/
copyFrom: (p: PointData) => this;
/**
* Copies x and y into the given point
* @param {PointLike} p - The point to copy.
* @returns {PointLike} Given point with values updated
* @example
* ```ts
* const point1: PointLike = new Point(10, 20);
* const point2: PointLike = new Point(0, 0);
* point1.copyTo(point2);
* console.log(point2.x, point2.y); // 10, 20
* ```
*/
copyTo: <T extends PointLike>(p: T) => T;
/**
* Returns true if the given point is equal to this point
* @param {PointData} p - The point to check
* @returns {boolean} Whether the given point equal to this point
* @example
* ```ts
* const point1: PointLike = new Point(10, 20);
* const point2: PointLike = new Point(10, 20);
* const point3: PointLike = new Point(30, 40);
* console.log(point1.equals(point2)); // true
* console.log(point1.equals(point3)); // false
* ```
*/
equals: (p: PointData) => boolean;
/**
* Sets the point to a new x and y position.
* If y is omitted, both x and y will be set to x.
* @param {number} [x=0] - position of the point on the x axis
* @param {number} [y=x] - position of the point on the y axis
* @example
* ```ts
* const point: PointLike = new Point(10, 20);
* point.set(30, 40);
* console.log(point.x, point.y); // 30, 40
* point.set(50); // Sets both x and y to 50
* console.log(point.x, point.y); // 50, 50
* ```
*/
set: (x?: number, y?: number) => void;
}
export interface Point extends PixiMixins.Point {
}
/**
* The Point object represents a location in a two-dimensional coordinate system, where `x` represents
* the position on the horizontal axis and `y` represents the position on the vertical axis.
*
* Many Pixi functions accept the `PointData` type as an alternative to `Point`,
* which only requires `x` and `y` properties.
* @example
* ```ts
* // Basic point creation
* const point = new Point(100, 200);
*
* // Using with transformations
* const matrix = new Matrix();
* matrix.translate(50, 50).apply(point);
*
* // Point arithmetic
* const start = new Point(0, 0);
* const end = new Point(100, 100);
* const middle = new Point(
* (start.x + end.x) / 2,
* (start.y + end.y) / 2
* );
* ```
* @see {@link PointData} For basic x,y interface
* @see {@link PointLike} For point manipulation interface
* @see {@link ObservablePoint} For observable version
* @category maths
* @standard
*/
export declare class Point implements PointLike {
/**
* Position of the point on the x axis
* @example
* ```ts
* // Set x position
* const point = new Point();
* point.x = 100;
*
* // Use in calculations
* const width = rightPoint.x - leftPoint.x;
* ```
*/
x: number;
/**
* Position of the point on the y axis
* @example
* ```ts
* // Set y position
* const point = new Point();
* point.y = 200;
*
* // Use in calculations
* const height = bottomPoint.y - topPoint.y;
* ```
*/
y: number;
/**
* Creates a new `Point`
* @param {number} [x=0] - position of the point on the x axis
* @param {number} [y=0] - position of the point on the y axis
*/
constructor(x?: number, y?: number);
/**
* Creates a clone of this point, which is a new instance with the same `x` and `y` values.
* @example
* ```ts
* // Basic point cloning
* const original = new Point(100, 200);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.set(300, 400);
*
* // Verify independence
* console.log(original); // Point(100, 200)
* console.log(modified); // Point(300, 400)
* ```
* @remarks
* - Creates new Point instance
* - Deep copies x and y values
* - Independent from original
* - Useful for preserving values
* @returns A clone of this point
* @see {@link Point.copyFrom} For copying into existing point
* @see {@link Point.copyTo} For copying to existing point
*/
clone(): Point;
/**
* Copies x and y from the given point into this point.
* @example
* ```ts
* // Basic copying
* const source = new Point(100, 200);
* const target = new Point();
* target.copyFrom(source);
*
* // Copy and chain operations
* const point = new Point()
* .copyFrom(source)
* .set(x + 50, y + 50);
*
* // Copy from any PointData
* const data = { x: 10, y: 20 };
* point.copyFrom(data);
* ```
* @param p - The point to copy from
* @returns The point instance itself
* @see {@link Point.copyTo} For copying to another point
* @see {@link Point.clone} For creating new point copy
*/
copyFrom(p: PointData): this;
/**
* Copies this point's x and y into the given point.
* @example
* ```ts
* // Basic copying
* const source = new Point(100, 200);
* const target = new Point();
* source.copyTo(target);
* ```
* @param p - The point to copy to. Can be any type that is or extends `PointLike`
* @returns The point (`p`) with values updated
* @see {@link Point.copyFrom} For copying from another point
* @see {@link Point.clone} For creating new point copy
*/
copyTo<T extends PointLike>(p: T): T;
/**
* Checks if another point is equal to this point.
*
* Compares x and y values using strict equality.
* @example
* ```ts
* // Basic equality check
* const p1 = new Point(100, 200);
* const p2 = new Point(100, 200);
* console.log(p1.equals(p2)); // true
*
* // Compare with PointData
* const data = { x: 100, y: 200 };
* console.log(p1.equals(data)); // true
*
* // Check different points
* const p3 = new Point(200, 300);
* console.log(p1.equals(p3)); // false
* ```
* @param p - The point to check
* @returns `true` if both `x` and `y` are equal
* @see {@link Point.copyFrom} For making points equal
* @see {@link PointData} For point data interface
*/
equals(p: PointData): boolean;
/**
* Sets the point to a new x and y position.
*
* If y is omitted, both x and y will be set to x.
* @example
* ```ts
* // Basic position setting
* const point = new Point();
* point.set(100, 200);
*
* // Set both x and y to same value
* point.set(50); // x=50, y=50
*
* // Chain with other operations
* point
* .set(10, 20)
* .copyTo(otherPoint);
* ```
* @param x - Position on the x axis
* @param y - Position on the y axis, defaults to x
* @returns The point instance itself
* @see {@link Point.copyFrom} For copying from another point
* @see {@link Point.equals} For comparing positions
*/
set(x?: number, y?: number): this;
toString(): string;
/**
* A static Point object with `x` and `y` values of `0`.
*
* This shared instance is reset to zero values when accessed.
*
* > [!IMPORTANT] This point is shared and temporary. Do not store references to it.
* @example
* ```ts
* // Use for temporary calculations
* const tempPoint = Point.shared;
* tempPoint.set(100, 200);
* matrix.apply(tempPoint);
*
* // Will be reset to (0,0) on next access
* const fresh = Point.shared; // x=0, y=0
* ```
* @readonly
* @returns A fresh zeroed point for temporary use
* @see {@link Point.constructor} For creating new points
* @see {@link PointData} For basic point interface
*/
static get shared(): Point;
}
/**
* The data structure that contains the position, scale, pivot, skew and rotation of an object.
* This is used by the {@link Matrix} class to decompose the matrix into its components.
* @category maths
* @advanced
*/
export interface TransformableObject {
/** The position of the object */
position: PointData;
/** The scale of the object */
scale: PointData;
/** The pivot of the object */
pivot: PointData;
/** The skew of the object */
skew: PointData;
/** The rotation of the object */
rotation: number;
}
/**
* A fast matrix for 2D transformations.
* Represents a 3x3 transformation matrix:
*
* ```js
* | a c tx |
* | b d ty |
* | 0 0 1 |
* ```
* @example
* ```ts
* // Create identity matrix
* const matrix = new Matrix();
*
* // Create matrix with custom values
* const transform = new Matrix(2, 0, 0, 2, 100, 100); // Scale 2x, translate 100,100
*
* // Transform a point
* const point = { x: 10, y: 20 };
* const transformed = transform.apply(point);
*
* // Chain transformations
* matrix
* .translate(100, 50)
* .rotate(Math.PI / 4)
* .scale(2, 2);
* ```
* @remarks
* - Used for transform hierarchies
* - Supports scale, rotation, position
* - Can be concatenated with append/prepend
* - Efficient for batched transformations
* @category maths
* @standard
*/
export declare class Matrix {
/**
* Scale on the x axis.
* @default 1
*/
a: number;
/**
* Shear on the y axis.
* @default 0
*/
b: number;
/**
* Shear on the x axis.
* @default 0
*/
c: number;
/**
* Scale on the y axis.
* @default 1
*/
d: number;
/**
* Translation on the x axis.
* @default 0
*/
tx: number;
/**
* Translation on the y axis.
* @default 0
*/
ty: number;
/**
* Array representation of the matrix.
* Only populated when `toArray()` is called.
* @default null
* @see {@link Matrix.toArray} For filling this array
*/
array: Float32Array | null;
/**
* @param a - x scale
* @param b - y skew
* @param c - x skew
* @param d - y scale
* @param tx - x translation
* @param ty - y translation
*/
constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number);
/**
* Creates a Matrix object based on the given array.
* Populates matrix components from a flat array in column-major order.
*
* > [!NOTE] Array mapping order:
* > ```
* > array[0] = a (x scale)
* > array[1] = b (y skew)
* > array[2] = tx (x translation)
* > array[3] = c (x skew)
* > array[4] = d (y scale)
* > array[5] = ty (y translation)
* > ```
* @example
* ```ts
* // Create matrix from array
* const matrix = new Matrix();
* matrix.fromArray([
* 2, 0, 100, // a, b, tx
* 0, 2, 100 // c, d, ty
* ]);
*
* // Create matrix from typed array
* const float32Array = new Float32Array([
* 1, 0, 0, // Scale x1, no skew
* 0, 1, 0 // No skew, scale x1
* ]);
* matrix.fromArray(float32Array);
* ```
* @param array - The array to populate the matrix from
* @see {@link Matrix.toArray} For converting matrix to array
* @see {@link Matrix.set} For setting values directly
*/
fromArray(array: number[]): void;
/**
* Sets the matrix properties directly.
* All matrix components can be set in one call.
* @example
* ```ts
* // Set to identity matrix
* matrix.set(1, 0, 0, 1, 0, 0);
*
* // Set to scale matrix
* matrix.set(2, 0, 0, 2, 0, 0); // Scale 2x
*
* // Set to translation matrix
* matrix.set(1, 0, 0, 1, 100, 50); // Move 100,50
* ```
* @param a - Scale on x axis
* @param b - Shear on y axis
* @param c - Shear on x axis
* @param d - Scale on y axis
* @param tx - Translation on x axis
* @param ty - Translation on y axis
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.identity} For resetting to identity
* @see {@link Matrix.fromArray} For setting from array
*/
set(a: number, b: number, c: number, d: number, tx: number, ty: number): this;
/**
* Creates an array from the current Matrix object.
*
* > [!NOTE] The array format is:
* > ```
* > Non-transposed:
* > [a, c, tx,
* > b, d, ty,
* > 0, 0, 1]
* >
* > Transposed:
* > [a, b, 0,
* > c, d, 0,
* > tx,ty,1]
* > ```
* @example
* ```ts
* // Basic array conversion
* const matrix = new Matrix(2, 0, 0, 2, 100, 100);
* const array = matrix.toArray();
*
* // Using existing array
* const float32Array = new Float32Array(9);
* matrix.toArray(false, float32Array);
*
* // Get transposed array
* const transposed = matrix.toArray(true);
* ```
* @param transpose - Whether to transpose the matrix
* @param out - Optional Float32Array to store the result
* @returns The array containing the matrix values
* @see {@link Matrix.fromArray} For creating matrix from array
* @see {@link Matrix.array} For cached array storage
*/
toArray(transpose?: boolean, out?: Float32Array): Float32Array;
/**
* Get a new position with the current transformation applied.
*
* Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
* @example
* ```ts
* // Basic point transformation
* const matrix = new Matrix().translate(100, 50).rotate(Math.PI / 4);
* const point = new Point(10, 20);
* const transformed = matrix.apply(point);
*
* // Reuse existing point
* const output = new Point();
* matrix.apply(point, output);
* ```
* @param pos - The origin point to transform
* @param newPos - Optional point to store the result
* @returns The transformed point
* @see {@link Matrix.applyInverse} For inverse transformation
* @see {@link Point} For point operations
*/
apply<P extends PointData = Point>(pos: PointData, newPos?: P): P;
/**
* Get a new position with the inverse of the current transformation applied.
*
* Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
* @example
* ```ts
* // Basic inverse transformation
* const matrix = new Matrix().translate(100, 50).rotate(Math.PI / 4);
* const worldPoint = new Point(150, 100);
* const localPoint = matrix.applyInverse(worldPoint);
*
* // Reuse existing point
* const output = new Point();
* matrix.applyInverse(worldPoint, output);
*
* // Convert mouse position to local space
* const mousePoint = new Point(mouseX, mouseY);
* const localMouse = matrix.applyInverse(mousePoint);
* ```
* @param pos - The origin point to inverse-transform
* @param newPos - Optional point to store the result
* @returns The inverse-transformed point
* @see {@link Matrix.apply} For forward transformation
* @see {@link Matrix.invert} For getting inverse matrix
*/
applyInverse<P extends PointData = Point>(pos: PointData, newPos?: P): P;
/**
* Translates the matrix on the x and y axes.
* Adds to the position values while preserving scale, rotation and skew.
* @example
* ```ts
* // Basic translation
* const matrix = new Matrix();
* matrix.translate(100, 50); // Move right 100, down 50
*
* // Chain with other transformations
* matrix
* .scale(2, 2)
* .translate(100, 0)
* .rotate(Math.PI / 4);
* ```
* @param x - How much to translate on the x axis
* @param y - How much to translate on the y axis
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.set} For setting position directly
* @see {@link Matrix.setTransform} For complete transform setup
*/
translate(x: number, y: number): this;
/**
* Applies a scale transformation to the matrix.
* Multiplies the scale values with existing matrix components.
* @example
* ```ts
* // Basic scaling
* const matrix = new Matrix();
* matrix.scale(2, 3); // Scale 2x horizontally, 3x vertically
*
* // Chain with other transformations
* matrix
* .translate(100, 100)
* .scale(2, 2) // Scales after translation
* .rotate(Math.PI / 4);
* ```
* @param x - The amount to scale horizontally
* @param y - The amount to scale vertically
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.setTransform} For setting scale directly
* @see {@link Matrix.append} For combining transformations
*/
scale(x: number, y: number): this;
/**
* Applies a rotation transformation to the matrix.
*
* Rotates around the origin (0,0) by the given angle in radians.
* @example
* ```ts
* // Basic rotation
* const matrix = new Matrix();
* matrix.rotate(Math.PI / 4); // Rotate 45 degrees
*
* // Chain with other transformations
* matrix
* .translate(100, 100) // Move to rotation center
* .rotate(Math.PI) // Rotate 180 degrees
* .scale(2, 2); // Scale after rotation
*
* // Common angles
* matrix.rotate(Math.PI / 2); // 90 degrees
* matrix.rotate(Math.PI); // 180 degrees
* matrix.rotate(Math.PI * 2); // 360 degrees
* ```
* @remarks
* - Rotates around origin point (0,0)
* - Affects position if translation was set
* - Uses counter-clockwise rotation
* - Order of operations matters when chaining
* @param angle - The angle in radians
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.setTransform} For setting rotation directly
* @see {@link Matrix.append} For combining transformations
*/
rotate(angle: number): this;
/**
* Appends the given Matrix to this Matrix.
* Combines two matrices by multiplying them together: this = this * matrix
* @example
* ```ts
* // Basic matrix combination
* const matrix = new Matrix();
* const other = new Matrix().translate(100, 0).rotate(Math.PI / 4);
* matrix.append(other);
* ```
* @remarks
* - Order matters: A.append(B) !== B.append(A)
* - Modifies current matrix
* - Preserves transformation order
* - Commonly used for combining transforms
* @param matrix - The matrix to append
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.prepend} For prepending transformations
* @see {@link Matrix.appendFrom} For appending two external matrices
*/
append(matrix: Matrix): this;
/**
* Appends two matrices and sets the result to this matrix.
* Performs matrix multiplication: this = A * B
* @example
* ```ts
* // Basic matrix multiplication
* const result = new Matrix();
* const matrixA = new Matrix().scale(2, 2);
* const matrixB = new Matrix().rotate(Math.PI / 4);
* result.appendFrom(matrixA, matrixB);
* ```
* @remarks
* - Order matters: A * B !== B * A
* - Creates a new transformation from two others
* - More efficient than append() for multiple operations
* - Does not modify input matrices
* @param a - The first matrix to multiply
* @param b - The second matrix to multiply
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.append} For single matrix combination
* @see {@link Matrix.prepend} For reverse order multiplication
*/
appendFrom(a: Matrix, b: Matrix): this;
/**
* Sets the matrix based on all the available properties.
* Combines position, scale, rotation, skew and pivot in a single operation.
* @example
* ```ts
* // Basic transform setup
* const matrix = new Matrix();
* matrix.setTransform(
* 100, 100, // position
* 0, 0, // pivot
* 2, 2, // scale
* Math.PI / 4, // rotation (45 degrees)
* 0, 0 // skew
* );
* ```
* @remarks
* - Updates all matrix components at once
* - More efficient than separate transform calls
* - Uses radians for rotation and skew
* - Pivot affects rotation center
* @param x - Position on the x axis
* @param y - Position on the y axis
* @param pivotX - Pivot on the x axis
* @param pivotY - Pivot on the y axis
* @param scaleX - Scale on the x axis
* @param scaleY - Scale on the y axis
* @param rotation - Rotation in radians
* @param skewX - Skew on the x axis
* @param skewY - Skew on the y axis
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.decompose} For extracting transform properties
* @see {@link TransformableObject} For transform data structure
*/
setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): this;
/**
* Prepends the given Matrix to this Matrix.
* Combines two matrices by multiplying them together: this = matrix * this
* @example
* ```ts
* // Basic matrix prepend
* const matrix = new Matrix().scale(2, 2);
* const other = new Matrix().translate(100, 0);
* matrix.prepend(other); // Translation happens before scaling
* ```
* @remarks
* - Order matters: A.prepend(B) !== B.prepend(A)
* - Modifies current matrix
* - Reverses transformation order compared to append()
* @param matrix - The matrix to prepend
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.append} For appending transformations
* @see {@link Matrix.appendFrom} For combining external matrices
*/
prepend(matrix: Matrix): this;
/**
* Decomposes the matrix into its individual transform components.
* Extracts position, scale, rotation and skew values from the matrix.
* @example
* ```ts
* // Basic decomposition
* const matrix = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4)
* .scale(2, 2);
*
* const transform = {
* position: new Point(),
* scale: new Point(),
* pivot: new Point(),
* skew: new Point(),
* rotation: 0
* };
*
* matrix.decompose(transform);
* console.log(transform.position); // Point(100, 100)
* console.log(transform.rotation); // ~0.785 (PI/4)
* console.log(transform.scale); // Point(2, 2)
* ```
* @remarks
* - Handles combined transformations
* - Accounts for pivot points
* - Chooses between rotation/skew based on transform type
* - Uses radians for rotation and skew
* @param transform - The transform object to store the decomposed values
* @returns The transform with the newly applied properties
* @see {@link Matrix.setTransform} For composing from components
* @see {@link TransformableObject} For transform structure
*/
decompose(transform: TransformableObject): TransformableObject;
/**
* Inverts this matrix.
* Creates the matrix that when multiplied with this matrix results in an identity matrix.
* @example
* ```ts
* // Basic matrix inversion
* const matrix = new Matrix()
* .translate(100, 50)
* .scale(2, 2);
*
* matrix.invert(); // Now transforms in opposite direction
*
* // Verify inversion
* const point = new Point(50, 50);
* const transformed = matrix.apply(point);
* const original = matrix.invert().apply(transformed);
* // original ≈ point
* ```
* @remarks
* - Modifies the current matrix
* - Useful for reversing transformations
* - Cannot invert matrices with zero determinant
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.identity} For resetting to identity
* @see {@link Matrix.applyInverse} For inverse transformations
*/
invert(): this;
/**
* Checks if this matrix is an identity matrix.
*
* An identity matrix has no transformations applied (default state).
* @example
* ```ts
* // Check if matrix is identity
* const matrix = new Matrix();
* console.log(matrix.isIdentity()); // true
*
* // Check after transformations
* matrix.translate(100, 0);
* console.log(matrix.isIdentity()); // false
*
* // Reset and verify
* matrix.identity();
* console.log(matrix.isIdentity()); // true
* ```
* @remarks
* - Verifies a = 1, d = 1 (no scale)
* - Verifies b = 0, c = 0 (no skew)
* - Verifies tx = 0, ty = 0 (no translation)
* @returns True if matrix has no transformations
* @see {@link Matrix.identity} For resetting to identity
* @see {@link Matrix.IDENTITY} For constant identity matrix
*/
isIdentity(): boolean;
/**
* Resets this Matrix to an identity (default) matrix.
* Sets all components to their default values: scale=1, no skew, no translation.
* @example
* ```ts
* // Reset transformed matrix
* const matrix = new Matrix()
* .scale(2, 2)
* .rotate(Math.PI / 4);
* matrix.identity(); // Back to default state
*
* // Chain after reset
* matrix
* .identity()
* .translate(100, 100)
* .scale(2, 2);
*
* // Compare with identity constant
* const isDefault = matrix.equals(Matrix.IDENTITY);
* ```
* @remarks
* - Sets a=1, d=1 (default scale)
* - Sets b=0, c=0 (no skew)
* - Sets tx=0, ty=0 (no translation)
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.IDENTITY} For constant identity matrix
* @see {@link Matrix.isIdentity} For checking identity state
*/
identity(): this;
/**
* Creates a new Matrix object with the same values as this one.
* @returns A copy of this matrix. Good for chaining method calls.
*/
clone(): Matrix;
/**
* Creates a new Matrix object with the same values as this one.
* @param matrix
* @example
* ```ts
* // Basic matrix cloning
* const matrix = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4);
* const copy = matrix.clone();
*
* // Clone and modify
* const modified = matrix.clone()
* .scale(2, 2);
*
* // Compare matrices
* console.log(matrix.equals(copy)); // true
* console.log(matrix.equals(modified)); // false
* ```
* @returns A copy of this matrix. Good for chaining method calls.
* @see {@link Matrix.copyTo} For copying to existing matrix
* @see {@link Matrix.copyFrom} For copying from another matrix
*/
copyTo(matrix: Matrix): Matrix;
/**
* Changes the values of the matrix to be the same as the ones in given matrix.
* @example
* ```ts
* // Basic matrix copying
* const source = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4);
* const target = new Matrix();
* target.copyFrom(source);
* ```
* @param matrix - The matrix to copy from
* @returns This matrix. Good for chaining method calls.
* @see {@link Matrix.clone} For creating new matrix copy
* @see {@link Matrix.copyTo} For copying to another matrix
*/
copyFrom(matrix: Matrix): this;
/**
* Checks if this matrix equals another matrix.
* Compares all components for exact equality.
* @example
* ```ts
* // Basic equality check
* const m1 = new Matrix();
* const m2 = new Matrix();
* console.log(m1.equals(m2)); // true
*
* // Compare transformed matrices
* const transform = new Matrix()
* .translate(100, 100)
* const clone = new Matrix()
* .scale(2, 2);
* console.log(transform.equals(clone)); // false
* ```
* @param matrix - The matrix to compare to
* @returns True if matrices are identical
* @see {@link Matrix.copyFrom} For copying matrix values
* @see {@link Matrix.isIdentity} For identity comparison
*/
equals(matrix: Matrix): boolean;
toString(): string;
/**
* A default (identity) matrix with no transformations applied.
*
* > [!IMPORTANT] This is a shared read-only object. Create a new Matrix if you need to modify it.
* @example
* ```ts
* // Get identity matrix reference
* const identity = Matrix.IDENTITY;
* console.log(identity.isIdentity()); // true
*
* // Compare with identity
* const matrix = new Matrix();
* console.log(matrix.equals(Matrix.IDENTITY)); // true
*
* // Create new matrix instead of modifying IDENTITY
* const transform = new Matrix()
* .copyFrom(Matrix.IDENTITY)
* .translate(100, 100);
* ```
* @readonly
* @returns A read-only identity matrix
* @see {@link Matrix.shared} For temporary calculations
* @see {@link Matrix.identity} For resetting matrices
*/
static get IDENTITY(): Readonly<Matrix>;
/**
* A static Matrix that can be used to avoid creating new objects.
* Will always ensure the matrix is reset to identity when requested.
*
* > [!IMPORTANT] This matrix is shared and temporary. Do not store references to it.
* @example
* ```ts
* // Use for temporary calculations
* const tempMatrix = Matrix.shared;
* tempMatrix.translate(100, 100).rotate(Math.PI / 4);
* const point = tempMatrix.apply({ x: 10, y: 20 });
*
* // Will be reset to identity on next access
* const fresh = Matrix.shared; // Back to identity
* ```
* @remarks
* - Always returns identity matrix
* - Safe to modify temporarily
* - Not safe to store references
* - Useful for one-off calculations
* @readonly
* @returns A fresh identity matrix for temporary use
* @see {@link Matrix.IDENTITY} For immutable identity matrix
* @see {@link Matrix.identity} For resetting matrices
*/
static get shared(): Matrix;
}
export interface ObservablePoint extends PixiMixins.ObservablePoint {
}
/**
* Observer used to listen for observable point changes.
* Provides callback mechanism for point value updates.
* @example
* ```ts
* // Basic observer implementation
* const observer: Observer<ObservablePoint> = {
* _onUpdate: (point) => {
* console.log(`Point updated to (${point.x}, ${point.y})`);
* }
* };
*
* // Create observable point with observer
* const point = new ObservablePoint(observer, 100, 100);
*
* // Observer will be notified on changes
* point.x = 200; // Logs: Point updated to (200, 100)
* ```
* @remarks
* - Used internally by ObservablePoint
* - Triggered on x/y changes
* - Can track multiple points
* - Useful for change detection
* @typeParam T - The type of point being observed
* @see {@link ObservablePoint} The observable point class
* @see {@link PointLike} For point interface
* @category maths
* @standard
*/
export interface Observer<T> {
/**
* Callback to call when the point has updated.
* Triggered whenever x or y coordinates change.
* @param point - The point that was updated
*/
_onUpdate: (point?: T) => void;
}
/**
* The ObservablePoint object represents a location in a two-dimensional coordinate system.
* Triggers a callback when its position changes.
*
* The x and y properties represent the position on the horizontal and vertical axes, respectively.
* @example
* ```ts
* // Basic observable point usage
* const point = new ObservablePoint(
* { _onUpdate: (p) => console.log(`Updated to (${p.x}, ${p.y})`) },
* 100, 100
* );
*
* // Update triggers callback
* point.x = 200; // Logs: Updated to (200, 100)
* point.y = 300; // Logs: Updated to (200, 300)
*
* // Set both coordinates
* point.set(50, 50); // Logs: Updated to (50, 50)
* ```
* @see {@link Point} For non-observable version
* @see {@link Observer} For observer interface
* @see {@link PointLike} For point interface
* @category maths
* @standard
*/
export declare class ObservablePoint implements PointLike {
/** @ignore */
_x: number;
/** @ignore */
_y: number;
/** This object used to call the `onUpdate` callback when the point changes. */
private readonly _observer;
/**
* Creates a new `ObservablePoint`
* @param observer - Observer to pass to listen for change events.
* @param {number} [x=0] - position of the point on the x axis
* @param {number} [y=0] - position of the point on the y axis
*/
constructor(observer: Observer<ObservablePoint>, x?: number, y?: number);
/**
* Creates a clone of this point.
* @example
* ```ts
* // Basic cloning
* const point = new ObservablePoint(observer, 100, 200);
* const copy = point.clone();
*
* // Clone with new observer
* const newObserver = {
* _onUpdate: (p) => console.log(`Clone updated: (${p.x}, ${p.y})`)
* };
* const watched = point.clone(newObserver);
*
* // Verify independence
* watched.set(300, 400); // Only triggers new observer
* ```
* @param observer - Optional observer to pass to the new observable point
* @returns A copy of this observable point
* @see {@link ObservablePoint.copyFrom} For copying into existing point
* @see {@link Observer} For observer interface details
*/
clone(observer?: Observer<ObservablePoint>): ObservablePoint;
/**
* Sets the point to a new x and y position.
*
* If y is omitted, both x and y will be set to x.
* @example
* ```ts
* // Basic position setting
* const point = new ObservablePoint(observer);
* point.set(100, 200);
*
* // Set both x and y to same value
* point.set(50); // x=50, y=50
* ```
* @param x - Position on the x axis
* @param y - Position on the y axis, defaults to x
* @returns The point instance itself
* @see {@link ObservablePoint.copyFrom} For copying from another point
* @see {@link ObservablePoint.equals} For comparing positions
*/
set(x?: number, y?: number): this;
/**
* Copies x and y from the given point into this point.
* @example
* ```ts
* // Basic copying
* const source = new ObservablePoint(observer, 100, 200);
* const target = new ObservablePoint();
* target.copyFrom(source);
*
* // Copy and chain operations
* const point = new ObservablePoint()
* .copyFrom(source)
* .set(x + 50, y + 50);
*
* // Copy from any PointData
* const data = { x: 10, y: 20 };
* point.copyFrom(data);
* ```
* @param p - The point to copy from
* @returns The point instance itself
* @see {@link ObservablePoint.copyTo} For copying to another point
* @see {@link ObservablePoint.clone} For creating new point copy
*/
copyFrom(p: PointData): this;
/**
* Copies this point's x and y into the given point.
* @example
* ```ts
* // Basic copying
* const source = new ObservablePoint(100, 200);
* const target = new ObservablePoint();
* source.copyTo(target);
* ```
* @param p - The point to copy to. Can be any type that is or extends `PointLike`
* @returns The point (`p`) with values updated
* @see {@link ObservablePoint.copyFrom} For copying from another point
* @see {@link ObservablePoint.clone} For creating new point copy
*/
copyTo<T extends PointLike>(p: T): T;
/**
* Checks if another point is equal to this point.
*
* Compares x and y values using strict equality.
* @example
* ```ts
* // Basic equality check
* const p1 = new ObservablePoint(100, 200);
* const p2 = new ObservablePoint(100, 200);
* console.log(p1.equals(p2)); // true
*
* // Compare with PointData
* const data = { x: 100, y: 200 };
* console.log(p1.equals(data)); // true
*
* // Check different points
* const p3 = new ObservablePoint(200, 300);
* console.log(p1.equals(p3)); // false
* ```
* @param p - The point to check
* @returns `true` if both `x` and `y` are equal
* @see {@link ObservablePoint.copyFrom} For making points equal
* @see {@link PointData} For point data interface
*/
equals(p: PointData): boolean;
toString(): string;
/**
* Position of the observable point on the x axis.
* Triggers observer callback when value changes.
* @example
* ```ts
* // Basic x position
* const point = new ObservablePoint(observer);
* point.x = 100; // Triggers observer
*
* // Use in calculations
* const width = rightPoint.x - leftPoint.x;
* ```
* @default 0
*/
get x(): number;
set x(value: number);
/**
* Position of the observable point on the y axis.
* Triggers observer callback when value changes.
* @example
* ```ts
* // Basic y position
* const point = new ObservablePoint(observer);
* point.y = 200; // Triggers observer
*
* // Use in calculations
* const height = bottomPoint.y - topPoint.y;
* ```
* @default 0
*/
get y(): number;
set y(value: number);
}
/**
* Collection of valid extension types.
* @category extensions
* @advanced
*/
export declare enum ExtensionType {
/** extensions that are registered as Application plugins */
Application = "application",
/** extensions that are registered as WebGL render pipes */
WebGLPipes = "webgl-pipes",
/** extensions that are registered as WebGL render pipes adaptors */
WebGLPipesAdaptor = "webgl-pipes-adaptor",
/** extensions that are registered as WebGL render systems */
WebGLSystem = "webgl-system",
/** extensions that are registered as WebGPU render pipes */
WebGPUPipes = "webgpu-pipes",
/** extensions that are registered as WebGPU render pipes adaptors */
WebGPUPipesAdaptor = "webgpu-pipes-adaptor",
/** extensions that are registered as WebGPU render systems */
WebGPUSystem = "webgpu-system",
/** extensions that are registered as Canvas render pipes */
CanvasSystem = "canvas-system",
/** extensions that are registered as Canvas render pipes adaptors */
CanvasPipesAdaptor = "canvas-pipes-adaptor",
/** extensions that are registered as Canvas render systems */
CanvasPipes = "canvas-pipes",
/** extensions that combine the other Asset extensions */
Asset = "asset",
/** extensions that are used to load assets through Assets */
LoadParser = "load-parser",
/** extensions that are used to resolve asset urls through Assets */
ResolveParser = "resolve-parser",
/** extensions that are used to handle how urls are cached by Assets */
CacheParser = "cache-parser",
/** extensions that are used to add/remove available resources from Assets */
DetectionParser = "detection-parser",
/** extensions that are registered with the MaskEffectManager */
MaskEffect = "mask-effect",
/** A type of extension for creating a new advanced blend mode */
BlendMode = "blend-mode",
/** A type of extension that will be used to auto detect a resource type */
TextureSource = "texture-source",
/** A type of extension that will be used to auto detect an environment */
Environment = "environment",
/** A type of extension for building and triangulating custom shapes used in graphics. */
ShapeBuilder = "shape-builder",
/** A type of extension for creating custom batchers used in rendering. */
Batcher = "batcher"
}
/**
* The metadata for an extension.
* @category extensions
* @ignore
*/
export interface ExtensionMetadataDetails {
/** The extension type, can be multiple types */
type: ExtensionType | ExtensionType[];
/** Optional. Some plugins provide an API name/property, to make them more easily accessible */
name?: string;
/** Optional, used for sorting the plugins in a particular order */
priority?: number;
}
/**
* The metadata for an extension.
* @category extensions
* @advanced
*/
export type ExtensionMetadata = ExtensionType | ExtensionMetadataDetails;
/**
* Format when registering an extension. Generally, the extension
* should have these values as `extension` static property,
* but you can override name or type by providing an object.
* @category extensions
* @advanced
*/
interface ExtensionFormat {
/** The extension type, can be multiple types */
type: ExtensionType | ExtensionType[];
/** Optional. Some plugins provide an API name/property, such as Renderer plugins */
name?: string;
/** Optional, used for sorting the plugins in a particular order */
priority?: number;
/** Reference to the plugin object/class */
ref: any;
}
/**
* Extension format that is used internally for registrations.
* @category extensions
* @ignore
*/
interface StrictExtensionFormat extends ExtensionFormat {
/** The extension type, always expressed as multiple, even if a single */
type: ExtensionType[];
}
/**
* The function that is called when an extension is added or removed.
* @category extensions
* @ignore
*/
export type ExtensionHandler = (extension: StrictExtensionFormat) => void;
/**
* Get the priority for an extension.
* @ignore
* @param ext - Any extension
* @param defaultPriority - Fallback priority if none is defined.
* @returns The priority for the extension.
* @category extensions
*/
export declare const normalizeExtensionPriority: (ext: ExtensionFormat | any, defaultPriority: number) => number;
/**
* Global registration system for all PixiJS extensions. Provides a centralized way to add, remove,
* and manage functionality across the engine.
*
* Features:
* - Register custom extensions and plugins
* - Handle multiple extension types
* - Priority-based ordering
* @example
* ```ts
* import { extensions, ExtensionType } from 'pixi.js';
*
* // Register a simple object extension
* extensions.add({
* extension: {
* type: ExtensionType.LoadParser,
* name: 'my-loader',
* priority: 100, // Optional priority for ordering
* },
* // add load parser functions
* });
*
* // Register a class-based extension
* class MyRendererPlugin {
* static extension = {
* type: [ExtensionType.WebGLSystem, ExtensionType.WebGPUSystem],
* name: 'myRendererPlugin'
* };
*
* // add renderer plugin methods
* }
* extensions.add(MyRendererPlugin);
*
* // Remove extensions
* extensions.remove(MyRendererPlugin);
* ```
* @remarks
* - Extensions must have a type from {@link ExtensionType}
* - Can be registered before or after their handlers
* - Supports priority-based ordering
* - Automatically normalizes extension formats
* @see {@link ExtensionType} For all available extension types
* @see {@link ExtensionFormat} For extension registration format
* @see {@link Application} For application plugin system
* @see {@link LoaderParser} For asset loading extensions
* @category extensions
* @standard
* @class
*/
export declare const extensions: {
/** @ignore */
_addHandlers: Partial<Record<ExtensionType, ExtensionHandler>>;
/** @ignore */
_removeHandlers: Partial<Record<ExtensionType, ExtensionHandler>>;
/** @ignore */
_queue: Partial<Record<ExtensionType, StrictExtensionFormat[]>>;
/**
* Remove extensions from PixiJS.
* @param extensions - Extensions to be removed. Can be:
* - Extension class with static `extension` property
* - Extension format object with `type` and `ref`
* - Multiple extensions as separate arguments
* @returns {extensions} this for chaining
* @example
* ```ts
* // Remove a single extension
* extensions.remove(MyRendererPlugin);
*
* // Remove multiple extensions
* extensions.remove(
* MyRendererPlugin,
* MySystemPlugin
* );
* ```
* @see {@link ExtensionType} For available extension types
* @see {@link ExtensionFormat} For extension format details
*/
remove(...extensions: Array<ExtensionFormat | any>): any;
/**
* Register new extensions with PixiJS. Extensions can be registered in multiple formats:
* - As a class with a static `extension` property
* - As an extension format object
* - As multiple extensions passed as separate arguments
* @param extensions - Extensions to add to PixiJS. Each can be:
* - A class with static `extension` property
* - An extension format object with `type` and `ref`
* - Multiple extensions as separate arguments
* @returns This extensions instance for chaining
* @example
* ```ts
* // Register a simple extension
* extensions.add(MyRendererPlugin);
*
* // Register multiple extensions
* extensions.add(
* MyRendererPlugin,
* MySystemPlugin,
* });
* ```
* @see {@link ExtensionType} For available extension types
* @see {@link ExtensionFormat} For extension format details
* @see {@link extensions.remove} For removing registered extensions
*/
add(...extensions: Array<ExtensionFormat | any>): any;
/**
* Internal method to handle extensions by name.
* @param type - The extension type.
* @param onAdd - Function handler when extensions are added/registered {@link StrictExtensionFormat}.
* @param onRemove - Function handler when extensions are removed/unregistered {@link StrictExtensionFormat}.
* @returns this for chaining.
* @internal
* @ignore
*/
handle(type: ExtensionType, onAdd: ExtensionHandler, onRemove: ExtensionHandler): any;
/**
* Handle a type, but using a map by `name` property.
* @param type - Type of extension to handle.
* @param map - The object map of named extensions.
* @returns this for chaining.
* @ignore
*/
handleByMap(type: ExtensionType, map: Record<string, any>): any;
/**
* Handle a type, but using a list of extensions with a `name` property.
* @param type - Type of extension to handle.
* @param map - The array of named extensions.
* @param defaultPriority - Fallback priority if none is defined.
* @returns this for chaining.
* @ignore
*/
handleByNamedList(type: ExtensionType, map: {
name: string;
value: any;
}[], defaultPriority?: number): any;
/**
* Handle a type, but using a list of extensions.
* @param type - Type of extension to handle.
* @param list - The list of extensions.
* @param defaultPriority - The default priority to use if none is specified.
* @returns this for chaining.
* @ignore
*/
handleByList(type: ExtensionType, list: any[], defaultPriority?: number): any;
/**
* Mixin the source object(s) properties into the target class's prototype.
* Copies all property descriptors from source objects to the target's prototype.
* @param Target - The target class to mix properties into
* @param sources - One or more source objects containing properties to mix in
* @example
* ```ts
* // Create a mixin with shared properties
* const moveable = {
* x: 0,
* y: 0,
* move(x: number, y: number) {
* this.x += x;
* this.y += y;
* }
* };
*
* // Create a mixin with computed properties
* const scalable = {
* scale: 1,
* get scaled() {
* return this.scale > 1;
* }
* };
*
* // Apply mixins to a class
* extensions.mixin(Sprite, moveable, scalable);
*
* // Use mixed-in properties
* const sprite = new Sprite();
* sprite.move(10, 20);
* console.log(sprite.x, sprite.y); // 10, 20
* ```
* @remarks
* - Copies all properties including getters/setters
* - Does not modify source objects
* - Preserves property descriptors
* @see {@link Object.defineProperties} For details on property descriptors
* @see {@link Object.getOwnPropertyDescriptors} For details on property copying
*/
mixin(Target: any, ...sources: Parameters<typeof Object.getOwnPropertyDescriptors>[0][]): void;
};
/**
* Interface for HTMLImageElement.
* @category environment
* @advanced
*/
export interface ImageLike extends EventTarget {
/** Whether or not the image has completely loaded. */
readonly complete: boolean;
/** The Cross-Origin Resource Sharing (CORS) setting to use when retrieving the image. */
crossOrigin: string | null;
/** The URL of the image which is currently presented in the <img> element it represents. */
readonly currentSrc: string;
/** The width. */
width: number;
/** The height. */
height: number;
/** The address or URL of the a media resource that is to be considered. */
src: string;
/** Returns a Promise that resolves once the image is decoded. */
decode(): Promise<void>;
/** Removes the image from the DOM and cleans up resources. */
remove(): void;
onload: ((this: GlobalEventHandlers, ev: Event) => any) | null;
onerror: ((this: GlobalEventHandlers, ev: Event) => any) | null;
}
/**
* Common interface for CanvasRenderingContext2D, OffscreenCanvasRenderingContext2D, and other custom canvas 2D context.
* @category environment
* @advanced
*/
export interface ICanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, Omit<CanvasTextDrawingStyles, "letterSpacing">, CanvasPath {
/** creates a pattern using the specified image and repetition. */
createPattern(image: CanvasImageSource | ICanvas | ImageLike, repetition: string | null): CanvasPattern | null;
/** provides different ways to draw an image onto the canvas */
drawImage(image: CanvasImageSource | ICanvas | ImageLike, dx: number, dy: number): void;
drawImage(image: CanvasImageSource | ICanvas | ImageLike, dx: number, dy: number, dw: number, dh: number): void;
drawImage(image: CanvasImageSource | ICanvas | ImageLike, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
/** sets the horizontal spacing behavior between text characters. */
letterSpacing?: string;
/** sets the horizontal spacing behavior between text characters. */
textLetterSpacing?: string;
}
/**
* The context identifiers for the canvas.
* These identifiers are used to specify the type of rendering context to create.
* @category environment
* @advanced
*/
export type ContextIds = "2d" | "bitmaprenderer" | "webgl" | "experimental-webgl" | "webgl2" | "experimental-webgl2" | "webgpu";
/**
* The predefined color spaces for the canvas.
* @category environment
* @advanced
*/
type PredefinedColorSpace$1 = "srgb" | "display-p3";
/**
* The rendering context for the canvas.
* @category environment
* @advanced
*/
type RenderingContext$1 = ICanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext;
/**
* The context 2D settings for creating a rendering context.
* @category environment
* @advanced
*/
export interface ICanvasRenderingContext2DSettings {
alpha?: boolean;
colorSpace?: PredefinedColorSpace$1;
desynchronized?: boolean;
willReadFrequently?: boolean;
}
/**
* The context settings for creating a rendering context.
* @category environment
* @advanced
*/
export type ContextSettings = ICanvasRenderingContext2DSettings | ImageBitmapRenderingContextSettings | WebGLContextAttributes;
/**
* The parent node of the canvas.
* @category environment
* @advanced
*/
export interface ICanvasParentNode {
/** Adds a node to the end of the list of children of the parent node. */
appendChild(element: HTMLElement): void;
/** Removes a child node from the parent node. */
removeChild(element: HTMLElement): void;
removeChild(element: ICanvas): void;
}
/**
* Represents the style properties of a canvas element.
* @category environment
* @advanced
*/
export interface ICanvasStyle {
width?: string;
height?: string;
cursor?: string;
touchAction?: string;
msTouchAction?: string;
msContentZooming?: string;
}
/**
* Represents a rectangle in the canvas.
* @category environment
* @advanced
*/
export interface ICanvasRect {
/** The x-coordinate of the rectangle's top-left corner. */
x: number;
/** The y-coordinate of the rectangle's top-left corner. */
y: number;
/** The width of the rectangle. */
width: number;
/** The height of the rectangle. */
height: number;
}
/**
* WebGL context events.
* @category environment
* @advanced
*/
export interface WebGLContextEventMap {
"webglcontextlost": WebGLContextEvent;
"webglcontextrestore": WebGLContextEvent;
}
/**
* Common interface for HTMLCanvasElement, OffscreenCanvas, and other custom canvas classes.
* @extends PixiMixins.ICanvas
* @extends Partial<EventTarget>
* @category environment
* @advanced
*/
export interface ICanvas extends PixiMixins.ICanvas, Partial<EventTarget> {
/** Width of the canvas. */
width: number;
/** Height of the canvas. */
height: number;
/**
* Get rendering context of the canvas.
* @param {ContextIds} contextId - The identifier of the type of context to create.
* @param {ContextSettings} options - The options for creating context.
* @returns {RenderingContext | null} The created context, or null if contextId is not supported.
*/
getContext(contextId: "2d", options?: ICanvasRenderingContext2DSettings): ICanvasRenderingContext2D | null;
getContext(contextId: "bitmaprenderer", options?: ImageBitmapRenderingContextSettings): ImageBitmapRenderingContext | null;
getContext(contextId: "webgl" | "experimental-webgl", options?: WebGLContextAttributes): WebGLRenderingContext | null;
getContext(contextId: "webgl2" | "experimental-webgl2", options?: WebGLContextAttributes): WebGL2RenderingContext | null;
getContext(contextId: "webgpu"): GPUCanvasContext | null;
getContext(contextId: ContextIds, options?: ContextSettings): RenderingContext$1 | null;
/**
* Get the content of the canvas as data URL.
* @param {string} [type] - A string indicating the image format. The default type is `image/png`;
* that type is also used if the given type isn't supported.
* @param {string} [quality] - A number between 0 and 1 indicating the image quality to be used when
* creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
* A user agent will use its default quality value if this option is not specified, or if the number
* is outside the allowed range.
* @returns {string} A string containing the requested data URL.
*/
toDataURL?(type?: string, quality?: number): string;
/**
* Creates a Blob from the content of the canvas.
* @param {(blob: Blob | null) => void} callback - A callback function with the resulting `Blob` object
* as a single argument. `null` may be passed if the image cannot be created for any reason.
* @param {string} [type] - A string indicating the image format. The default type is `image/png`;
* that type is also used if the given type isn't supported.
* @param {string} [quality] - A number between 0 and 1 indicating the image quality to be used when
* creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
* A user agent will use its default quality value if this option is not specified, or if the number
* is outside the allowed range.
* @returns {void}
*/
toBlob?(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;
/**
* Get the content of the canvas as Blob.
* @param {object} [options] - The options for creating Blob.
* @param {string} [options.type] - A string indicating the image format. The default type is `image/png`;
* that type is also used if the given type isn't supported.
* @param {string} [options.quality] - A number between 0 and 1 indicating the image quality to be used when
* creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
* A user agent will use its default quality value if this option is not specified, or if the number
* is outside the allowed range.
* @returns {Promise<Blob>} A `Promise` returning a Blob object representing the image contained in the canvas.
*/
convertToBlob?(options?: {
type?: string;
quality?: number;
}): Promise<Blob>;
/**
* Adds the listener for the specified event.
* @param {string} type - The type of event to listen for.
* @param {EventListenerOrEventListenerObject} listener - The callback to invoke when the event is fired.
* @param {boolean | AddEventListenerOptions} options - The options for adding event listener.
* @returns {void}
*/
addEventListener?: {
(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
<K extends keyof WebGLContextEventMap>(type: K, listener: (this: ICanvas, ev: WebGLContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
};
/**
* Removes the listener for the specified event.
* @param {string} type - The type of event to listen for.
* @param {EventListenerOrEventListenerObject} listener - The callback to invoke when the event is fired.
* @param {boolean | EventListenerOptions} options - The options for removing event listener.
* @returns {void}
*/
removeEventListener?: {
(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
<K extends keyof WebGLContextEventMap>(type: K, listener: (this: ICanvas, ev: WebGLContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
};
/**
* Dispatches a event.
* @param {Event} event - The Event object to dispatch. Its Event.target property will be set to the current EventTarget.
* @returns {boolean} Returns false if event is cancelable, and at least one of the event handlers which received event
* called Event.preventDefault(). Otherwise true.
*/
dispatchEvent(event: Event): boolean;
/** Parent node of the canvas. */
readonly parentNode?: ICanvasParentNode | null;
/** Style of the canvas. */
readonly style?: ICanvasStyle;
/**
* Get the position and the size of the canvas.
* @returns The smallest rectangle which contains the entire canvas.
*/
getBoundingClientRect?(): ICanvasRect;
}
declare function earcut(vertices: ArrayLike<number>, holes?: ArrayLike<number>, dimensions?: number): number[];
/**
* A polygon triangulation library
* @see {@link https://github.com/mapbox/earcut}
* @param {number[]} vertices - A flat array of vertex coordinates
* @param {number[]} [holes] - An array of hole indices
* @param {number} [dimensions=2] - The number of coordinates per vertex in the input array
* @returns {number[]} Triangulated polygon
* @category utils
* @advanced
*/
declare const earcut$1: typeof earcut;
/**
* SystemRunner is used internally by the renderers as an efficient way for systems to
* be notified about what the renderer is up to during the rendering phase.
*
* ```ts
* import { SystemRunner } from 'pixi.js';
*
* const myObject = {
* loaded: new SystemRunner('loaded')
* }
*
* const listener = {
* loaded: function(){
* // thin
* }
* }
*
* myObject.loaded.add(listener);
*
* myObject.loaded.emit();
* ```
*
* Or for handling calling the same function on many items
* ```ts
* import { SystemRunner } from 'pixi.js';
*
* const myGame = {
* update: new SystemRunner('update')
* }
*
* const gameObject = {
* update: function(time){
* // update my gamey state
* }
* }
*
* myGame.update.add(gameObject);
*
* myGame.update.emit(time);
* ```
* @category rendering
* @internal
*/
export declare class SystemRunner {
items: any[];
private _name;
/**
* @param name - The function name that will be executed on the listeners added to this Runner.
*/
constructor(name: string);
/**
* Dispatch/Broadcast Runner to all listeners added to the queue.
* @param {...any} params - (optional) parameters to pass to each listener
*/
emit(a0?: unknown, a1?: unknown, a2?: unknown, a3?: unknown, a4?: unknown, a5?: unknown, a6?: unknown, a7?: unknown): this;
/**
* Add a listener to the Runner
*
* Runners do not need to have scope or functions passed to them.
* All that is required is to pass the listening object and ensure that it has contains a function that has the same name
* as the name provided to the Runner when it was created.
*
* Eg A listener passed to this Runner will require a 'complete' function.
*
* ```ts
* import { Runner } from 'pixi.js';
*
* const complete = new Runner('complete');
* ```
*
* The scope used will be the object itself.
* @param {any} item - The object that will be listening.
*/
add(item: unknown): this;
/**
* Remove a single listener from the dispatch queue.
* @param {any} item - The listener that you would like to remove.
*/
remove(item: unknown): this;
/**
* Check to see if the listener is already in the Runner
* @param {any} item - The listener that you would like to check.
*/
contains(item: unknown): boolean;
/** Remove all listeners from the Runner */
removeAll(): this;
/** Remove all references, don't use after this. */
destroy(): void;
/**
* `true` if there are no this Runner contains no listeners
* @readonly
*/
get empty(): boolean;
/**
* The name of the runner.
* @readonly
*/
get name(): string;
}
/**
* A simple axis-aligned bounding box (AABB) data structure used to define rectangular boundaries.
* Provides a clearer alternative to array-based bounds representation [minX, minY, maxX, maxY].
* @example
* ```ts
* // Create bounds data
* const bounds: BoundsData = {
* minX: 0,
* minY: 0,
* maxX: 100,
* maxY: 100
* };
*
* // Calculate dimensions
* const width = bounds.maxX - bounds.minX;
* const height = bounds.maxY - bounds.minY;
*
* // Check if point is inside
* const isInside = (x: number, y: number) =>
* x >= bounds.minX && x <= bounds.maxX &&
* y >= bounds.minY && y <= bounds.maxY;
* ```
* @see {@link Bounds} For full bounds implementation
* @see {@link Container#getBounds} For getting bounds
* @category rendering
* @standard
*/
export interface BoundsData {
/** The minimum X coordinate of the bounds */
minX: number;
/** The minimum Y coordinate of the bounds */
minY: number;
/** The maximum X coordinate of the bounds */
maxX: number;
/** The maximum Y coordinate of the bounds */
maxY: number;
}
/**
* A representation of an axis-aligned bounding box (AABB) used for efficient collision detection and culling.
* Stores minimum and maximum coordinates to define a rectangular boundary.
* @example
* ```ts
* // Create bounds
* const bounds = new Bounds();
*
* // Add a rectangular frame
* bounds.addFrame(0, 0, 100, 100);
* console.log(bounds.width, bounds.height); // 100, 100
*
* // Transform bounds
* const matrix = new Matrix()
* .translate(50, 50)
* .rotate(Math.PI / 4);
* bounds.applyMatrix(matrix);
*
* // Check point intersection
* if (bounds.containsPoint(75, 75)) {
* console.log('Point is inside bounds!');
* }
* ```
* @category rendering
* @standard
*/
export declare class Bounds {
/**
* The minimum X coordinate of the bounds.
* Represents the leftmost edge of the bounding box.
* @example
* ```ts
* const bounds = new Bounds();
* // Set left edge
* bounds.minX = 100;
* ```
* @default Infinity
*/
minX: number;
/**
* The minimum Y coordinate of the bounds.
* Represents the topmost edge of the bounding box.
* @example
* ```ts
* const bounds = new Bounds();
* // Set top edge
* bounds.minY = 100;
* ```
* @default Infinity
*/
minY: number;
/**
* The maximum X coordinate of the bounds.
* Represents the rightmost edge of the bounding box.
* @example
* ```ts
* const bounds = new Bounds();
* // Set right edge
* bounds.maxX = 200;
* // Get width
* const width = bounds.maxX - bounds.minX;
* ```
* @default -Infinity
*/
maxX: number;
/**
* The maximum Y coordinate of the bounds.
* Represents the bottommost edge of the bounding box.
* @example
* ```ts
* const bounds = new Bounds();
* // Set bottom edge
* bounds.maxY = 200;
* // Get height
* const height = bounds.maxY - bounds.minY;
* ```
* @default -Infinity
*/
maxY: number;
/**
* The transformation matrix applied to this bounds object.
* Used when calculating bounds with transforms.
* @example
* ```ts
* const bounds = new Bounds();
*
* // Apply translation matrix
* bounds.matrix = new Matrix()
* .translate(100, 100);
*
* // Combine transformations
* bounds.matrix = new Matrix()
* .translate(50, 50)
* .rotate(Math.PI / 4)
* .scale(2, 2);
*
* // Use in bounds calculations
* bounds.addFrame(0, 0, 100, 100); // Uses current matrix
* bounds.addFrame(0, 0, 100, 100, customMatrix); // Override matrix
* ```
* @advanced
*/
matrix: Matrix;
private _rectangle;
/**
* Creates a new Bounds object.
* @param minX - The minimum X coordinate of the bounds.
* @param minY - The minimum Y coordinate of the bounds.
* @param maxX - The maximum X coordinate of the bounds.
* @param maxY - The maximum Y coordinate of the bounds.
*/
constructor(minX?: number, minY?: number, maxX?: number, maxY?: number);
/**
* Checks if bounds are empty, meaning either width or height is zero or negative.
* Empty bounds occur when min values exceed max values on either axis.
* @example
* ```ts
* const bounds = new Bounds();
*
* // Check if newly created bounds are empty
* console.log(bounds.isEmpty()); // true, default bounds are empty
*
* // Add frame and check again
* bounds.addFrame(0, 0, 100, 100);
* console.log(bounds.isEmpty()); // false, bounds now have area
*
* // Clear bounds
* bounds.clear();
* console.log(bounds.isEmpty()); // true, bounds are empty again
* ```
* @returns True if bounds are empty (have no area)
* @see {@link Bounds#clear} For resetting bounds
* @see {@link Bounds#isValid} For checking validity
*/
isEmpty(): boolean;
/**
* The bounding rectangle representation of these bounds.
* Lazily creates and updates a Rectangle instance based on the current bounds.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
*
* // Get rectangle representation
* const rect = bounds.rectangle;
* console.log(rect.x, rect.y, rect.width, rect.height);
*
* // Use for hit testing
* if (bounds.rectangle.contains(mouseX, mouseY)) {
* console.log('Mouse is inside bounds!');
* }
* ```
* @see {@link Rectangle} For rectangle methods
* @see {@link Bounds.isEmpty} For bounds validation
*/
get rectangle(): Rectangle;
/**
* Clears the bounds and resets all coordinates to their default values.
* Resets the transformation matrix back to identity.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* console.log(bounds.isEmpty()); // false
* // Clear the bounds
* bounds.clear();
* console.log(bounds.isEmpty()); // true
* ```
* @returns This bounds object for chaining
*/
clear(): this;
/**
* Sets the bounds directly using coordinate values.
* Provides a way to set all bounds values at once.
* @example
* ```ts
* const bounds = new Bounds();
* bounds.set(0, 0, 100, 100);
* ```
* @param x0 - Left X coordinate of frame
* @param y0 - Top Y coordinate of frame
* @param x1 - Right X coordinate of frame
* @param y1 - Bottom Y coordinate of frame
* @see {@link Bounds#addFrame} For matrix-aware bounds setting
* @see {@link Bounds#clear} For resetting bounds
*/
set(x0: number, y0: number, x1: number, y1: number): void;
/**
* Adds a rectangular frame to the bounds, optionally transformed by a matrix.
* Updates the bounds to encompass the new frame coordinates.
* @example
* ```ts
* const bounds = new Bounds();
* bounds.addFrame(0, 0, 100, 100);
*
* // Add transformed frame
* const matrix = new Matrix()
* .translate(50, 50)
* .rotate(Math.PI / 4);
* bounds.addFrame(0, 0, 100, 100, matrix);
* ```
* @param x0 - Left X coordinate of frame
* @param y0 - Top Y coordinate of frame
* @param x1 - Right X coordinate of frame
* @param y1 - Bottom Y coordinate of frame
* @param matrix - Optional transformation matrix
* @see {@link Bounds#addRect} For adding Rectangle objects
* @see {@link Bounds#addBounds} For adding other Bounds
*/
addFrame(x0: number, y0: number, x1: number, y1: number, matrix?: Matrix): void;
/**
* Adds a rectangle to the bounds, optionally transformed by a matrix.
* Updates the bounds to encompass the given rectangle.
* @example
* ```ts
* const bounds = new Bounds();
* // Add simple rectangle
* const rect = new Rectangle(0, 0, 100, 100);
* bounds.addRect(rect);
*
* // Add transformed rectangle
* const matrix = new Matrix()
* .translate(50, 50)
* .rotate(Math.PI / 4);
* bounds.addRect(rect, matrix);
* ```
* @param rect - The rectangle to be added
* @param matrix - Optional transformation matrix
* @see {@link Bounds#addFrame} For adding raw coordinates
* @see {@link Bounds#addBounds} For adding other bounds
*/
addRect(rect: Rectangle, matrix?: Matrix): void;
/**
* Adds another bounds object to this one, optionally transformed by a matrix.
* Expands the bounds to include the given bounds' area.
* @example
* ```ts
* const bounds = new Bounds();
*
* // Add child bounds
* const childBounds = sprite.getBounds();
* bounds.addBounds(childBounds);
*
* // Add transformed bounds
* const matrix = new Matrix()
* .scale(2, 2);
* bounds.addBounds(childBounds, matrix);
* ```
* @param bounds - The bounds to be added
* @param matrix - Optional transformation matrix
* @see {@link Bounds#addFrame} For adding raw coordinates
* @see {@link Bounds#addRect} For adding rectangles
*/
addBounds(bounds: BoundsData, matrix?: Matrix): void;
/**
* Adds other Bounds as a mask, creating an intersection of the two bounds.
* Only keeps the overlapping region between current bounds and mask bounds.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Create mask bounds
* const mask = new Bounds();
* mask.addFrame(50, 50, 150, 150);
* // Apply mask - results in bounds of (50,50,100,100)
* bounds.addBoundsMask(mask);
* ```
* @param mask - The Bounds to use as a mask
* @see {@link Bounds#addBounds} For union operation
* @see {@link Bounds#fit} For fitting to rectangle
*/
addBoundsMask(mask: Bounds): void;
/**
* Applies a transformation matrix to the bounds, updating its coordinates.
* Transforms all corners of the bounds using the given matrix.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Apply translation
* const translateMatrix = new Matrix()
* .translate(50, 50);
* bounds.applyMatrix(translateMatrix);
* ```
* @param matrix - The matrix to apply to the bounds
* @see {@link Matrix} For matrix operations
* @see {@link Bounds#addFrame} For adding transformed frames
*/
applyMatrix(matrix: Matrix): void;
/**
* Resizes the bounds object to fit within the given rectangle.
* Clips the bounds if they extend beyond the rectangle's edges.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 200, 200);
* // Fit within viewport
* const viewport = new Rectangle(50, 50, 100, 100);
* bounds.fit(viewport);
* // bounds are now (50, 50, 150, 150)
* ```
* @param rect - The rectangle to fit within
* @returns This bounds object for chaining
* @see {@link Bounds#addBoundsMask} For intersection
* @see {@link Bounds#pad} For expanding bounds
*/
fit(rect: Rectangle): this;
/**
* Resizes the bounds object to include the given bounds.
* Similar to fit() but works with raw coordinate values instead of a Rectangle.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 200, 200);
* // Fit to specific coordinates
* bounds.fitBounds(50, 150, 50, 150);
* // bounds are now (50, 50, 150, 150)
* ```
* @param left - The left value of the bounds
* @param right - The right value of the bounds
* @param top - The top value of the bounds
* @param bottom - The bottom value of the bounds
* @returns This bounds object for chaining
* @see {@link Bounds#fit} For fitting to Rectangle
* @see {@link Bounds#addBoundsMask} For intersection
*/
fitBounds(left: number, right: number, top: number, bottom: number): this;
/**
* Pads bounds object, making it grow in all directions.
* If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
*
* // Add equal padding
* bounds.pad(10);
* // bounds are now (-10, -10, 110, 110)
*
* // Add different padding for x and y
* bounds.pad(20, 10);
* // bounds are now (-30, -20, 130, 120)
* ```
* @param paddingX - The horizontal padding amount
* @param paddingY - The vertical padding amount
* @returns This bounds object for chaining
* @see {@link Bounds#fit} For constraining bounds
* @see {@link Bounds#scale} For uniform scaling
*/
pad(paddingX: number, paddingY?: number): this;
/**
* Ceils the bounds by rounding up max values and rounding down min values.
* Useful for pixel-perfect calculations and avoiding fractional pixels.
* @example
* ```ts
* const bounds = new Bounds();
* bounds.set(10.2, 10.9, 50.1, 50.8);
*
* // Round to whole pixels
* bounds.ceil();
* // bounds are now (10, 10, 51, 51)
* ```
* @returns This bounds object for chaining
* @see {@link Bounds#scale} For size adjustments
* @see {@link Bounds#fit} For constraining bounds
*/
ceil(): this;
/**
* Creates a new Bounds instance with the same values.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
*
* // Create a copy
* const copy = bounds.clone();
*
* // Original and copy are independent
* bounds.pad(10);
* console.log(copy.width === bounds.width); // false
* ```
* @returns A new Bounds instance with the same values
* @see {@link Bounds#copyFrom} For reusing existing bounds
*/
clone(): Bounds;
/**
* Scales the bounds by the given values, adjusting all edges proportionally.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
*
* // Scale uniformly
* bounds.scale(2);
* // bounds are now (0, 0, 200, 200)
*
* // Scale non-uniformly
* bounds.scale(0.5, 2);
* // bounds are now (0, 0, 100, 400)
* ```
* @param x - The X value to scale by
* @param y - The Y value to scale by (defaults to x)
* @returns This bounds object for chaining
* @see {@link Bounds#pad} For adding padding
* @see {@link Bounds#fit} For constraining size
*/
scale(x: number, y?: number): this;
/**
* The x position of the bounds in local space.
* Setting this value will move the bounds while maintaining its width.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Get x position
* console.log(bounds.x); // 0
*
* // Move bounds horizontally
* bounds.x = 50;
* console.log(bounds.minX, bounds.maxX); // 50, 150
*
* // Width stays the same
* console.log(bounds.width); // Still 100
* ```
*/
get x(): number;
set x(value: number);
/**
* The y position of the bounds in local space.
* Setting this value will move the bounds while maintaining its height.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Get y position
* console.log(bounds.y); // 0
*
* // Move bounds vertically
* bounds.y = 50;
* console.log(bounds.minY, bounds.maxY); // 50, 150
*
* // Height stays the same
* console.log(bounds.height); // Still 100
* ```
*/
get y(): number;
set y(value: number);
/**
* The width value of the bounds.
* Represents the distance between minX and maxX coordinates.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Get width
* console.log(bounds.width); // 100
* // Resize width
* bounds.width = 200;
* console.log(bounds.maxX - bounds.minX); // 200
* ```
*/
get width(): number;
set width(value: number);
/**
* The height value of the bounds.
* Represents the distance between minY and maxY coordinates.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Get height
* console.log(bounds.height); // 100
* // Resize height
* bounds.height = 150;
* console.log(bounds.maxY - bounds.minY); // 150
* ```
*/
get height(): number;
set height(value: number);
/**
* The left edge coordinate of the bounds.
* Alias for minX.
* @example
* ```ts
* const bounds = new Bounds(50, 0, 150, 100);
* console.log(bounds.left); // 50
* console.log(bounds.left === bounds.minX); // true
* ```
* @readonly
*/
get left(): number;
/**
* The right edge coordinate of the bounds.
* Alias for maxX.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* console.log(bounds.right); // 100
* console.log(bounds.right === bounds.maxX); // true
* ```
* @readonly
*/
get right(): number;
/**
* The top edge coordinate of the bounds.
* Alias for minY.
* @example
* ```ts
* const bounds = new Bounds(0, 25, 100, 125);
* console.log(bounds.top); // 25
* console.log(bounds.top === bounds.minY); // true
* ```
* @readonly
*/
get top(): number;
/**
* The bottom edge coordinate of the bounds.
* Alias for maxY.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 200);
* console.log(bounds.bottom); // 200
* console.log(bounds.bottom === bounds.maxY); // true
* ```
* @readonly
*/
get bottom(): number;
/**
* Whether the bounds has positive width and height.
* Checks if both dimensions are greater than zero.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Check if bounds are positive
* console.log(bounds.isPositive); // true
*
* // Negative bounds
* bounds.maxX = bounds.minX;
* console.log(bounds.isPositive); // false, width is 0
* ```
* @readonly
* @see {@link Bounds#isEmpty} For checking empty state
* @see {@link Bounds#isValid} For checking validity
*/
get isPositive(): boolean;
/**
* Whether the bounds has valid coordinates.
* Checks if the bounds has been initialized with real values.
* @example
* ```ts
* const bounds = new Bounds();
* console.log(bounds.isValid); // false, default state
*
* // Set valid bounds
* bounds.addFrame(0, 0, 100, 100);
* console.log(bounds.isValid); // true
* ```
* @readonly
* @see {@link Bounds#isEmpty} For checking empty state
* @see {@link Bounds#isPositive} For checking dimensions
*/
get isValid(): boolean;
/**
* Adds vertices from a Float32Array to the bounds, optionally transformed by a matrix.
* Used for efficiently updating bounds from raw vertex data.
* @example
* ```ts
* const bounds = new Bounds();
*
* // Add vertices from geometry
* const vertices = new Float32Array([
* 0, 0, // Vertex 1
* 100, 0, // Vertex 2
* 100, 100 // Vertex 3
* ]);
* bounds.addVertexData(vertices, 0, 6);
*
* // Add transformed vertices
* const matrix = new Matrix()
* .translate(50, 50)
* .rotate(Math.PI / 4);
* bounds.addVertexData(vertices, 0, 6, matrix);
*
* // Add subset of vertices
* bounds.addVertexData(vertices, 2, 4); // Only second vertex
* ```
* @param vertexData - The array of vertices to add
* @param beginOffset - Starting index in the vertex array
* @param endOffset - Ending index in the vertex array (excluded)
* @param matrix - Optional transformation matrix
* @see {@link Bounds#addFrame} For adding rectangular frames
* @see {@link Matrix} For transformation details
*/
addVertexData(vertexData: Float32Array, beginOffset: number, endOffset: number, matrix?: Matrix): void;
/**
* Checks if a point is contained within the bounds.
* Returns true if the point's coordinates fall within the bounds' area.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* // Basic point check
* console.log(bounds.containsPoint(50, 50)); // true
* console.log(bounds.containsPoint(150, 150)); // false
*
* // Check edges
* console.log(bounds.containsPoint(0, 0)); // true, includes edges
* console.log(bounds.containsPoint(100, 100)); // true, includes edges
* ```
* @param x - x coordinate to check
* @param y - y coordinate to check
* @returns True if the point is inside the bounds
* @see {@link Bounds#isPositive} For valid bounds check
* @see {@link Bounds#rectangle} For Rectangle representation
*/
containsPoint(x: number, y: number): boolean;
/**
* Returns a string representation of the bounds.
* Useful for debugging and logging bounds information.
* @example
* ```ts
* const bounds = new Bounds(0, 0, 100, 100);
* console.log(bounds.toString()); // "[pixi.js:Bounds minX=0 minY=0 maxX=100 maxY=100 width=100 height=100]"
* ```
* @returns A string describing the bounds
* @see {@link Bounds#copyFrom} For copying bounds
* @see {@link Bounds#clone} For creating a new instance
*/
toString(): string;
/**
* Copies the bounds from another bounds object.
* Useful for reusing bounds objects and avoiding allocations.
* @example
* ```ts
* const sourceBounds = new Bounds(0, 0, 100, 100);
* // Copy bounds
* const targetBounds = new Bounds();
* targetBounds.copyFrom(sourceBounds);
* ```
* @param bounds - The bounds to copy from
* @returns This bounds object for chaining
* @see {@link Bounds#clone} For creating new instances
*/
copyFrom(bounds: Bounds): this;
}
/**
* Two Pi.
* @type {number}
* @category maths
* @standard
*/
export declare const PI_2: number;
/**
* Conversion factor for converting radians to degrees.
* @type {number} RAD_TO_DEG
* @category maths
* @standard
*/
export declare const RAD_TO_DEG: number;
/**
* Conversion factor for converting degrees to radians.
* @type {number}
* @category maths
* @standard
*/
export declare const DEG_TO_RAD: number;
/**
* Constants that identify shapes, mainly to prevent `instanceof` calls.
* @category maths
* @advanced
*/
export type SHAPE_PRIMITIVE = "polygon" | "rectangle" | "circle" | "ellipse" | "triangle" | "roundedRectangle";
/**
* A basic interface that defines common properties and methods for all Pixi shape primitives.
* Provides a standard API for shape manipulation, hit testing, and bounds calculation.
* @example
* ```ts
* // Implement basic shape
* class CustomShape implements ShapePrimitive {
* public readonly type = 'custom';
* public x = 0;
* public y = 0;
*
* // Implement required methods
* public contains(x: number, y: number): boolean {
* // Custom hit testing logic
* return true;
* }
*
* public getBounds(out?: Rectangle): Rectangle {
* // Custom bounds calculation
* return out || new Rectangle();
* }
*
* // ... implement other required methods
* }
* // Use in a container
* container.hitArea = new CustomShape();
* ```
* @see {@link Rectangle} For rectangular shape implementation
* @see {@link Circle} For circular shape implementation
* @see {@link Polygon} For polygon shape implementation
* @category maths
* @advanced
*/
export interface ShapePrimitive {
/** The type of the object, mainly used to avoid `instanceof` checks */
readonly type: SHAPE_PRIMITIVE | (string & {});
/** Checks whether the x and y coordinates passed to this function are contained within this ShapePrimitive. */
contains(x: number, y: number): boolean;
/** Checks whether the x and y coordinates passed to this function are contained within the stroke of this shape */
strokeContains(x: number, y: number, strokeWidth: number, alignment?: number): boolean;
/** Creates a clone of this ShapePrimitive instance. */
clone(): ShapePrimitive;
/** Copies the properties from another ShapePrimitive to this ShapePrimitive. */
copyFrom(source: ShapePrimitive): void;
/** Copies the properties from this ShapePrimitive to another ShapePrimitive. */
copyTo(destination: ShapePrimitive): void;
/** Returns the framing rectangle of the ShapePrimitive as a Rectangle object. */
getBounds(out?: Rectangle): Rectangle;
/** The X coordinate of the shape */
readonly x: number;
/** The Y coordinate of the shape */
readonly y: number;
}
export interface Rectangle extends PixiMixins.Rectangle {
}
/**
* The `Rectangle` object represents a rectangular area defined by its position and dimensions.
* Used for hit testing, bounds calculation, and general geometric operations.
* @example
* ```ts
* // Basic rectangle creation
* const rect = new Rectangle(100, 100, 200, 150);
*
* // Use as container bounds
* container.hitArea = new Rectangle(0, 0, 100, 100);
*
* // Check point containment
* const isInside = rect.contains(mouseX, mouseY);
*
* // Manipulate dimensions
* rect.width *= 2;
* rect.height += 50;
* ```
* @remarks
* - Position defined by top-left corner (x,y)
* - Dimensions defined by width and height
* - Supports point and rectangle containment
* - Common in UI and layout calculations
* @see {@link Circle} For circular shapes
* @see {@link Polygon} For complex shapes
* @see {@link RoundedRectangle} For rounded corners
* @category maths
* @standard
*/
export declare class Rectangle implements ShapePrimitive {
/**
* The type of the object, mainly used to avoid `instanceof` checks
* @example
* ```ts
* // Check shape type
* const shape = new Rectangle(0, 0, 100, 100);
* console.log(shape.type); // 'rectangle'
*
* // Use in type guards
* if (shape.type === 'rectangle') {
* console.log(shape.width, shape.height);
* }
* ```
* @readonly
* @default 'rectangle'
* @see {@link SHAPE_PRIMITIVE} For all shape types
*/
readonly type: SHAPE_PRIMITIVE;
/**
* The X coordinate of the upper-left corner of the rectangle
* @example
* ```ts
* // Basic x position
* const rect = new Rectangle();
* rect.x = 100;
* ```
* @default 0
*/
x: number;
/**
* The Y coordinate of the upper-left corner of the rectangle
* @example
* ```ts
* // Basic y position
* const rect = new Rectangle();
* rect.y = 100;
* ```
* @default 0
*/
y: number;
/**
* The overall width of this rectangle
* @example
* ```ts
* // Basic width setting
* const rect = new Rectangle();
* rect.width = 200;
* ```
* @default 0
*/
width: number;
/**
* The overall height of this rectangle
* @example
* ```ts
* // Basic height setting
* const rect = new Rectangle();
* rect.height = 150;
* ```
* @default 0
*/
height: number;
/**
* @param x - The X coordinate of the upper-left corner of the rectangle
* @param y - The Y coordinate of the upper-left corner of the rectangle
* @param width - The overall width of the rectangle
* @param height - The overall height of the rectangle
*/
constructor(x?: string | number, y?: string | number, width?: string | number, height?: string | number);
/**
* Returns the left edge (x-coordinate) of the rectangle.
* @example
* ```ts
* // Get left edge position
* const rect = new Rectangle(100, 100, 200, 150);
* console.log(rect.left); // 100
*
* // Use in alignment calculations
* sprite.x = rect.left + padding;
*
* // Compare positions
* if (point.x > rect.left) {
* console.log('Point is right of rectangle');
* }
* ```
* @readonly
* @returns The x-coordinate of the left edge
* @see {@link Rectangle.right} For right edge position
* @see {@link Rectangle.x} For direct x-coordinate access
*/
get left(): number;
/**
* Returns the right edge (x + width) of the rectangle.
* @example
* ```ts
* // Get right edge position
* const rect = new Rectangle(100, 100, 200, 150);
* console.log(rect.right); // 300
*
* // Align to right edge
* sprite.x = rect.right - sprite.width;
*
* // Check boundaries
* if (point.x < rect.right) {
* console.log('Point is inside right bound');
* }
* ```
* @readonly
* @returns The x-coordinate of the right edge
* @see {@link Rectangle.left} For left edge position
* @see {@link Rectangle.width} For width value
*/
get right(): number;
/**
* Returns the top edge (y-coordinate) of the rectangle.
* @example
* ```ts
* // Get top edge position
* const rect = new Rectangle(100, 100, 200, 150);
* console.log(rect.top); // 100
*
* // Position above rectangle
* sprite.y = rect.top - sprite.height;
*
* // Check vertical position
* if (point.y > rect.top) {
* console.log('Point is below top edge');
* }
* ```
* @readonly
* @returns The y-coordinate of the top edge
* @see {@link Rectangle.bottom} For bottom edge position
* @see {@link Rectangle.y} For direct y-coordinate access
*/
get top(): number;
/**
* Returns the bottom edge (y + height) of the rectangle.
* @example
* ```ts
* // Get bottom edge position
* const rect = new Rectangle(100, 100, 200, 150);
* console.log(rect.bottom); // 250
*
* // Stack below rectangle
* sprite.y = rect.bottom + margin;
*
* // Check vertical bounds
* if (point.y < rect.bottom) {
* console.log('Point is above bottom edge');
* }
* ```
* @readonly
* @returns The y-coordinate of the bottom edge
* @see {@link Rectangle.top} For top edge position
* @see {@link Rectangle.height} For height value
*/
get bottom(): number;
/**
* Determines whether the Rectangle is empty (has no area).
* @example
* ```ts
* // Check zero dimensions
* const rect = new Rectangle(100, 100, 0, 50);
* console.log(rect.isEmpty()); // true
* ```
* @returns True if the rectangle has no area
* @see {@link Rectangle.width} For width value
* @see {@link Rectangle.height} For height value
*/
isEmpty(): boolean;
/**
* A constant empty rectangle. This is a new object every time the property is accessed.
* @example
* ```ts
* // Get fresh empty rectangle
* const empty = Rectangle.EMPTY;
* console.log(empty.isEmpty()); // true
* ```
* @returns A new empty rectangle instance
* @see {@link Rectangle.isEmpty} For empty state testing
*/
static get EMPTY(): Rectangle;
/**
* Creates a clone of this Rectangle
* @example
* ```ts
* // Basic cloning
* const original = new Rectangle(100, 100, 200, 150);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.width *= 2;
* modified.height += 50;
*
* // Verify independence
* console.log(original.width); // 200
* console.log(modified.width); // 400
* ```
* @returns A copy of the rectangle
* @see {@link Rectangle.copyFrom} For copying into existing rectangle
* @see {@link Rectangle.copyTo} For copying to another rectangle
*/
clone(): Rectangle;
/**
* Converts a Bounds object to a Rectangle object.
* @example
* ```ts
* // Convert bounds to rectangle
* const bounds = container.getBounds();
* const rect = new Rectangle().copyFromBounds(bounds);
* ```
* @param bounds - The bounds to copy and convert to a rectangle
* @returns Returns itself
* @see {@link Bounds} For bounds object structure
* @see {@link Rectangle.getBounds} For getting rectangle bounds
*/
copyFromBounds(bounds: Bounds): this;
/**
* Copies another rectangle to this one.
* @example
* ```ts
* // Basic copying
* const source = new Rectangle(100, 100, 200, 150);
* const target = new Rectangle();
* target.copyFrom(source);
*
* // Chain with other operations
* const rect = new Rectangle()
* .copyFrom(source)
* .pad(10);
* ```
* @param rectangle - The rectangle to copy from
* @returns Returns itself
* @see {@link Rectangle.copyTo} For copying to another rectangle
* @see {@link Rectangle.clone} For creating new rectangle copy
*/
copyFrom(rectangle: Rectangle): Rectangle;
/**
* Copies this rectangle to another one.
* @example
* ```ts
* // Basic copying
* const source = new Rectangle(100, 100, 200, 150);
* const target = new Rectangle();
* source.copyTo(target);
*
* // Chain with other operations
* const result = source
* .copyTo(new Rectangle())
* .getBounds();
* ```
* @param rectangle - The rectangle to copy to
* @returns Returns given parameter
* @see {@link Rectangle.copyFrom} For copying from another rectangle
* @see {@link Rectangle.clone} For creating new rectangle copy
*/
copyTo(rectangle: Rectangle): Rectangle;
/**
* Checks whether the x and y coordinates given are contained within this Rectangle
* @example
* ```ts
* // Basic containment check
* const rect = new Rectangle(100, 100, 200, 150);
* const isInside = rect.contains(150, 125); // true
* // Check edge cases
* console.log(rect.contains(100, 100)); // true (on edge)
* console.log(rect.contains(300, 250)); // false (outside)
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coordinates are within this Rectangle
* @see {@link Rectangle.containsRect} For rectangle containment
* @see {@link Rectangle.strokeContains} For checking stroke intersection
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this rectangle including the stroke.
* @example
* ```ts
* // Basic stroke check
* const rect = new Rectangle(100, 100, 200, 150);
* const isOnStroke = rect.strokeContains(150, 100, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = rect.strokeContains(150, 100, 4, 1); // Inside
* const centerStroke = rect.strokeContains(150, 100, 4, 0.5); // Centered
* const outerStroke = rect.strokeContains(150, 100, 4, 0); // Outside
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @param strokeWidth - The width of the line to check
* @param alignment - The alignment of the stroke (1 = inner, 0.5 = centered, 0 = outer)
* @returns Whether the x/y coordinates are within this rectangle's stroke
* @see {@link Rectangle.contains} For checking fill containment
* @see {@link Rectangle.getBounds} For getting stroke bounds
*/
strokeContains(x: number, y: number, strokeWidth: number, alignment?: number): boolean;
/**
* Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object.
* Returns true only if the area of the intersection is >0, this means that Rectangles
* sharing a side are not overlapping. Another side effect is that an arealess rectangle
* (width or height equal to zero) can't intersect any other rectangle.
* @param {Rectangle} other - The Rectangle to intersect with `this`.
* @param {Matrix} transform - The transformation matrix of `other`.
* @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`.
*/
/**
* Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object.
*
* Returns true only if the area of the intersection is greater than 0.
* This means that rectangles sharing only a side are not considered intersecting.
* @example
* ```ts
* // Basic intersection check
* const rect1 = new Rectangle(0, 0, 100, 100);
* const rect2 = new Rectangle(50, 50, 100, 100);
* console.log(rect1.intersects(rect2)); // true
*
* // With transformation matrix
* const matrix = new Matrix();
* matrix.rotate(Math.PI / 4); // 45 degrees
* console.log(rect1.intersects(rect2, matrix)); // Checks with rotation
*
* // Edge cases
* const zeroWidth = new Rectangle(0, 0, 0, 100);
* console.log(rect1.intersects(zeroWidth)); // false (no area)
* ```
* @remarks
* - Returns true only if intersection area is > 0
* - Rectangles sharing only a side are not intersecting
* - Zero-area rectangles cannot intersect anything
* - Supports optional transformation matrix
* @param other - The Rectangle to intersect with `this`
* @param transform - Optional transformation matrix of `other`
* @returns True if the transformed `other` Rectangle intersects with `this`
* @see {@link Rectangle.containsRect} For containment testing
* @see {@link Rectangle.contains} For point testing
*/
intersects(other: Rectangle, transform?: Matrix): boolean;
/**
* Pads the rectangle making it grow in all directions.
*
* If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
* @example
* ```ts
* // Basic padding
* const rect = new Rectangle(100, 100, 200, 150);
* rect.pad(10); // Adds 10px padding on all sides
*
* // Different horizontal and vertical padding
* const uiRect = new Rectangle(0, 0, 100, 50);
* uiRect.pad(20, 10); // 20px horizontal, 10px vertical
* ```
* @remarks
* - Adjusts x/y by subtracting padding
* - Increases width/height by padding * 2
* - Common in UI layout calculations
* - Chainable with other methods
* @param paddingX - The horizontal padding amount
* @param paddingY - The vertical padding amount
* @returns Returns itself
* @see {@link Rectangle.enlarge} For growing to include another rectangle
* @see {@link Rectangle.fit} For shrinking to fit within another rectangle
*/
pad(paddingX?: number, paddingY?: number): this;
/**
* Fits this rectangle around the passed one.
* @example
* ```ts
* // Basic fitting
* const container = new Rectangle(0, 0, 100, 100);
* const content = new Rectangle(25, 25, 200, 200);
* content.fit(container); // Clips to container bounds
* ```
* @param rectangle - The rectangle to fit around
* @returns Returns itself
* @see {@link Rectangle.enlarge} For growing to include another rectangle
* @see {@link Rectangle.pad} For adding padding around the rectangle
*/
fit(rectangle: Rectangle): this;
/**
* Enlarges rectangle so that its corners lie on a grid defined by resolution.
* @example
* ```ts
* // Basic grid alignment
* const rect = new Rectangle(10.2, 10.6, 100.8, 100.4);
* rect.ceil(); // Aligns to whole pixels
*
* // Custom resolution grid
* const uiRect = new Rectangle(5.3, 5.7, 50.2, 50.8);
* uiRect.ceil(0.5); // Aligns to half pixels
*
* // Use with precision value
* const preciseRect = new Rectangle(20.001, 20.999, 100.001, 100.999);
* preciseRect.ceil(1, 0.01); // Handles small decimal variations
* ```
* @param resolution - The grid size to align to (1 = whole pixels)
* @param eps - Small number to prevent floating point errors
* @returns Returns itself
* @see {@link Rectangle.fit} For constraining to bounds
* @see {@link Rectangle.enlarge} For growing dimensions
*/
ceil(resolution?: number, eps?: number): this;
/**
* Scales the rectangle's dimensions and position by the specified factors.
* @example
* ```ts
* const rect = new Rectangle(50, 50, 100, 100);
*
* // Scale uniformly
* rect.scale(0.5, 0.5);
* // rect is now: x=25, y=25, width=50, height=50
*
* // non-uniformly
* rect.scale(0.5, 1);
* // rect is now: x=25, y=50, width=50, height=100
* ```
* @param x - The factor by which to scale the horizontal properties (x, width).
* @param y - The factor by which to scale the vertical properties (y, height).
* @returns Returns itself
*/
scale(x: number, y?: number): this;
/**
* Enlarges this rectangle to include the passed rectangle.
* @example
* ```ts
* // Basic enlargement
* const rect = new Rectangle(50, 50, 100, 100);
* const other = new Rectangle(0, 0, 200, 75);
* rect.enlarge(other);
* // rect is now: x=0, y=0, width=200, height=150
*
* // Use for bounding box calculation
* const bounds = new Rectangle();
* objects.forEach((obj) => {
* bounds.enlarge(obj.getBounds());
* });
* ```
* @param rectangle - The rectangle to include
* @returns Returns itself
* @see {@link Rectangle.fit} For shrinking to fit within another rectangle
* @see {@link Rectangle.pad} For adding padding around the rectangle
*/
enlarge(rectangle: Rectangle): this;
/**
* Returns the framing rectangle of the rectangle as a Rectangle object
* @example
* ```ts
* // Basic bounds retrieval
* const rect = new Rectangle(100, 100, 200, 150);
* const bounds = rect.getBounds();
*
* // Reuse existing rectangle
* const out = new Rectangle();
* rect.getBounds(out);
* ```
* @param out - Optional rectangle to store the result
* @returns The framing rectangle
* @see {@link Rectangle.copyFrom} For direct copying
* @see {@link Rectangle.clone} For creating new copy
*/
getBounds(out?: Rectangle): Rectangle;
/**
* Determines whether another Rectangle is fully contained within this Rectangle.
*
* Rectangles that occupy the same space are considered to be containing each other.
*
* Rectangles without area (width or height equal to zero) can't contain anything,
* not even other arealess rectangles.
* @example
* ```ts
* // Check if one rectangle contains another
* const container = new Rectangle(0, 0, 100, 100);
* const inner = new Rectangle(25, 25, 50, 50);
*
* console.log(container.containsRect(inner)); // true
*
* // Check overlapping rectangles
* const partial = new Rectangle(75, 75, 50, 50);
* console.log(container.containsRect(partial)); // false
*
* // Zero-area rectangles
* const empty = new Rectangle(0, 0, 0, 100);
* console.log(container.containsRect(empty)); // false
* ```
* @param other - The Rectangle to check for containment
* @returns True if other is fully contained within this Rectangle
* @see {@link Rectangle.contains} For point containment
* @see {@link Rectangle.intersects} For overlap testing
*/
containsRect(other: Rectangle): boolean;
/**
* Sets the position and dimensions of the rectangle.
* @example
* ```ts
* // Basic usage
* const rect = new Rectangle();
* rect.set(100, 100, 200, 150);
*
* // Chain with other operations
* const bounds = new Rectangle()
* .set(0, 0, 100, 100)
* .pad(10);
* ```
* @param x - The X coordinate of the upper-left corner of the rectangle
* @param y - The Y coordinate of the upper-left corner of the rectangle
* @param width - The overall width of the rectangle
* @param height - The overall height of the rectangle
* @returns Returns itself for method chaining
* @see {@link Rectangle.copyFrom} For copying from another rectangle
* @see {@link Rectangle.clone} For creating a new copy
*/
set(x: number, y: number, width: number, height: number): this;
toString(): string;
}
/**
* Base options for destroying display objects.
* Controls how deep the destruction process should go through the display tree.
* @example
* ```ts
* // Basic destruction - only this container
* container.destroy({ children: false });
*
* // Deep destruction - container and all children
* container.destroy({ children: true });
*
* // Cleanup pattern
* function cleanupScene(scene: Container) {
* // Remove from parent first
* scene.parent?.removeChild(scene);
* // Then destroy with all children
* scene.destroy({ children: true });
* }
* ```
* @see {@link Container#destroy} For destruction method
* @see {@link DestroyOptions} For all destroy options
* @category scene
* @standard
*/
export interface BaseDestroyOptions {
/**
* Whether to destroy children recursively.
* When true, runs destroy() on all children in the display tree.
* @default false
* @example
* ```js
* container.destroy({ children: true });
* ```
*/
children?: boolean;
}
/**
* Options when destroying textures through `.destroy()` calls.
* Controls how thoroughly textures and their sources are cleaned up.
* @example
* ```ts
* // Basic texture cleanup
* sprite.destroy({
* texture: true
* });
*
* // Complete texture cleanup
* sprite.destroy({
* texture: true,
* textureSource: true
* });
* ```
* @see {@link Container#destroy} For general destruction
* @see {@link Texture#destroy} For texture cleanup
* @category scene
* @standard
*/
export interface TextureDestroyOptions {
/**
* Whether to destroy the texture for the display object.
* @default false
* @example
* ```js
* texturedObject.destroy({ texture: true });
* ```
*/
texture?: boolean;
/**
* Whether to destroy the underlying texture source.
* Use carefully with shared texture sources.
* @default false
* @example
* ```js
* texturedObject.destroy({ textureSource: true });
* ```
*/
textureSource?: boolean;
}
/**
* Options when destroying a graphics context.
* Controls the cleanup of graphics-specific resources.
* @example
* ```ts
* // Basic context cleanup
* graphics.destroy({
* context: true
* });
*
* // Full graphics cleanup
* graphics.destroy({
* context: true,
* texture: true,
* textureSource: true
* });
* ```
* @see {@link Graphics#destroy} For graphics destruction
* @see {@link DestroyOptions} For all destroy options
* @category scene
* @standard
*/
export interface ContextDestroyOptions {
/**
* Whether to destroy the graphics context associated with the graphics object.
* @default false
* @example
* ```js
* graphics.destroy({ context: true });
* ```
*/
context?: boolean;
}
/**
* Options when destroying a text object. Controls whether associated text styles
* should be cleaned up along with the text object itself.
* ```ts
* // Basic text cleanup
* text.destroy({ style: false }); // Keep style for reuse
* text.destroy({ style: true }); // Destroy style as well
* ```
* @category text
* @standard
*/
export interface TextDestroyOptions {
/**
* Whether to destroy the text style object along with the text.
* Use carefully with shared styles.
* @default false
*/
style?: boolean;
}
/**
* A utility type that allows a type to be either the specified type or a boolean.
* This is useful for options that can be either a specific value or a boolean flag.
* @category utils
* @advanced
*/
export type TypeOrBool<T> = T | boolean;
/**
* Options for destroying a container and its resources.
* Combines all destroy options into a single configuration object.
* @example
* ```ts
* // Destroy the container and all its children, including textures and styles
* container.destroy({
* children: true,
* texture: true,
* textureSource: true,
* context: true,
* style: true
* });
* ```
* @category scene
* @standard
*/
export type DestroyOptions = TypeOrBool<BaseDestroyOptions & ContextDestroyOptions & TextureDestroyOptions & TextDestroyOptions>;
/**
* Constants used by the renderer for clearing the screen or render textures.
* @category rendering
* @advanced
*/
export declare enum CLEAR {
/** No clear operation. */
NONE = 0,
/** Clear the color buffer. */
COLOR = 16384,
/** Clear the stencil buffer. */
STENCIL = 1024,
/** Clear the depth buffer. */
DEPTH = 256,
/** Clear the color and depth buffers. */
COLOR_DEPTH = 16640,
/** Clear the color and stencil buffers. */
COLOR_STENCIL = 17408,
/** Clear the depth and stencil buffers. */
DEPTH_STENCIL = 1280,
/** Clear the color, depth, and stencil buffers. */
ALL = 17664
}
/**
* Used for clearing render textures. true is the same as `ALL` false is the same as `NONE`
* @category rendering
* @advanced
*/
export type CLEAR_OR_BOOL = CLEAR | boolean;
/**
* A system is a generic interface for a renderer system.
* It is used to define the methods that a system should implement.
* @category rendering
* @advanced
*/
export interface System<INIT_OPTIONS = null, DESTROY_OPTIONS = RendererDestroyOptions> {
init?: (options: INIT_OPTIONS) => void;
/** Generic destroy methods to be overridden by the subclass */
destroy?: (options?: DESTROY_OPTIONS) => void;
}
/**
* The constructor for a System.
* It is used to create instances of systems that can be added to a renderer.
* @category rendering
* @advanced
*/
export interface SystemConstructor {
new (renderer: Renderer): System;
}
/**
* Options for the background system.
* @category rendering
* @advanced
*/
export interface BackgroundSystemOptions {
/**
* The background color used to clear the canvas. See {@link ColorSource} for accepted color values.
* @default 'black'
*/
backgroundColor: ColorSource;
/** Alias for `backgroundColor` */
background?: ColorSource;
/**
* Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
* This value determines whether the canvas is initialized with alpha transparency support.
* Note: This cannot be changed after initialization. If set to `1`, the canvas will remain opaque,
* even if a transparent background color is set later.
* @default 1
*/
backgroundAlpha?: number;
/**
* Whether to clear the canvas before new render passes.
* @default true
*/
clearBeforeRender?: boolean;
}
/**
* The background system manages the background color and alpha of the main view.
* @category rendering
* @advanced
*/
export declare class BackgroundSystem implements System<BackgroundSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "background";
readonly priority: 0;
};
/** default options used by the system */
static defaultOptions: BackgroundSystemOptions;
/**
* This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
* If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every
* frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect
* to clear the canvas every frame. Disable this by setting this to false. For example, if
* your game has a canvas filling background image you often don't need this set.
*/
clearBeforeRender: boolean;
private readonly _backgroundColor;
constructor();
/**
* initiates the background system
* @param options - the options for the background colors
*/
init(options: BackgroundSystemOptions): void;
/** The background color to fill if not transparent */
get color(): Color;
set color(value: ColorSource);
/** The background color alpha. Setting this to 0 will make the canvas transparent. */
get alpha(): number;
set alpha(value: number);
/** The background color as an [R, G, B, A] array. */
get colorRgba(): RgbaArray;
/**
* destroys the background system
* @internal
*/
destroy(): void;
}
/**
* Various GL texture/resources formats.
* @category rendering
* @advanced
*/
export declare enum GL_FORMATS {
RGBA = 6408,
RGB = 6407,
RG = 33319,
RED = 6403,
RGBA_INTEGER = 36249,
RGB_INTEGER = 36248,
RG_INTEGER = 33320,
RED_INTEGER = 36244,
ALPHA = 6406,
LUMINANCE = 6409,
LUMINANCE_ALPHA = 6410,
DEPTH_COMPONENT = 6402,
DEPTH_STENCIL = 34041
}
/**
* Various GL target types.
* @category rendering
* @advanced
*/
export declare enum GL_TARGETS {
TEXTURE_2D = 3553,
TEXTURE_CUBE_MAP = 34067,
TEXTURE_2D_ARRAY = 35866,
TEXTURE_CUBE_MAP_POSITIVE_X = 34069,
TEXTURE_CUBE_MAP_NEGATIVE_X = 34070,
TEXTURE_CUBE_MAP_POSITIVE_Y = 34071,
TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072,
TEXTURE_CUBE_MAP_POSITIVE_Z = 34073,
TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074
}
/**
* The wrap modes that are supported by pixi.
*
* The {@link WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
* It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
* If the texture is non power of two then clamp will be used regardless as WebGL can
* only use REPEAT if the texture is po2.
*
* This property only affects WebGL.
* @category rendering
* @advanced
*/
export declare enum GL_WRAP_MODES {
/**
* The textures uvs are clamped
* @default 33071
*/
CLAMP = 33071,
/**
* The texture uvs tile and repeat
* @default 10497
*/
REPEAT = 10497,
/**
* The texture uvs tile and repeat with mirroring
* @default 33648
*/
MIRRORED_REPEAT = 33648
}
/** @internal */
export declare enum GL_TYPES {
/**
* 8 bits per channel for gl.RGBA
* @default 5121
*/
UNSIGNED_BYTE = 5121,
/** @default 5123 */
UNSIGNED_SHORT = 5123,
/**
* 5 red bits, 6 green bits, 5 blue bits.
* @default 33635
*/
UNSIGNED_SHORT_5_6_5 = 33635,
/**
* 4 red bits, 4 green bits, 4 blue bits, 4 alpha bits.
* @default 32819
*/
UNSIGNED_SHORT_4_4_4_4 = 32819,
/**
* 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit.
* @default 32820
*/
UNSIGNED_SHORT_5_5_5_1 = 32820,
/** @default 5125 */
UNSIGNED_INT = 5125,
/** @default 35899 */
UNSIGNED_INT_10F_11F_11F_REV = 35899,
/** @default 33640 */
UNSIGNED_INT_2_10_10_10_REV = 33640,
/** @default 34042 */
UNSIGNED_INT_24_8 = 34042,
/** @default 35902 */
UNSIGNED_INT_5_9_9_9_REV = 35902,
/** @default 5120 */
BYTE = 5120,
/** @default 5122 */
SHORT = 5122,
/** @default 5124 */
INT = 5124,
/** @default 5126 */
FLOAT = 5126,
/** @default 36269 */
FLOAT_32_UNSIGNED_INT_24_8_REV = 36269,
/** @default 36193 */
HALF_FLOAT = 36193
}
/**
* Internal texture for WebGL context
* @category rendering
* @ignore
*/
export declare class GlTexture implements GPUData {
target: GL_TARGETS;
/** The WebGL texture. */
texture: WebGLTexture;
/** Width of texture that was used in texImage2D. */
width: number;
/** Height of texture that was used in texImage2D. */
height: number;
/** Whether mip levels has to be generated. */
mipmap: boolean;
/** Type copied from texture source. */
type: number;
/** Type copied from texture source. */
internalFormat: number;
/** Type of sampler corresponding to this texture. See {@link SAMPLER_TYPES} */
samplerType: number;
format: GL_FORMATS;
constructor(texture: WebGLTexture);
destroy(): void;
}
/**
* an interface that allows a resource to be bound to the gpu in a bind group
* @category rendering
* @advanced
*/
export interface BindResource {
/**
* The type of resource this is
* @ignore
*/
_resourceType: string;
/**
* Unique id for this resource this can change and is used to link the gpu
* @ignore
*/
_resourceId: number;
_touched: number;
/**
* a boolean that indicates if the resource has been destroyed.
* If true, the resource should not be used and any bind groups
* that will release any references to this resource.
* @ignore
*/
destroyed: boolean;
/**
* event dispatch whenever the underlying resource needs to change
* this could be a texture or buffer that has been resized.
* This is important as it allows the renderer to know that it needs to rebind the resource
*/
on?(event: "change", listenerFunction: (resource: BindResource) => void, listener: BindGroup): void;
/** todo */
off?(event: "change", listenerFunction: (resource: BindResource) => void, listener: BindGroup): void;
}
/**
* A bind group is a collection of resources that are bound together for use by a shader.
* They are essentially a wrapper for the WebGPU BindGroup class. But with the added bonus
* that WebGL can also work with them.
* @see https://gpuweb.github.io/gpuweb/#dictdef-gpubindgroupdescriptor
* @example
* // Create a bind group with a single texture and sampler
* const bindGroup = new BindGroup({
* uTexture: texture.source,
* uTexture: texture.style,
* });
*
* Bind groups resources must implement the {@link BindResource} interface.
* The following resources are supported:
* - {@link TextureSource}
* - {@link TextureStyle}
* - {@link Buffer}
* - {@link BufferResource}
* - {@link UniformGroup}
*
* The keys in the bind group must correspond to the names of the resources in the GPU program.
*
* This bind group class will also watch for changes in its resources ensuring that the changes
* are reflected in the WebGPU BindGroup.
* @category rendering
* @advanced
*/
export declare class BindGroup {
/** The resources that are bound together for use by a shader. */
resources: Record<string, BindResource>;
/**
* a key used internally to match it up to a WebGPU Bindgroup
* @internal
*/
_key: string;
private _dirty;
/**
* Create a new instance eof the Bind Group.
* @param resources - The resources that are bound together for use by a shader.
*/
constructor(resources?: Record<string, BindResource>);
/**
* Updates the key if its flagged as dirty. This is used internally to
* match this bind group to a WebGPU BindGroup.
* @internal
*/
_updateKey(): void;
/**
* Set a resource at a given index. this function will
* ensure that listeners will be removed from the current resource
* and added to the new resource.
* @param resource - The resource to set.
* @param index - The index to set the resource at.
*/
setResource(resource: BindResource, index: number): void;
/**
* Returns the resource at the current specified index.
* @param index - The index of the resource to get.
* @returns - The resource at the specified index.
*/
getResource(index: number): BindResource;
/**
* Used internally to 'touch' each resource, to ensure that the GC
* knows that all resources in this bind group are still being used.
* @param now - The current time in milliseconds.
* @param tick - The current tick.
* @internal
*/
_touch(now: number, tick: number): void;
/** Destroys this bind group and removes all listeners. */
destroy(): void;
protected onResourceChange(resource: BindResource): void;
}
/**
* Data about the pixels of a texture.
* This includes the pixel data as a Uint8ClampedArray, and the width and height of the texture.
* @category rendering
* @advanced
*/
export type GetPixelsOutput = {
pixels: Uint8ClampedArray;
width: number;
height: number;
};
/** @internal */
export interface CanvasGenerator {
generateCanvas(texture: Texture): ICanvas;
getPixels(texture: Texture): GetPixelsOutput;
}
/**
* Specifies the alpha composition mode for textures.
*
* - `no-premultiply-alpha`: Does not premultiply alpha.
* - `premultiply-alpha-on-upload`: Premultiplies alpha on texture upload.
* - `premultiplied-alpha`: Assumes the texture is already in premultiplied alpha format.
* @category rendering
* @advanced
*/
export type ALPHA_MODES = "no-premultiply-alpha" | "premultiply-alpha-on-upload" | "premultiplied-alpha";
/**
* The texture formats that are supported by pixi.
*
* These formats are used to specify the format of textures in WebGPU and WebGL.
* They include various uncompressed, compressed, and depth/stencil formats.
* @category rendering
* @advanced
*/
export type TEXTURE_FORMATS = "r8unorm" | "r8snorm" | "r8uint" | "r8sint" | "r16uint" | "r16sint" | "r16float" | "rg8unorm" | "rg8snorm" | "rg8uint" | "rg8sint" | "r32uint" | "r32sint" | "r32float" | "rg16uint" | "rg16sint" | "rg16float" | "rgba8unorm" | "rgba8unorm-srgb" | "rgba8snorm" | "rgba8uint" | "rgba8sint" | "bgra8unorm" | "bgra8unorm-srgb" | "rgb9e5ufloat" | "rgb10a2unorm" | "rg11b10ufloat" | "rg32uint" | "rg32sint" | "rg32float" | "rgba16uint" | "rgba16sint" | "rgba16float" | "rgba32uint" | "rgba32sint" | "rgba32float" | "stencil8" | "depth16unorm" | "depth24plus" | "depth24plus-stencil8" | "depth32float" | "depth32float-stencil8" | "bc1-rgba-unorm" | "bc1-rgba-unorm-srgb" | "bc2-rgba-unorm" | "bc2-rgba-unorm-srgb" | "bc3-rgba-unorm" | "bc3-rgba-unorm-srgb" | "bc4-r-unorm" | "bc4-r-snorm" | "bc5-rg-unorm" | "bc5-rg-snorm" | "bc6h-rgb-ufloat" | "bc6h-rgb-float" | "bc7-rgba-unorm" | "bc7-rgba-unorm-srgb" | "etc2-rgb8unorm" | "etc2-rgb8unorm-srgb" | "etc2-rgb8a1unorm" | "etc2-rgb8a1unorm-srgb" | "etc2-rgba8unorm" | "etc2-rgba8unorm-srgb" | "eac-r11unorm" | "eac-r11snorm" | "eac-rg11unorm" | "eac-rg11snorm" | "astc-4x4-unorm" | "astc-4x4-unorm-srgb" | "astc-5x4-unorm" | "astc-5x4-unorm-srgb" | "astc-5x5-unorm" | "astc-5x5-unorm-srgb" | "astc-6x5-unorm" | "astc-6x5-unorm-srgb" | "astc-6x6-unorm" | "astc-6x6-unorm-srgb" | "astc-8x5-unorm" | "astc-8x5-unorm-srgb" | "astc-8x6-unorm" | "astc-8x6-unorm-srgb" | "astc-8x8-unorm" | "astc-8x8-unorm-srgb" | "astc-10x5-unorm" | "astc-10x5-unorm-srgb" | "astc-10x6-unorm" | "astc-10x6-unorm-srgb" | "astc-10x8-unorm" | "astc-10x8-unorm-srgb" | "astc-10x10-unorm" | "astc-10x10-unorm-srgb" | "astc-12x10-unorm" | "astc-12x10-unorm-srgb" | "astc-12x12-unorm" | "astc-12x12-unorm-srgb";
/**
* The texture dimensions that are supported by pixi.
*
* - `1d` is a one-dimensional texture, which is typically used for linear data.
* - `2d` is a two-dimensional texture, which is commonly used for images and textures.
* - `3d` is a three-dimensional texture, which is used for volumetric data or 3D textures.
* @category rendering
* @advanced
*/
export type TEXTURE_DIMENSIONS = "1d" | "2d" | "3d";
/**
* The wrap modes that are supported by pixi.
*
* The wrap mode affects the default wrapping mode of future operations.
* - `clamp-to-edge` is the default mode, which clamps the texture coordinates to the edge of the texture.
* - `repeat` allows the texture to repeat in both u and v directions.
* - `mirror-repeat` allows the texture to repeat in both u and v directions, but mirrors the texture on every other repeat.
* @category rendering
* @standard
*/
export type WRAP_MODE = "clamp-to-edge" | "repeat" | "mirror-repeat";
/** @internal */
export declare enum DEPRECATED_WRAP_MODES {
CLAMP = "clamp-to-edge",
REPEAT = "repeat",
MIRRORED_REPEAT = "mirror-repeat"
}
/**
* The wrap modes that are supported by pixi.
* @deprecated since 8.0.0
* @category rendering
* @see WRAP_MODE
* @advanced
*/
export declare const WRAP_MODES: typeof DEPRECATED_WRAP_MODES;
/**
* The scale modes that are supported by pixi.
*
* The scale mode affects the default scaling mode of future operations.
* It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
*
* - `nearest` is a pixelating scaling mode, which does not interpolate pixels.
* - `linear` is a smooth scaling mode, which interpolates pixels for smoother results.
* @category rendering
* @standard
*/
export type SCALE_MODE = "nearest" | "linear";
/** @internal */
export declare enum DEPRECATED_SCALE_MODES {
NEAREST = "nearest",
LINEAR = "linear"
}
/**
* The scale modes that are supported by pixi.
* @deprecated since 8.0.0
* @category rendering
* @see SCALE_MODE
* @advanced
*/
export declare const SCALE_MODES: typeof DEPRECATED_SCALE_MODES;
/**
* The compare function types used for comparing values in various operations.
* @category rendering
* @advanced
*/
export type COMPARE_FUNCTION = "never" | "less" | "equal" | "less-equal" | "greater" | "not-equal" | "greater-equal" | "always";
/**
* The options for the texture style.
* @category rendering
* @advanced
*/
export interface TextureStyleOptions extends Partial<TextureStyle> {
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
addressMode?: WRAP_MODE;
/** specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeU?: WRAP_MODE;
/** specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeV?: WRAP_MODE;
/** Specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeW?: WRAP_MODE;
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
scaleMode?: SCALE_MODE;
/** specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
magFilter?: SCALE_MODE;
/** specifies the sampling behavior when the sample footprint is larger than one texel. */
minFilter?: SCALE_MODE;
/** specifies behavior for sampling between mipmap levels. */
mipmapFilter?: SCALE_MODE;
/** specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMinClamp?: number;
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMaxClamp?: number;
/**
* When provided the sampler will be a comparison sampler with the specified
* {@link COMPARE_FUNCTION}.
* Note: Comparison samplers may use filtering, but the sampling results will be
* implementation-dependent and may differ from the normal filtering rules.
*/
compare?: COMPARE_FUNCTION;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link TextureStyle#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link TextureStyle#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
*
* setting this to anything higher than 1 will set scale modes to 'linear'
*/
maxAnisotropy?: number;
}
/**
* A texture style describes how a texture should be sampled by a shader.
* @category rendering
* @advanced
*/
export declare class TextureStyle extends EventEmitter<{
change: TextureStyle;
destroy: TextureStyle;
}> implements BindResource {
/** @internal */
_resourceType: string;
/** @internal */
_touched: number;
private _sharedResourceId;
/** default options for the style */
static readonly defaultOptions: TextureStyleOptions;
/** */
addressModeU?: WRAP_MODE;
/** */
addressModeV?: WRAP_MODE;
/** Specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeW?: WRAP_MODE;
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
magFilter?: SCALE_MODE;
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
minFilter?: SCALE_MODE;
/** Specifies behavior for sampling between mipmap levels. */
mipmapFilter?: SCALE_MODE;
/** */
lodMinClamp?: number;
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMaxClamp?: number;
/**
* When provided the sampler will be a comparison sampler with the specified
* {@link COMPARE_FUNCTION}.
* Note: Comparison samplers may use filtering, but the sampling results will be
* implementation-dependent and may differ from the normal filtering rules.
*/
compare?: COMPARE_FUNCTION;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link TextureStyle#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link TextureStyle#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
* @internal
*/
_maxAnisotropy?: number;
/**
* Has the style been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* @param options - options for the style
*/
constructor(options?: TextureStyleOptions);
set addressMode(value: WRAP_MODE);
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode(): WRAP_MODE;
set wrapMode(value: WRAP_MODE);
get wrapMode(): WRAP_MODE;
set scaleMode(value: SCALE_MODE);
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode(): SCALE_MODE;
/** Specifies the maximum anisotropy value clamp used by the sampler. */
set maxAnisotropy(value: number);
get maxAnisotropy(): number;
get _resourceId(): number;
update(): void;
private _generateResourceId;
/** Destroys the style */
destroy(): void;
}
/**
* Options for the {@link GCManagedHash}.
* @internal
*/
export interface GCManagedHashOptions<T extends GCable & {
uid: number;
} & Pick<EventEmitter, "once" | "off">> {
renderer: Renderer;
type: GCData["type"];
onUnload?: (item: T, ...args: any[]) => void;
priority?: number;
name: string;
}
/**
* A hash for managing renderable and resource resources with GC integration.
* @internal
*/
export declare class GCManagedHash<T extends GCable & {
uid: number;
} & Pick<EventEmitter, "once" | "off">> {
items: Record<number, T>;
private _renderer;
private _onUnload?;
readonly name: string;
constructor(options: GCManagedHashOptions<T>);
/**
* Add an item to the hash. No-op if already added.
* @param item
* @returns true if the item was added, false if it was already in the hash
*/
add(item: T): boolean;
remove(item: T, ...args: unknown[]): void;
removeAll(...args: unknown[]): void;
destroy(...args: unknown[]): void;
}
/**
* The different topology types supported by the renderer used to describe how the geometry should be renderer
* @category rendering
* @advanced
*/
export type Topology = "point-list" | "line-list" | "line-strip" | "triangle-list" | "triangle-strip";
/**
* @deprecated since 8.0.0
* @category rendering
* @advanced
*/
export declare const DRAW_MODES: {
POINTS: string;
LINES: string;
LINE_STRIP: string;
TRIANGLES: string;
TRIANGLE_STRIP: string;
};
/**
* The different types of vertex formats supported by the renderer
* @category rendering
* @advanced
*/
export type VertexFormat = "uint8x2" | "uint8x4" | "sint8x2" | "sint8x4" | "unorm8x2" | "unorm8x4" | "snorm8x2" | "snorm8x4" | "uint16x2" | "uint16x4" | "sint16x2" | "sint16x4" | "unorm16x2" | "unorm16x4" | "snorm16x2" | "snorm16x4" | "float16x2" | "float16x4" | "float32" | "float32x2" | "float32x3" | "float32x4" | "uint32" | "uint32x2" | "uint32x3" | "uint32x4" | "sint32" | "sint32x2" | "sint32x3" | "sint32x4";
/**
* The WebGL rendering context type used by the PixiJS WebGL renderer.
* This is typically a `WebGL2RenderingContext`, which is the default for PixiJS.
* It is used to ensure that the renderer operates with the correct context type.
* @category rendering
* @advanced
*/
export type GlRenderingContext = WebGL2RenderingContext;
/**
* Constants for various buffer types in Pixi
* @category rendering
* @advanced
*/
export declare enum BUFFER_TYPE {
/** buffer type for using as an index buffer */
ELEMENT_ARRAY_BUFFER = 34963,
/** buffer type for using attribute data */
ARRAY_BUFFER = 34962,
/** the buffer type is for uniform buffer objects */
UNIFORM_BUFFER = 35345
}
/** @internal */
export declare class GlBuffer implements GPUData {
buffer: WebGLBuffer;
updateID: number;
byteLength: number;
type: number;
_lastBindBaseLocation: number;
_lastBindCallId: number;
constructor(buffer: WebGLBuffer, type: BUFFER_TYPE);
destroy(): void;
}
/** @internal */
export declare class GpuBufferData implements GPUData {
gpuBuffer: GPUBuffer;
constructor(gpuBuffer: GPUBuffer);
destroy(): void;
}
/**
* System plugin to the renderer to manage buffers.
* @category rendering
* @advanced
*/
export declare class GpuBufferSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "buffer";
};
protected CONTEXT_UID: number;
private readonly _renderer;
private readonly _managedBuffers;
private _gpu;
constructor(renderer: WebGPURenderer);
protected contextChange(gpu: GPU$1): void;
getGPUBuffer(buffer: Buffer$1): GPUBuffer;
updateBuffer(buffer: Buffer$1): GPUBuffer;
/** dispose all WebGL resources of all managed buffers */
destroyAll(): void;
protected onBufferUnload(buffer: Buffer$1): void;
createGPUBuffer(buffer: Buffer$1): GPUBuffer;
protected onBufferChange(buffer: Buffer$1): void;
destroy(): void;
}
/**
* Buffer usage flags. they can be combined using the bitwise OR operator
* eg : BufferUsage.VERTEX | BufferUsage.INDEX
* @category rendering
* @advanced
*/
export declare enum BufferUsage {
/**
* The buffer can be mapped for reading. (Example: calling mapAsync() with GPUMapMode.READ)
* May only be combined with COPY_DST.
*/
MAP_READ = 1,
/**
* The buffer can be mapped for writing. (Example: calling mapAsync() with GPUMapMode.WRITE)
* May only be combined with COPY_SRC.
*/
MAP_WRITE = 2,
/**
* The buffer can be used as the source of a copy operation.
* (Examples: as the source argument of a copyBufferToBuffer() or copyBufferToTexture() call.)
*/
COPY_SRC = 4,
/**
* The buffer can be used as the destination of a copy or write operation.
* (Examples: as the destination argument of a copyBufferToBuffer() or
* copyTextureToBuffer() call, or as the target of a writeBuffer() call.)
*/
COPY_DST = 8,
/** The buffer can be used as an index buffer. (Example: passed to setIndexBuffer().) */
INDEX = 16,
/** The buffer can be used as a vertex buffer. (Example: passed to setVertexBuffer().) */
VERTEX = 32,
/**
* The buffer can be used as a uniform buffer.
* (Example: as a bind group entry for a GPUBufferBindingLayout with a buffer.type of "uniform".)
*/
UNIFORM = 64,
/**
* The buffer can be used as a storage buffer.
* (Example: as a bind group entry for a GPUBufferBindingLayout with a buffer.type of "storage" or "read-only-storage".)
*/
STORAGE = 128,
/**
* The buffer can be used as to store indirect command arguments.
* (Examples: as the indirectBuffer argument of a drawIndirect() or dispatchWorkgroupsIndirect() call.)
*/
INDIRECT = 256,
/**
* The buffer can be used to capture query results.
* (Example: as the destination argument of a resolveQuerySet() call.)
*/
QUERY_RESOLVE = 512,
/** the buffer will not be updated frequently */
STATIC = 1024
}
/**
* All the various typed arrays that exist in js
* @category rendering
* @advanced
*/
export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array;
/**
* Options for creating a buffer
*
* This interface defines the options that can be passed to the Buffer constructor.
* It includes the data to initialize the buffer with, the size of the buffer,
* the usage of the buffer, a label for debugging, and whether the buffer should shrink to fit
* when the data becomes smaller.
* @category rendering
* @advanced
*/
export interface BufferOptions {
/**
* the data to initialize the buffer with, this can be a typed array,
* or a regular number array. If it is a number array, it will be converted to a Float32Array
*/
data?: TypedArray | number[];
/** the size of the buffer in bytes, if not supplied, it will be inferred from the data */
size?: number;
/** the usage of the buffer, see {@link BufferUsage} */
usage: number;
/** a label for the buffer, this is useful for debugging */
label?: string;
/**
* should the GPU buffer be shrunk when the data becomes smaller?
* changing this will cause the buffer to be destroyed and a new one created on the GPU
* this can be expensive, especially if the buffer is already big enough!
* setting this to false will prevent the buffer from being shrunk. This will yield better performance
* if you are constantly setting data that is changing size often.
* @default true
*/
shrinkToFit?: boolean;
}
/** @internal */
export interface BufferDescriptor {
label?: string;
size: GPUSize64;
usage: BufferUsage;
mappedAtCreation?: boolean;
}
/**
* A wrapper for a WebGPU/WebGL Buffer.
* In PixiJS, the Buffer class is used to manage the data that is sent to the GPU rendering pipeline.
* It abstracts away the underlying GPU buffer and provides an interface for uploading typed arrays or other data to the GPU,
* They are used in the following places:
* <br><br>
* .1. {@link Geometry} as attribute data or index data for geometry
* <br>
* .2. {@link UniformGroup} as an underlying buffer for uniform data
* <br>
* .3. {@link BufferResource} as an underlying part of a buffer used directly by the GPU program
* <br>
*
* It is important to note that you must provide a usage type when creating a buffer. This is because
* the underlying GPU buffer needs to know how it will be used. For example, if you are creating a buffer
* to hold vertex data, you would use `BufferUsage.VERTEX`. This will tell the GPU that this buffer will be
* used as a vertex buffer. This is important because it will affect how you can use the buffer.
*
* Buffers are updated by calling the {@link Buffer.update} method. This immediately updates the buffer on the GPU.
* Be mindful of calling this more often than you need to. It is recommended to update buffers only when needed.
*
* In WebGPU, a GPU buffer cannot resized. This limitation is abstracted away, but know that resizing a buffer means
* creating a brand new one and destroying the old, so it is best to limit this if possible.
* @example
*
* const buffer = new Buffer({
* data: new Float32Array([1, 2, 3, 4]),
* usage: BufferUsage.VERTEX,
* });
* @category rendering
* @advanced
*/
declare class Buffer$1 extends EventEmitter<{
change: BindResource;
update: Buffer$1;
destroy: Buffer$1;
unload: Buffer$1;
}> implements BindResource, GPUDataOwner, GCable {
/**
* emits when the underlying buffer has changed shape (i.e. resized)
* letting the renderer know that it needs to discard the old buffer on the GPU and create a new one
* @event change
*/
/**
* emits when the underlying buffer data has been updated. letting the renderer know
* that it needs to update the buffer on the GPU
* @event update
*/
/**
* emits when the buffer is destroyed. letting the renderer know that it needs to destroy the buffer on the GPU
* @event destroy
*/
/** @internal */
_gpuData: Record<number, GlBuffer | GpuBufferData>;
/** @internal */
_gcData?: GCData;
/** @internal */
_gcLastUsed: number;
/** If set to true, the buffer will be garbage collected automatically when it is not used. */
autoGarbageCollect: boolean;
/** a unique id for this uniform group used through the renderer */
readonly uid: number;
/**
* a resource type, used to identify how to handle it when its in a bind group / shader resource
* @internal
*/
readonly _resourceType = "buffer";
/**
* the resource id used internally by the renderer to build bind group keys
* @internal
*/
_resourceId: number;
/**
* used internally to know if a uniform group was used in the last render pass
* @internal
*/
_touched: number;
/**
* a description of the buffer and how it should be set up on the GPU
* @internal
*/
readonly descriptor: BufferDescriptor;
/** @internal */
_updateID: number;
/** @internal */
_updateSize: number;
private _data;
private _dataInt32;
/**
* should the GPU buffer be shrunk when the data becomes smaller?
* changing this will cause the buffer to be destroyed and a new one created on the GPU
* this can be expensive, especially if the buffer is already big enough!
* setting this to false will prevent the buffer from being shrunk. This will yield better performance
* if you are constantly setting data that is changing size often.
* @default true
*/
shrinkToFit: boolean;
/**
* Has the buffer been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* Creates a new Buffer with the given options
* @param options - the options for the buffer
*/
constructor(options: BufferOptions);
/** the data in the buffer */
get data(): TypedArray;
set data(value: TypedArray);
get dataInt32(): Int32Array;
/** whether the buffer is static or not */
get static(): boolean;
set static(value: boolean);
/**
* Sets the data in the buffer to the given value. This will immediately update the buffer on the GPU.
* If you only want to update a subset of the buffer, you can pass in the size of the data.
* @param value - the data to set
* @param size - the size of the data in bytes
* @param syncGPU - should the buffer be updated on the GPU immediately?
*/
setDataWithSize(value: TypedArray, size: number, syncGPU: boolean): void;
/**
* updates the buffer on the GPU to reflect the data in the buffer.
* By default it will update the entire buffer. If you only want to update a subset of the buffer,
* you can pass in the size of the buffer to update.
* @param sizeInBytes - the new size of the buffer in bytes
*/
update(sizeInBytes?: number): void;
/** Unloads the buffer from the GPU */
unload(): void;
/** Destroys the buffer */
destroy(): void;
}
/** @internal */
export interface GlUniformData {
name: string;
index: number;
type: string;
size: number;
isArray: boolean;
value: any;
}
/** @internal */
export interface GlUniformBlockData {
index: number;
name: string;
size: number;
value?: TypedArray;
}
/**
* The options for the gl program
* @category rendering
* @advanced
*/
export interface GlProgramOptions {
/** The fragment glsl shader source. */
fragment: string;
/** The vertex glsl shader source. */
vertex: string;
/** the name of the program, defaults to 'pixi-program' */
name?: string;
/** the preferred vertex precision for the shader, this may not be used if the device does not support it */
preferredVertexPrecision?: string;
/** the preferred fragment precision for the shader, this may not be used if the device does not support it */
preferredFragmentPrecision?: string;
transformFeedbackVaryings?: {
names: string[];
bufferMode: "separate" | "interleaved";
};
}
/**
* A wrapper for a WebGL Program. You can create one and then pass it to a shader.
* This will manage the WebGL program that is compiled and uploaded to the GPU.
*
* To get the most out of this class, you should be familiar with glsl shaders and how they work.
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLProgram
* @example
*
* // Create a new program
* const program = new GlProgram({
* vertex: '...',
* fragment: '...',
* });
*
*
* There are a few key things that pixi shader will do for you automatically:
* <br>
* - If no precision is provided in the shader, it will be injected into the program source for you.
* This precision will be taken form the options provided, if none is provided,
* then the program will default to the defaultOptions.
* <br>
* - It will inject the program name into the shader source if none is provided.
* <br>
* - It will set the program version to 300 es.
*
* For optimal usage and best performance, its best to reuse programs as much as possible.
* You should use the {@link GlProgram.from} helper function to create programs.
* @class
* @category rendering
* @advanced
*/
export declare class GlProgram {
/** The default options used by the program. */
static defaultOptions: Partial<GlProgramOptions>;
/** the fragment glsl shader source. */
readonly fragment?: string;
/** the vertex glsl shader source */
readonly vertex?: string;
/**
* attribute data extracted from the program once created this happens when the program is used for the first time
* @internal
*/
_attributeData: Record<string, ExtractedAttributeData>;
/**
* uniform data extracted from the program once created this happens when the program is used for the first time
* @internal
*/
_uniformData: Record<string, GlUniformData>;
/**
* uniform data extracted from the program once created this happens when the program is used for the first time
* @internal
*/
_uniformBlockData: Record<string, GlUniformBlockData>;
/** details on how to use this program with transform feedback */
transformFeedbackVaryings?: {
names: string[];
bufferMode: "separate" | "interleaved";
};
/**
* the key that identifies the program via its source vertex + fragment
* @internal
*/
readonly _key: number;
/**
* A cache key used to identify the program instance.
* @internal
*/
_cacheKey: string;
/**
* Creates a shiny new GlProgram. Used by WebGL renderer.
* @param options - The options for the program.
*/
constructor(options: GlProgramOptions);
/** destroys the program */
destroy(): void;
/**
* Helper function that creates a program for a given source.
* It will check the program cache if the program has already been created.
* If it has that one will be returned, if not a new one will be created and cached.
* @param options - The options for the program.
* @returns A program using the same source
*/
static from(options: GlProgramOptions): GlProgram;
}
/**
* Stores GPU-specific data for a Geometry instance in WebGL context.
*
* This class manages Vertex Array Object (VAO) caching for geometries,
* allowing efficient reuse of VAOs across different shader programs.
* Each geometry can have multiple VAOs cached, one for each unique
* shader program signature it's used with.
* @internal
*/
export declare class GlGeometryGpuData implements GPUData {
vaoCache: Record<string, WebGLVertexArrayObject>;
constructor();
destroy(): void;
}
/**
* System plugin to the renderer to manage geometry.
* @category rendering
* @advanced
*/
export declare class GlGeometrySystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "geometry";
};
/**
* `true` if we has `*_vertex_array_object` extension.
* @readonly
*/
hasVao: boolean;
/**
* `true` if has `ANGLE_instanced_arrays` extension.
* @readonly
*/
hasInstance: boolean;
protected gl: GlRenderingContext;
protected _activeGeometry: Geometry;
/** @internal */
_activeVao: WebGLVertexArrayObject;
/** @internal */
_managedGeometries: GCManagedHash<Geometry>;
/** Renderer that owns this {@link GeometrySystem}. */
private _renderer;
/** @param renderer - The renderer this System works for. */
constructor(renderer: WebGLRenderer);
/** Sets up the renderer context and necessary buffers. */
protected contextChange(): void;
/**
* Binds geometry so that is can be drawn. Creating a Vao if required
* @param geometry - Instance of geometry to bind.
* @param program - Instance of program to use vao for.
*/
bind(geometry?: Geometry, program?: GlProgram): void;
/** Reset and unbind any active VAO and geometry. */
resetState(): void;
/** Update buffers of the currently bound geometry. */
updateBuffers(): void;
/**
* Check compatibility between a geometry and a program
* @param geometry - Geometry instance.
* @param program - Program instance.
*/
protected checkCompatibility(geometry: Geometry, program: GlProgram): void;
/**
* Takes a geometry and program and generates a unique signature for them.
* @param geometry - To get signature from.
* @param program - To test geometry against.
* @returns - Unique signature of the geometry and program
*/
protected getSignature(geometry: Geometry, program: GlProgram): string;
protected getVao(geometry: Geometry, program: GlProgram): WebGLVertexArrayObject;
/**
* Creates or gets Vao with the same structure as the geometry and stores it on the geometry.
* If vao is created, it is bound automatically. We use a shader to infer what and how to set up the
* attribute locations.
* @param geometry - Instance of geometry to to generate Vao for.
* @param program
* @param _incRefCount - Increment refCount of all geometry buffers.
*/
protected initGeometryVao(geometry: Geometry, program: GlProgram, _incRefCount?: boolean): WebGLVertexArrayObject;
protected onGeometryUnload(geometry: Geometry, contextLost?: boolean): void;
/**
* Dispose all WebGL resources of all managed geometries.
* @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls
*/
destroyAll(contextLost?: boolean): void;
/**
* Activate vertex array object.
* @param geometry - Geometry instance.
* @param program - Shader program instance.
*/
protected activateVao(geometry: Geometry, program: GlProgram): void;
/**
* Draws the currently bound geometry.
* @param topology - The type primitive to render.
* @param size - The number of elements to be rendered. If not specified, all vertices after the
* starting vertex will be drawn.
* @param start - The starting vertex in the geometry to start drawing from. If not specified,
* drawing will start from the first vertex.
* @param instanceCount - The number of instances of the set of elements to execute. If not specified,
* all instances will be drawn.
* @returns This instance of the geometry system.
*/
draw(topology?: Topology, size?: number, start?: number, instanceCount?: number): this;
/** Unbind/reset everything. */
protected unbind(): void;
destroy(): void;
}
/**
* The index buffer array type used in geometries.
* @category rendering
* @advanced
*/
export type IndexBufferArray = Uint16Array | Uint32Array;
/**
* The attribute data for a geometries attributes
* @category rendering
* @advanced
*/
export interface Attribute {
/** the buffer that this attributes data belongs to */
buffer: Buffer$1;
/** the format of the attribute */
format?: VertexFormat;
/** the stride of the data in the buffer - in bytes*/
stride?: number;
/** the offset of the attribute from the buffer, defaults to 0 - in bytes*/
offset?: number;
/** is this an instanced buffer? (defaults to false) */
instance?: boolean;
/** the number of elements to be rendered. If not specified, all vertices after the starting vertex will be drawn. */
size?: number;
/**
* the starting vertex in the geometry to start drawing from. If not specified,
* drawing will start from the first vertex.
*/
start?: number;
/**
* attribute divisor for instanced rendering. Note: this is a **WebGL-only** feature, the WebGPU renderer will
* issue a warning if one of the attributes has divisor set.
*/
divisor?: number;
}
/**
* The attribute option used by the constructor for adding geometries attributes
* extends {@link Attribute} but allows for the buffer to be a typed or number array
* @category rendering
* @advanced
*/
export type AttributeOption = Omit<Attribute, "buffer"> & {
buffer: Buffer$1 | TypedArray | number[];
} | Buffer$1 | TypedArray | number[];
/**
* The attribute options used by the constructor for adding geometries attributes
* extends {@link Attribute} but allows for the buffer to be a typed or number array
* @category rendering
* @advanced
*/
export type AttributeOptions = Record<string, AttributeOption>;
/**
* the interface that describes the structure of the geometry
* @category rendering
* @advanced
*/
export interface GeometryDescriptor {
/** an optional label to easily identify the geometry */
label?: string;
/** the attributes that make up the geometry */
attributes?: AttributeOptions;
/** optional index buffer for this geometry */
indexBuffer?: Buffer$1 | TypedArray | number[];
/** the topology of the geometry, defaults to 'triangle-list' */
topology?: Topology;
instanceCount?: number;
}
/**
* A Geometry is a low-level object that represents the structure of 2D shapes in terms of vertices and attributes.
* It's a crucial component for rendering as it describes the shape and format of the data that will go through the shaders.
* Essentially, a Geometry object holds the data you'd send to a GPU buffer.
*
* A geometry is basically made of two components:
* <br>
* <b>Attributes</b>: These are essentially arrays that define properties of the vertices like position, color,
* texture coordinates, etc. They map directly to attributes in your vertex shaders.
* <br>
* <b>Indices</b>: An optional array that describes how the vertices are connected.
* If not provided, vertices will be interpreted in the sequence they're given.
* @example
*
* const geometry = new Geometry({
* attributes: {
* aPosition: [ // add some positions
* 0, 0,
* 0, 100,
* 100, 100,
* 100, 0,
* ],
* aUv: [ // add some uvs
* 0, 0,
* 0, 1,
* 1, 1,
* 1, 0,
* ]
* }
* });
* @category rendering
* @advanced
*/
export declare class Geometry extends EventEmitter<{
update: Geometry;
destroy: Geometry;
unload: Geometry;
}> implements GPUDataOwner, GCable {
/** @internal */
_gpuData: Record<number, GlGeometryGpuData>;
/** @internal */
_gcData?: GCData;
/** If set to true, the resource will be garbage collected automatically when it is not used. */
autoGarbageCollect: boolean;
/** @internal */
_gcLastUsed: number;
/** The topology of the geometry. */
topology: Topology;
/** The unique id of the geometry. */
readonly uid: number;
/** A record of the attributes of the geometry. */
readonly attributes: Record<string, Attribute>;
/** The buffers that the attributes use */
readonly buffers: Buffer$1[];
/** The index buffer of the geometry */
indexBuffer: Buffer$1;
/**
* the layout key will be generated by WebGPU all geometries that have the same structure
* will have the same layout key. This is used to cache the pipeline layout
* @internal
*/
_layoutKey: number;
/** the instance count of the geometry to draw */
instanceCount: number;
private readonly _bounds;
private _boundsDirty;
/**
* Create a new instance of a geometry
* @param options - The options for the geometry.
*/
constructor(options?: GeometryDescriptor);
protected onBufferUpdate(): void;
/**
* Returns the requested attribute.
* @param id - The name of the attribute required
* @returns - The attribute requested.
*/
getAttribute(id: string): Attribute;
/**
* Returns the index buffer
* @returns - The index buffer.
*/
getIndex(): Buffer$1;
/**
* Returns the requested buffer.
* @param id - The name of the buffer required.
* @returns - The buffer requested.
*/
getBuffer(id: string): Buffer$1;
/**
* Used to figure out how many vertices there are in this geometry
* @returns the number of vertices in the geometry
*/
getSize(): number;
/**
* Adds an attribute to the geometry.
* @param name - The name of the attribute to add.
* @param attributeOption - The attribute option to add.
*/
addAttribute(name: string, attributeOption: AttributeOption): void;
/**
* Adds an index buffer to the geometry.
* @param indexBuffer - The index buffer to add. Can be a Buffer, TypedArray, or an array of numbers.
*/
addIndex(indexBuffer: Buffer$1 | TypedArray | number[]): void;
/** Returns the bounds of the geometry. */
get bounds(): Bounds;
/** Unloads the geometry from the GPU. */
unload(): void;
/**
* destroys the geometry.
* @param destroyBuffers - destroy the buffers associated with this geometry
*/
destroy(destroyBuffers?: boolean): void;
}
/**
* This interface represents the extracted attribute data from a WebGL program.
* It extends the `Attribute` interface but omits the `buffer` property.
* It includes an optional `location` property that indicates where the shader location is for this attribute.
* @category rendering
* @advanced
*/
export interface ExtractedAttributeData extends Omit<Attribute, "buffer"> {
/** set where the shader location is for this attribute */
location?: number;
}
/**
* returns the attribute data from the program
* @private
* @param {WebGLProgram} [program] - the WebGL program
* @param {WebGLRenderingContext} [gl] - the WebGL context
* @param sortAttributes
* @returns {object} the attribute data for this program
*/
export declare function extractAttributesFromGlProgram(program: WebGLProgram, gl: WebGLRenderingContextBase, sortAttributes?: boolean): Record<string, ExtractedAttributeData>;
/**
* Defines the structure of the extracted WGSL structs and groups.
* @category rendering
* @advanced
*/
export interface StructsAndGroups {
groups: {
group: number;
binding: number;
name: string;
isUniform: boolean;
type: string;
}[];
structs: {
name: string;
members: Record<string, string>;
}[];
}
/**
* @param wgsl
* @internal
*/
export declare function extractStructAndGroups(wgsl: string): StructsAndGroups;
/**
* a WebGPU descriptions of how the program is laid out
* @see https://gpuweb.github.io/gpuweb/#gpupipelinelayout
* @category rendering
* @advanced
*/
export type ProgramPipelineLayoutDescription = GPUBindGroupLayoutEntry[][];
/**
* a map the maps names of uniforms to group indexes
* @category rendering
* @advanced
*/
export type ProgramLayout = Record<string, number>[];
/**
* the program source
* @category rendering
* @advanced
*/
export interface ProgramSource {
/** The wgsl source code of the shader. */
source: string;
/** The main function to run in this shader */
entryPoint?: string;
}
/**
* The options for the gpu program
* @category rendering
* @advanced
*/
export interface GpuProgramOptions {
/**
* the name of the program, this is added to the label of the GPU Program created
* under the hood. Makes it much easier to debug!
*/
name?: string;
/** The fragment glsl shader source. */
fragment?: ProgramSource;
/** The vertex glsl shader source. */
vertex?: ProgramSource;
/** The layout of the program. If not provided, it will be generated from the shader sources. */
layout?: ProgramLayout;
/** The gpu layout of the program. If not provided, it will be generated from the shader sources. */
gpuLayout?: ProgramPipelineLayoutDescription;
}
/**
* A wrapper for a WebGPU Program, specifically designed for the WebGPU renderer.
* This class facilitates the creation and management of shader code that integrates with the WebGPU pipeline.
*
* To leverage the full capabilities of this class, familiarity with WGSL shaders is recommended.
* @see https://gpuweb.github.io/gpuweb/#index
* @example
*
* // Create a new program
* const program = new GpuProgram({
* vertex: {
* source: '...',
* entryPoint: 'main',
* },
* fragment:{
* source: '...',
* entryPoint: 'main',
* },
* });
*
*
* Note: Both fragment and vertex shader sources can coexist within a single WGSL source file
* this can make things a bit simpler.
*
* For optimal usage and best performance, it help to reuse programs whenever possible.
* The {@link GpuProgram.from} helper function is designed for this purpose, utilizing an
* internal cache to efficiently manage and retrieve program instances.
* By leveraging this function, you can significantly reduce overhead and enhance the performance of your rendering pipeline.
*
* An important distinction between WebGL and WebGPU regarding program data retrieval:
* While WebGL allows extraction of program information directly from its compiled state,
* WebGPU does not offer such a capability. Therefore, in the context of WebGPU, we're required
* to manually extract the program layout information from the source code itself.
* @category rendering
* @advanced
*/
export declare class GpuProgram {
/** The fragment glsl shader source. */
readonly fragment?: ProgramSource;
/** The vertex glsl shader source */
readonly vertex?: ProgramSource;
/**
* Mapping of uniform names to group indexes for organizing shader program uniforms.
* Automatically generated from shader sources if not provided.
* @example
* // Assuming a shader with two uniforms, `u_time` and `u_resolution`, grouped respectively:
* [
* { "u_time": 0 },
* { "u_resolution": 1 }
* ]
*/
readonly layout: ProgramLayout;
/**
* Configuration for the WebGPU bind group layouts, detailing resource organization for the shader.
* Generated from shader sources if not explicitly provided.
* @example
* // Assuming a shader program that requires two bind groups:
* [
* // First bind group layout entries
* [{ binding: 0, visibility: GPUShaderStage.VERTEX, type: "uniform-buffer" }],
* // Second bind group layout entries
* [{ binding: 1, visibility: GPUShaderStage.FRAGMENT, type: "sampler" },
* { binding: 2, visibility: GPUShaderStage.FRAGMENT, type: "sampled-texture" }]
* ]
*/
readonly gpuLayout: ProgramPipelineLayoutDescription;
/** @internal */
_layoutKey: number;
/** @internal */
_cacheKey: string;
/** @internal */
_attributeLocationsKey: number;
/** the structs and groups extracted from the shader sources */
readonly structsAndGroups: StructsAndGroups;
/**
* the name of the program, this is added to the label of the GPU Program created under the hood.
* Makes it much easier to debug!
*/
readonly name: string;
private _attributeData;
/** if true, the program will automatically assign global uniforms to group[0] */
autoAssignGlobalUniforms: boolean;
/** if true, the program will automatically assign local uniforms to group[1] */
autoAssignLocalUniforms: boolean;
/**
* Create a new GpuProgram
* @param options - The options for the gpu program
*/
constructor(options: GpuProgramOptions);
private _generateProgramKey;
get attributeData(): Record<string, ExtractedAttributeData>;
/** destroys the program */
destroy(): void;
/**
* Helper function that creates a program for a given source.
* It will check the program cache if the program has already been created.
* If it has that one will be returned, if not a new one will be created and cached.
* @param options - The options for the program.
* @returns A program using the same source
*/
static from(options: GpuProgramOptions): GpuProgram;
}
/**
* This manages the WebGPU bind groups. this is how data is bound to a shader when rendering
* @category rendering
* @advanced
*/
export declare class BindGroupSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "bindGroup";
};
private readonly _renderer;
private _hash;
private _gpu;
constructor(renderer: WebGPURenderer);
protected contextChange(gpu: GPU$1): void;
getBindGroup(bindGroup: BindGroup, program: GpuProgram, groupIndex: number): GPUBindGroup;
private _createBindGroup;
destroy(): void;
}
/**
* The system that handles color masking for the GPU.
* @category rendering
* @advanced
*/
export declare class GpuColorMaskSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "colorMask";
};
private readonly _renderer;
private _colorMaskCache;
constructor(renderer: WebGPURenderer);
setMask(colorMask: number): void;
destroy(): void;
}
/**
* A record of {@link BindGroup}'s used by the shader.
*
* `Record<number, BindGroup>`
* @category rendering
* @advanced
*/
export type ShaderGroups = Record<number, BindGroup>;
interface ShaderBase {
/** The WebGL program used by the WebGL renderer. */
glProgram?: GlProgram;
/** The WebGPU program used by the WebGPU renderer. */
gpuProgram?: GpuProgram;
/**
* A number that uses two bits on whether the shader is compatible with the WebGL renderer and/or the WebGPU renderer.
* 0b00 - not compatible with either
* 0b01 - compatible with WebGL
* 0b10 - compatible with WebGPU
* This is automatically set based on if a {@link GlProgram} or {@link GpuProgram} is provided.
*/
compatibleRenderers?: number;
}
/**
* A base interface for shaders that includes the common properties.
* @category rendering
* @advanced
*/
export interface GlShaderWith extends ShaderBase {
/** The WebGL program used by the WebGL renderer. */
glProgram: GlProgram;
}
/**
* A base interface for shaders that includes the common properties.
* @category rendering
* @advanced
*/
export interface GpuShaderWith extends ShaderBase {
/** The WebGPU program used by the WebGPU renderer. */
gpuProgram: GpuProgram;
}
/**
* A descriptor for a shader with groups.
* This is used to define a shader that uses {@link BindGroup}'s.
* @category rendering
* @advanced
*/
export interface ShaderWithGroupsDescriptor {
/** A record of {@link BindGroup}'s used by the shader. */
groups: ShaderGroups;
/** an optional map of how to bind the groups. This is automatically generated by reading the WebGPU program */
groupMap?: Record<string, Record<string, any>>;
}
interface ShaderWithResourcesDescriptor {
/**
* A key value of uniform resources used by the shader.
* Under the hood pixi will look at the provided shaders and figure out where
* the resources are mapped. Its up to you to make sure the resource key
* matches the uniform name in the webGPU program. WebGL is a little more forgiving!
*/
resources?: Record<string, any>;
}
/**
* A descriptor for a shader
* @category rendering
* @advanced
*/
export type ShaderWith = GlShaderWith | GpuShaderWith;
/**
* A descriptor for a shader with groups.
* @category rendering
* @advanced
*/
export type ShaderWithGroups = ShaderWithGroupsDescriptor & ShaderWith;
/**
* A descriptor for a shader with resources. This is an easier way to work with uniforms.
* especially when you are not working with bind groups
* @category rendering
* @advanced
*/
export type ShaderWithResources = ShaderWithResourcesDescriptor & ShaderWith;
/**
* A shader that can be used with both WebGL and WebGPU.
* @category rendering
* @advanced
*/
export interface IShaderWithResources extends ShaderWithResourcesDescriptor, ShaderBase {
}
/**
* A descriptor for a shader that can be used with both WebGL and WebGPU.
* @category rendering
* @advanced
*/
export type ShaderDescriptor = ShaderWithGroups & ShaderWithResources;
type GlShaderFromWith = {
gpu?: GpuProgramOptions;
gl: GlProgramOptions;
};
type GpuShaderFromWith = {
gpu: GpuProgramOptions;
gl?: GlProgramOptions;
};
/**
* A descriptor for a shader that can be used with both WebGL and WebGPU.
* @category rendering
* @advanced
*/
export type ShaderFromGroups = (GlShaderFromWith | GpuShaderFromWith) & Omit<ShaderWithGroups, "glProgram" | "gpuProgram">;
/**
* A descriptor for a shader that can be used with both WebGL and WebGPU.
* @category rendering
* @advanced
*/
export type ShaderFromResources = (GlShaderFromWith | GpuShaderFromWith) & Omit<ShaderWithResources, "glProgram" | "gpuProgram">;
/**
* The Shader class is an integral part of the PixiJS graphics pipeline.
* Central to rendering in PixiJS are two key elements: A [shader] and a [geometry].
* The shader incorporates a {@link GlProgram} for WebGL or a {@link GpuProgram} for WebGPU,
* instructing the respective technology on how to render the geometry.
*
* The primary goal of the Shader class is to offer a unified interface compatible with both WebGL and WebGPU.
* When constructing a shader, you need to provide both a WebGL program and a WebGPU program due to the distinctions
* between the two rendering engines. If only one is provided, the shader won't function with the omitted renderer.
*
* Both WebGL and WebGPU utilize the same resource object when passed into the shader.
* Post-creation, the shader's interface remains consistent across both WebGL and WebGPU.
* The sole distinction lies in whether a glProgram or a gpuProgram is employed.
*
* Modifying shader uniforms, which can encompass:
* - TextureSampler {@link TextureStyle}
* - TextureSource {@link TextureSource}
* - UniformsGroups {@link UniformGroup}
* @example
*
* const shader = new Shader({
* glProgram: glProgram,
* gpuProgram: gpuProgram,
* resources: {
* uTexture: texture.source,
* uSampler: texture.sampler,
* uColor: [1, 0, 0, 1],
* },
* });
*
* // update the uniforms
* shader.resources.uColor[1] = 1;
* shader.resources.uTexture = texture2.source;
* @class
* @category rendering
* @advanced
*/
export declare class Shader extends EventEmitter<{
"destroy": Shader;
}> {
/** A unique identifier for the shader */
readonly uid: number;
/** An instance of the GPU program used by the WebGPU renderer */
gpuProgram: GpuProgram;
/** An instance of the GL program used by the WebGL renderer */
glProgram: GlProgram;
/**
* A number that uses two bits on whether the shader is compatible with the WebGL renderer and/or the WebGPU renderer.
* 0b00 - not compatible with either
* 0b01 - compatible with WebGL
* 0b10 - compatible with WebGPU
* This is automatically set based on if a {@link GlProgram} or {@link GpuProgram} is provided.
*/
readonly compatibleRenderers: number;
/** */
groups: Record<number, BindGroup>;
/** A record of the resources used by the shader. */
resources: Record<string, any>;
/**
* A record of the uniform groups and resources used by the shader.
* This is used by WebGL renderer to sync uniform data.
* @internal
*/
_uniformBindMap: Record<number, Record<number, string>>;
private readonly _ownedBindGroups;
/** @internal */
_destroyed: boolean;
/**
* Fired after rendering finishes.
* @event Shader#destroy
*/
/**
* There are two ways to create a shader.
* one is to pass in resources which is a record of uniform groups and resources.
* another is to pass in groups which is a record of {@link BindGroup}s.
* this second method is really to make use of shared {@link BindGroup}s.
* For most cases you will want to use resources as they are easier to work with.
* USe Groups if you want to share {@link BindGroup}s between shaders.
* you cannot mix and match - either use resources or groups.
* @param options - The options for the shader
*/
constructor(options: ShaderWithResources);
constructor(options: ShaderWithGroups);
/**
* Sometimes a resource group will be provided later (for example global uniforms)
* In such cases, this method can be used to let the shader know about the group.
* @param name - the name of the resource group
* @param groupIndex - the index of the group (should match the webGPU shader group location)
* @param bindIndex - the index of the bind point (should match the webGPU shader bind point)
*/
addResource(name: string, groupIndex: number, bindIndex: number): void;
private _buildResourceAccessor;
/**
* Use to destroy the shader when its not longer needed.
* It will destroy the resources and remove listeners.
* @param destroyPrograms - if the programs should be destroyed as well.
* Make sure its not being used by other shaders!
*/
destroy(destroyPrograms?: boolean): void;
/**
* A short hand function to create a shader based of a vertex and fragment shader.
* @param options
* @returns A shiny new PixiJS shader!
*/
static from(options: ShaderFromGroups): Shader;
static from(options: ShaderFromResources): Shader;
}
/**
* Various blend modes supported by Pixi
* @category filters
* @standard
*/
export type BLEND_MODES = "inherit" | "normal" | "add" | "multiply" | "screen" | "darken" | "lighten" | "erase" | "color-dodge" | "color-burn" | "linear-burn" | "linear-dodge" | "linear-light" | "hard-light" | "soft-light" | "pin-light" | "difference" | "exclusion" | "overlay" | "saturation" | "color" | "luminosity" | "normal-npm" | "add-npm" | "screen-npm" | "none" | "subtract" | "divide" | "vivid-light" | "hard-mix" | "negation" | "min" | "max";
/**
* The map of blend modes supported by Pixi
* @category rendering
* @advanced
*/
export declare const BLEND_TO_NPM: {
normal: string;
add: string;
screen: string;
};
/**
* The stencil operation to perform when using the stencil buffer
* @category rendering
* @advanced
*/
export declare enum STENCIL_MODES {
DISABLED = 0,
RENDERING_MASK_ADD = 1,
MASK_ACTIVE = 2,
INVERSE_MASK_ACTIVE = 3,
RENDERING_MASK_REMOVE = 4,
NONE = 5
}
/**
* The culling mode to use. It can be either `none`, `front` or `back`.
* @category rendering
* @advanced
*/
export type CULL_MODES = "none" | "back" | "front";
/**
* This is a WebGL state, and is is passed to {@link GlStateSystem}.
*
* Each mesh rendered may require WebGL to be in a different state.
* For example you may want different blend mode or to enable polygon offsets
* @category rendering
* @advanced
*/
export declare class State {
/**
* The data is a unique number based on the states settings.
* This lets us quickly compare states with a single number rather than looking
* at all the individual settings.
*/
data: number;
/** @internal */
_blendModeId: number;
private _blendMode;
private _polygonOffset;
constructor();
/**
* Activates blending of the computed fragment color values.
* @default true
*/
get blend(): boolean;
set blend(value: boolean);
/**
* Activates adding an offset to depth values of polygon's fragments
* @default false
*/
get offsets(): boolean;
set offsets(value: boolean);
/** The culling settings for this state none - No culling back - Back face culling front - Front face culling */
set cullMode(value: CULL_MODES);
get cullMode(): CULL_MODES;
/**
* Activates culling of polygons.
* @default false
*/
get culling(): boolean;
set culling(value: boolean);
/**
* Activates depth comparisons and updates to the depth buffer.
* @default false
*/
get depthTest(): boolean;
set depthTest(value: boolean);
/**
* Enables or disables writing to the depth buffer.
* @default true
*/
get depthMask(): boolean;
set depthMask(value: boolean);
/**
* Specifies whether or not front or back-facing polygons can be culled.
* @default false
*/
get clockwiseFrontFace(): boolean;
set clockwiseFrontFace(value: boolean);
/**
* The blend mode to be applied when this state is set. Apply a value of `normal` to reset the blend mode.
* Setting this mode to anything other than NO_BLEND will automatically switch blending on.
* @default 'normal'
*/
get blendMode(): BLEND_MODES;
set blendMode(value: BLEND_MODES);
/**
* The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill.
* @default 0
*/
get polygonOffset(): number;
set polygonOffset(value: number);
toString(): string;
/**
* A quickly getting an instance of a State that is configured for 2d rendering.
* @returns a new State with values set for 2d rendering
*/
static for2d(): State;
static default2d: State;
}
/**
* A class which holds the canvas contexts and textures for a render target.
* @category rendering
* @ignore
*/
export declare class GpuRenderTarget {
contexts: GPUCanvasContext[];
msaaTextures: TextureSource[];
msaa: boolean;
msaaSamples: number;
colorTargetCount: number;
width: number;
height: number;
descriptor: GPURenderPassDescriptor;
}
/**
* The system that handles encoding commands for the GPU.
* @category rendering
* @advanced
*/
export declare class GpuEncoderSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "encoder";
readonly priority: 1;
};
commandEncoder: GPUCommandEncoder;
renderPassEncoder: GPURenderPassEncoder;
commandFinished: Promise<void>;
private _resolveCommandFinished;
private _gpu;
private _boundBindGroup;
private _boundVertexBuffer;
private _boundIndexBuffer;
private _boundPipeline;
private readonly _renderer;
constructor(renderer: WebGPURenderer);
renderStart(): void;
beginRenderPass(gpuRenderTarget: GpuRenderTarget): void;
endRenderPass(): void;
setViewport(viewport: Rectangle): void;
setPipelineFromGeometryProgramAndState(geometry: Geometry, program: GpuProgram, state: any, topology?: Topology): void;
setPipeline(pipeline: GPURenderPipeline): void;
private _setVertexBuffer;
private _setIndexBuffer;
resetBindGroup(index: number): void;
setBindGroup(index: number, bindGroup: BindGroup, program: GpuProgram): void;
setGeometry(geometry: Geometry, program: GpuProgram): void;
private _setShaderBindGroups;
private _syncBindGroup;
draw(options: {
geometry: Geometry;
shader: Shader;
state?: State;
topology?: Topology;
size?: number;
start?: number;
instanceCount?: number;
skipSync?: boolean;
}): void;
finishRenderPass(): void;
postrender(): void;
restoreRenderPass(): void;
private _clearCache;
destroy(): void;
protected contextChange(gpu: GPU$1): void;
}
/**
* The GpuLimitsSystem provides information about the capabilities and limitations of the underlying GPU.
* These limits, such as the maximum number of textures that can be used in a shader
* (`maxTextures`) or the maximum number of textures that can be batched together (`maxBatchableTextures`),
* are determined by the specific graphics hardware and driver.
*
* The values for these limits are not available immediately upon instantiation of the class.
* They are populated when the WebGPU Device rendering context is successfully initialized and ready,
* which occurs after the `renderer.init()` method has completed.
* Attempting to access these properties before the context is ready will result in undefined or default values.
*
* This system allows the renderer to adapt its behavior and resource allocation strategies
* to stay within the supported boundaries of the GPU, ensuring optimal performance and stability.
* @example
* ```ts
* const renderer = new WebGPURenderer();
* await renderer.init(); // GPU limits are populated after this call
*
* console.log(renderer.limits.maxTextures);
* console.log(renderer.limits.maxBatchableTextures);
* ```
* @category rendering
* @advanced
*/
export declare class GpuLimitsSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "limits";
};
/** The maximum number of textures that can be used by a shader */
maxTextures: number;
/** The maximum number of batchable textures */
maxBatchableTextures: number;
private readonly _renderer;
constructor(renderer: WebGPURenderer);
contextChange(): void;
destroy(): void;
}
/**
* Options for creating a render target.
* @category rendering
* @advanced
*/
export interface RenderTargetOptions {
/** the width of the RenderTarget */
width?: number;
/** the height of the RenderTarget */
height?: number;
/** the resolution of the RenderTarget */
resolution?: number;
/** an array of textures, or a number indicating how many color textures there should be */
colorTextures?: BindableTexture[] | number;
/** should this render target have a stencil buffer? */
stencil?: boolean;
/** should this render target have a depth buffer? */
depth?: boolean;
/** a depth stencil texture that the depth and stencil outputs will be written to */
depthStencilTexture?: BindableTexture | boolean;
/** should this render target be antialiased? */
antialias?: boolean;
/** is this a root element, true if this is gl context owners render target */
isRoot?: boolean;
}
/**
* A class that describes what the renderers are rendering to.
* This can be as simple as a Texture, or as complex as a multi-texture, multi-sampled render target.
* Support for stencil and depth buffers is also included.
*
* If you need something more complex than a Texture to render to, you should use this class.
* Under the hood, all textures you render to have a RenderTarget created on their behalf.
* @category rendering
* @advanced
*/
export declare class RenderTarget {
/** The default options for a render target */
static defaultOptions: RenderTargetOptions;
/** unique id for this render target */
readonly uid: number;
/**
* An array of textures that can be written to by the GPU - mostly this has one texture in Pixi, but you could
* write to multiple if required! (eg deferred lighting)
*/
colorTextures: TextureSource[];
/** the stencil and depth buffer will right to this texture in WebGPU */
depthStencilTexture: TextureSource;
/** if true, will ensure a stencil buffer is added. For WebGPU, this will automatically create a depthStencilTexture */
stencil: boolean;
/** if true, will ensure a depth buffer is added. For WebGPU, this will automatically create a depthStencilTexture */
depth: boolean;
dirtyId: number;
isRoot: boolean;
private readonly _size;
/** if true, then when the render target is destroyed, it will destroy all the textures that were created for it. */
private readonly _managedColorTextures;
/**
* @param [descriptor] - Options for creating a render target.
*/
constructor(descriptor?: RenderTargetOptions);
get size(): [
number,
number
];
get width(): number;
get height(): number;
get pixelWidth(): number;
get pixelHeight(): number;
get resolution(): number;
get colorTexture(): TextureSource;
protected onSourceResize(source: TextureSource): void;
/**
* This will ensure a depthStencil texture is created for this render target.
* Most likely called by the mask system to make sure we have stencil buffer added.
* @internal
*/
ensureDepthStencilTexture(): void;
resize(width: number, height: number, resolution?: number, skipColorTexture?: boolean): void;
destroy(): void;
}
/**
* This manages the stencil buffer. Used primarily for masking
* @category rendering
* @advanced
*/
export declare class GpuStencilSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "stencil";
};
private readonly _renderer;
private _renderTargetStencilState;
private _activeRenderTarget;
constructor(renderer: WebGPURenderer);
protected onRenderTargetChange(renderTarget: RenderTarget): void;
setStencilMode(stencilMode: STENCIL_MODES, stencilReference: number): void;
destroy(): void;
}
/** @internal */
export declare const UNIFORM_TYPES_VALUES: readonly [
"f32",
"i32",
"vec2<f32>",
"vec3<f32>",
"vec4<f32>",
"mat2x2<f32>",
"mat3x3<f32>",
"mat4x4<f32>",
"mat3x2<f32>",
"mat4x2<f32>",
"mat2x3<f32>",
"mat4x3<f32>",
"mat2x4<f32>",
"mat3x4<f32>",
"vec2<i32>",
"vec3<i32>",
"vec4<i32>"
];
/**
* useful for checking if a type is supported - a map of supported types with a true value.
* @internal
*/
export declare const UNIFORM_TYPES_MAP: Record<UNIFORM_TYPES, boolean>;
/** @internal */
export type UNIFORM_TYPES_SINGLE = typeof UNIFORM_TYPES_VALUES[number];
type OPTIONAL_SPACE = " " | "";
/** @internal */
export type UNIFORM_TYPES_ARRAY = `array<${UNIFORM_TYPES_SINGLE},${OPTIONAL_SPACE}${number}>`;
/** @internal */
export type UNIFORM_TYPES = UNIFORM_TYPES_SINGLE | UNIFORM_TYPES_ARRAY;
/**
* This is the type of the uniform structures that are used in the UniformGroup.
* @category rendering
* @advanced
*/
export interface UniformData {
/** the value of the uniform, this could be any object - a parser will figure out how to write it to the buffer */
value: unknown;
type: UNIFORM_TYPES;
/** the size of the variable (eg 2 for vec2, 3 for vec3, 4 for vec4) */
size?: number;
name?: string;
}
/** @internal */
export interface UboElement {
data: UniformData;
offset: number;
size: number;
}
/** @internal */
export interface UboLayout {
uboElements: UboElement[];
/** float32 size // TODO change to bytes */
size: number;
}
/** @internal */
export type UniformsSyncCallback = (...args: any[]) => void;
type FLOPS<T = UniformData> = T extends {
value: infer V;
} ? V : never;
/**
* Extracts the value type from a uniform data object.
* @internal
*/
export type ExtractUniformObject<T = Record<string, UniformData>> = {
[K in keyof T]: FLOPS<T[K]>;
};
/**
* Uniform group options
* @category rendering
* @advanced
*/
export type UniformGroupOptions = {
/**
* if true the UniformGroup is handled as an Uniform buffer object.
* This is the only way WebGPU can work with uniforms. WebGL2 can also use this.
* So don't set to true if you want to use WebGPU :D
*/
ubo?: boolean;
/** if true, then you are responsible for when the data is uploaded to the GPU by calling `update()` */
isStatic?: boolean;
};
/**
* Uniform group holds uniform map and some ID's for work
*
* `UniformGroup` has two modes:
*
* 1: Normal mode
* Normal mode will upload the uniforms with individual function calls as required. This is the default mode
* for WebGL rendering.
*
* 2: Uniform buffer mode
* This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or
* or a generic object that PixiJS will automatically map to a buffer for you.
* For maximum benefits, make Ubo UniformGroups static, and only update them each frame.
* This is the only way uniforms can be used with WebGPU.
*
* Rules of UBOs:
* - UBOs only work with WebGL2, so make sure you have a fallback!
* - Only floats are supported (including vec[2,3,4], mat[2,3,4])
* - Samplers cannot be used in ubo's (a GPU limitation)
* - You must ensure that the object you pass in exactly matches in the shader ubo structure.
* Otherwise, weirdness will ensue!
* - The name of the ubo object added to the group must match exactly the name of the ubo in the shader.
*
* When declaring your uniform options, you ust parse in the value and the type of the uniform.
* The types correspond to the WebGPU types
*
Uniforms can be modified via the classes 'uniforms' property. It will contain all the uniforms declared in the constructor.
*
* ```ts
* // UBO in shader:
* uniform myCoolData { // Declaring a UBO...
* mat4 uCoolMatrix;
* float uFloatyMcFloatFace;
* };
* ```
*
* ```js
* // A new Uniform Buffer Object...
* const myCoolData = new UniformGroup({
* uCoolMatrix: {value:new Matrix(), type: 'mat4<f32>'},
* uFloatyMcFloatFace: {value:23, type: 'f32'},
* }}
*
* // modify the data
* myCoolData.uniforms.uFloatyMcFloatFace = 42;
* // Build a shader...
* const shader = Shader.from(srcVert, srcFrag, {
* myCoolData // Name matches the UBO name in the shader. Will be processed accordingly.
* })
* ```
* @category rendering
* @advanced
*/
export declare class UniformGroup<UNIFORMS extends {
[key: string]: UniformData;
} = any> implements BindResource {
/** The default options used by the uniform group. */
static defaultOptions: UniformGroupOptions;
/**
* used internally to know if a uniform group was used in the last render pass
* @internal
*/
_touched: number;
/** a unique id for this uniform group used through the renderer */
readonly uid: number;
/**
* a resource type, used to identify how to handle it when its in a bind group / shader resource
* @internal
*/
_resourceType: string;
/**
* the resource id used internally by the renderer to build bind group keys
* @internal
*/
_resourceId: number;
/** the structures of the uniform group */
uniformStructures: UNIFORMS;
/** the uniforms as an easily accessible map of properties */
uniforms: ExtractUniformObject<UNIFORMS>;
/** true if it should be used as a uniform buffer object */
ubo: boolean;
/** an underlying buffer that will be uploaded to the GPU when using this UniformGroup */
buffer?: Buffer$1;
/**
* if true, then you are responsible for when the data is uploaded to the GPU.
* otherwise, the data is reuploaded each frame.
*/
isStatic: boolean;
/** used ito identify if this is a uniform group */
readonly isUniformGroup = true;
/**
* used to flag if this Uniform groups data is different from what it has stored in its buffer / on the GPU
* @internal
*/
_dirtyId: number;
/**
* a signature string generated for internal use
* @internal
*/
readonly _signature: number;
readonly destroyed = false;
/**
* Create a new Uniform group
* @param uniformStructures - The structures of the uniform group
* @param options - The optional parameters of this uniform group
*/
constructor(uniformStructures: UNIFORMS, options?: UniformGroupOptions);
/** Call this if you want the uniform groups data to be uploaded to the GPU only useful if `isStatic` is true. */
update(): void;
}
/** @internal */
export interface UboAdaptor {
createUboElements: (uniformData: UniformData[]) => UboLayout;
generateUboSync: (uboElements: UboElement[]) => UniformsSyncCallback;
}
/**
* System plugin to the renderer to manage uniform buffers.
* @category rendering
* @advanced
*/
export declare class UboSystem implements System {
/** Cache of uniform buffer layouts and sync functions, so we don't have to re-create them */
private _syncFunctionHash;
private readonly _adaptor;
constructor(adaptor: UboAdaptor);
/**
* Overridable function by `pixi.js/unsafe-eval` to silence
* throwing an error if platform doesn't support unsafe-evals.
* @private
*/
private _systemCheck;
ensureUniformGroup(uniformGroup: UniformGroup): void;
getUniformGroupData(uniformGroup: UniformGroup): {
layout: UboLayout;
syncFunction: (uniforms: Record<string, any>, data: Float32Array, dataInt32: Int32Array, offset: number) => void;
};
private _initUniformGroup;
private _generateUboSync;
syncUniformGroup(uniformGroup: UniformGroup, data?: Float32Array, offset?: number): boolean;
updateUniformGroup(uniformGroup: UniformGroup): boolean;
destroy(): void;
}
/**
* System plugin to the renderer to manage uniform buffers. With a WGSL twist!
* @category rendering
* @advanced
*/
export declare class GpuUboSystem extends UboSystem {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "ubo";
};
constructor();
}
/**
* A resource that can be bound to a bind group and used in a shader.
* Whilst a buffer can be used as a resource, this class allows you to specify an offset and size of the buffer to use.
* This is useful if you have a large buffer and only part of it is used in a shader.
*
* This resource, will listen for changes on the underlying buffer and emit a itself if the buffer changes shape.
* @example
*
* const buffer = new Buffer({
* data: new Float32Array(1000),
* usage: BufferUsage.UNIFORM,
* });
* // Create a buffer resource that uses the first 100 bytes of a buffer
* const bufferResource = new BufferResource({
* buffer,
* offset: 0,
* size: 100,
* });
* @category rendering
* @advanced
*/
export declare class BufferResource extends EventEmitter<{
change: BindResource;
}> implements BindResource {
/**
* emits when the underlying buffer has changed shape (i.e. resized)
* letting the renderer know that it needs to discard the old buffer on the GPU and create a new one
* @event change
*/
/** a unique id for this uniform group used through the renderer */
readonly uid: number;
/**
* a resource type, used to identify how to handle it when its in a bind group / shader resource
* @internal
*/
readonly _resourceType = "bufferResource";
/**
* used internally to know if a uniform group was used in the last render pass
* @internal
*/
_touched: number;
/**
* the resource id used internally by the renderer to build bind group keys
* @internal
*/
_resourceId: number;
/** the underlying buffer that this resource is using */
buffer: Buffer$1;
/** the offset of the buffer this resource is using. If not provided, then it will use the offset of the buffer. */
readonly offset: number;
/** the size of the buffer this resource is using. If not provided, then it will use the size of the buffer. */
readonly size: number;
/**
* A cheeky hint to the GL renderer to let it know this is a BufferResource
* @internal
*/
readonly _bufferResource = true;
/**
* Has the Buffer resource been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* Create a new Buffer Resource.
* @param options - The options for the buffer resource
* @param options.buffer - The underlying buffer that this resource is using
* @param options.offset - The offset of the buffer this resource is using.
* If not provided, then it will use the offset of the buffer.
* @param options.size - The size of the buffer this resource is using.
* If not provided, then it will use the size of the buffer.
*/
constructor({ buffer, offset, size }: {
buffer: Buffer$1;
offset?: number;
size?: number;
});
protected onBufferChange(): void;
/**
* Destroys this resource. Make sure the underlying buffer is not used anywhere else
* if you want to destroy it as well, or code will explode
* @param destroyBuffer - Should the underlying buffer be destroyed as well?
*/
destroy(destroyBuffer?: boolean): void;
}
/** @internal */
export declare class GpuUniformBatchPipe {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUPipes
];
readonly name: "uniformBatch";
};
private _renderer;
private _bindGroupHash;
private readonly _batchBuffer;
private _buffers;
private _bindGroups;
private _bufferResources;
constructor(renderer: WebGPURenderer);
renderEnd(): void;
private _resetBindGroups;
getUniformBindGroup(group: UniformGroup<any>, duplicate: boolean): BindGroup;
getUboResource(group: UniformGroup<any>): BufferResource;
getArrayBindGroup(data: Float32Array): BindGroup;
getArrayBufferResource(data: Float32Array): BufferResource;
private _getBufferResource;
private _getBindGroup;
private _uploadBindGroups;
destroy(): void;
}
/**
* A system that creates and manages the GPU pipelines.
*
* Caching Mechanism: At its core, the system employs a two-tiered caching strategy to minimize
* the redundant creation of GPU pipelines (or "pipes"). This strategy is based on generating unique
* keys that represent the state of the graphics settings and the specific requirements of the
* item being rendered. By caching these pipelines, subsequent draw calls with identical configurations
* can reuse existing pipelines instead of generating new ones.
*
* State Management: The system differentiates between "global" state properties (like color masks
* and stencil masks, which do not change frequently) and properties that may vary between draw calls
* (such as geometry, shaders, and blend modes). Unique keys are generated for both these categories
* using getStateKey for global state and getGraphicsStateKey for draw-specific settings. These keys are
* then then used to caching the pipe. The next time we need a pipe we can check
* the cache by first looking at the state cache and then the pipe cache.
* @category rendering
* @advanced
*/
export declare class PipelineSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "pipeline";
};
private readonly _renderer;
protected CONTEXT_UID: number;
private _moduleCache;
private _bufferLayoutsCache;
private readonly _bindingNamesCache;
private _pipeCache;
private readonly _pipeStateCaches;
private _gpu;
private _stencilState;
private _stencilMode;
private _colorMask;
private _multisampleCount;
private _colorTargetCount;
private _depthStencilAttachment;
constructor(renderer: WebGPURenderer);
protected contextChange(gpu: GPU$1): void;
setMultisampleCount(multisampleCount: number): void;
setRenderTarget(renderTarget: GpuRenderTarget): void;
setColorMask(colorMask: number): void;
setStencilMode(stencilMode: STENCIL_MODES): void;
setPipeline(geometry: Geometry, program: GpuProgram, state: State, passEncoder: GPURenderPassEncoder): void;
getPipeline(geometry: Geometry, program: GpuProgram, state: State, topology?: Topology): GPURenderPipeline;
private _createPipeline;
private _getModule;
private _createModule;
private _generateBufferKey;
private _generateAttributeLocationsKey;
/**
* Returns a hash of buffer names mapped to bind locations.
* This is used to bind the correct buffer to the correct location in the shader.
* @param geometry - The geometry where to get the buffer names
* @param program - The program where to get the buffer names
* @returns An object of buffer names mapped to the bind location.
*/
getBufferNamesToBind(geometry: Geometry, program: GpuProgram): Record<string, string>;
private _createVertexBufferLayouts;
private _updatePipeHash;
destroy(): void;
}
/**
* Represents a render target.
* @category rendering
* @ignore
*/
export declare class GlRenderTarget {
width: number;
height: number;
msaa: boolean;
framebuffer: WebGLFramebuffer;
resolveTargetFramebuffer: WebGLFramebuffer;
msaaRenderBuffer: WebGLRenderbuffer[];
depthStencilRenderBuffer: WebGLRenderbuffer;
}
/**
* A render surface is a texture, canvas, or render target
* @category rendering
* @see environment.ICanvas
* @see Texture
* @see RenderTarget
* @advanced
*/
export type RenderSurface = ICanvas | BindableTexture | RenderTarget;
/**
* An adaptor interface for RenderTargetSystem to support WebGL and WebGPU.
* This is used internally by the renderer, and is not intended to be used directly.
* @ignore
*/
export interface RenderTargetAdaptor<RENDER_TARGET extends GlRenderTarget | GpuRenderTarget> {
init(
/** the renderer */
renderer: Renderer,
/** the render target system */
renderTargetSystem: RenderTargetSystem<RENDER_TARGET>): void;
/** A function copies the contents of a render surface to a texture */
copyToTexture(
/** the render surface to copy from */
sourceRenderSurfaceTexture: RenderTarget,
/** the texture to copy to */
destinationTexture: Texture,
/** the origin of the copy */
originSrc: {
x: number;
y: number;
},
/** the size of the copy */
size: {
width: number;
height: number;
},
/** the destination origin (top left to paste from!) */
originDest?: {
x: number;
y: number;
}): Texture;
/** starts a render pass on the render target */
startRenderPass(
/** the render target to start the render pass on */
renderTarget: RenderTarget, clear: CLEAR_OR_BOOL,
/** the color to clear to */
clearColor?: RgbaArray,
/** the viewport to use */
viewport?: Rectangle): void;
/** clears the current render target to the specified color */
clear(
/** the render target to clear */
renderTarget: RenderTarget,
/** the clear mode to use. Can be true or a CLEAR number 'COLOR | DEPTH | STENCIL' 0b111 */
clear: CLEAR_OR_BOOL,
/** the color to clear to */
clearColor?: RgbaArray,
/** the viewport to use */
viewport?: Rectangle): void;
/** finishes the current render pass */
finishRenderPass(renderTarget: RenderTarget): void;
/** called after the render pass is finished */
postrender?(renderTarget: RenderTarget): void;
/** called before the render main pass is started */
prerender?(renderTarget: RenderTarget): void;
/**
* initializes a gpu render target. Both renderers use this function to initialize a gpu render target
* Its different type of object depending on the renderer.
*/
initGpuRenderTarget(
/** the render target to initialize */
renderTarget: RenderTarget): RENDER_TARGET;
/** called when a render target is resized */
resizeGpuRenderTarget(
/** the render target to resize */
renderTarget: RenderTarget): void;
/** destroys the gpu render target */
destroyGpuRenderTarget(
/** the render target to destroy */
gpuRenderTarget: RENDER_TARGET): void;
}
/**
* A system that manages render targets. A render target is essentially a place where the shaders can color in the pixels.
* The render target system is responsible for binding the render target to the renderer, and managing the viewport.
* Render targets can be pushed and popped.
*
* To make it easier, you can also bind textures and canvases too. This will automatically create a render target for you.
* The render target itself is a lot more powerful than just a texture or canvas,
* as it can have multiple textures attached to it.
* It will also give ou fine grain control over the stencil buffer / depth texture.
* @example
*
* ```js
*
* // create a render target
* const renderTarget = new RenderTarget({
* colorTextures: [new TextureSource({ width: 100, height: 100 })],
* });
*
* // bind the render target
* renderer.renderTarget.bind(renderTarget);
*
* // draw something!
* ```
* @category rendering
* @advanced
*/
export declare class RenderTargetSystem<RENDER_TARGET extends GlRenderTarget | GpuRenderTarget> implements System {
/** When rendering of a scene begins, this is where the root render surface is stored */
rootRenderTarget: RenderTarget;
/** This is the root viewport for the render pass*/
rootViewPort: Rectangle;
/** A boolean that lets the dev know if the current render pass is rendering to the screen. Used by some plugins */
renderingToScreen: boolean;
/** the current active render target */
renderTarget: RenderTarget;
/** the current active render surface that the render target is created from */
renderSurface: RenderSurface;
/** the current viewport that the gpu is using */
readonly viewport: Rectangle;
/**
* a runner that lets systems know if the active render target has changed.
* Eg the Stencil System needs to know so it can manage the stencil buffer
*/
readonly onRenderTargetChange: SystemRunner;
/** the projection matrix that is used by the shaders based on the active render target and the viewport */
readonly projectionMatrix: Matrix;
/** the default clear color for render targets */
readonly defaultClearColor: RgbaArray;
/** a reference to the adaptor that interfaces with WebGL / WebGP */
readonly adaptor: RenderTargetAdaptor<RENDER_TARGET>;
/**
* a hash that stores the render target for a given render surface. When you pass in a texture source,
* a render target is created for it. This map stores and makes it easy to retrieve the render target
*/
private readonly _renderSurfaceToRenderTargetHash;
/** A hash that stores a gpu render target for a given render target. */
private _gpuRenderTargetHash;
/**
* A stack that stores the render target and frame that is currently being rendered to.
* When push is called, the current render target is stored in this stack.
* When pop is called, the previous render target is restored.
*/
private readonly _renderTargetStack;
/** A reference to the renderer */
private readonly _renderer;
constructor(renderer: Renderer);
/** called when dev wants to finish a render pass */
finishRenderPass(): void;
/**
* called when the renderer starts to render a scene.
* @param options
* @param options.target - the render target to render to
* @param options.clear - the clear mode to use. Can be true or a CLEAR number 'COLOR | DEPTH | STENCIL' 0b111
* @param options.clearColor - the color to clear to
* @param options.frame - the frame to render to
*/
renderStart({ target, clear, clearColor, frame }: {
target: RenderSurface;
clear: CLEAR_OR_BOOL;
clearColor: RgbaArray;
frame?: Rectangle;
}): void;
postrender(): void;
/**
* Binding a render surface! This is the main function of the render target system.
* It will take the RenderSurface (which can be a texture, canvas, or render target) and bind it to the renderer.
* Once bound all draw calls will be rendered to the render surface.
*
* If a frame is not provide and the render surface is a texture, the frame of the texture will be used.
* @param renderSurface - the render surface to bind
* @param clear - the clear mode to use. Can be true or a CLEAR number 'COLOR | DEPTH | STENCIL' 0b111
* @param clearColor - the color to clear to
* @param frame - the frame to render to
* @returns the render target that was bound
*/
bind(renderSurface: RenderSurface, clear?: CLEAR_OR_BOOL, clearColor?: RgbaArray, frame?: Rectangle): RenderTarget;
clear(target?: RenderSurface, clear?: CLEAR_OR_BOOL, clearColor?: RgbaArray): void;
protected contextChange(): void;
/**
* Push a render surface to the renderer. This will bind the render surface to the renderer,
* @param renderSurface - the render surface to push
* @param clear - the clear mode to use. Can be true or a CLEAR number 'COLOR | DEPTH | STENCIL' 0b111
* @param clearColor - the color to clear to
* @param frame - the frame to use when rendering to the render surface
*/
push(renderSurface: RenderSurface, clear?: CLEAR | boolean, clearColor?: RgbaArray, frame?: Rectangle): RenderTarget;
/** Pops the current render target from the renderer and restores the previous render target. */
pop(): void;
/**
* Gets the render target from the provide render surface. Eg if its a texture,
* it will return the render target for the texture.
* If its a render target, it will return the same render target.
* @param renderSurface - the render surface to get the render target for
* @returns the render target for the render surface
*/
getRenderTarget(renderSurface: RenderSurface): RenderTarget;
/**
* Copies a render surface to another texture.
*
* NOTE:
* for sourceRenderSurfaceTexture, The render target must be something that is written too by the renderer
*
* The following is not valid:
* @example
* const canvas = document.createElement('canvas')
* canvas.width = 200;
* canvas.height = 200;
*
* const ctx = canvas2.getContext('2d')!
* ctx.fillStyle = 'red'
* ctx.fillRect(0, 0, 200, 200);
*
* const texture = RenderTexture.create({
* width: 200,
* height: 200,
* })
* const renderTarget = renderer.renderTarget.getRenderTarget(canvas2);
*
* renderer.renderTarget.copyToTexture(renderTarget,texture, {x:0,y:0},{width:200,height:200},{x:0,y:0});
*
* The best way to copy a canvas is to create a texture from it. Then render with that.
*
* Parsing in a RenderTarget canvas context (with a 2d context)
* @param sourceRenderSurfaceTexture - the render surface to copy from
* @param destinationTexture - the texture to copy to
* @param originSrc - the origin of the copy
* @param originSrc.x - the x origin of the copy
* @param originSrc.y - the y origin of the copy
* @param size - the size of the copy
* @param size.width - the width of the copy
* @param size.height - the height of the copy
* @param originDest - the destination origin (top left to paste from!)
* @param originDest.x - the x origin of the paste
* @param originDest.y - the y origin of the paste
*/
copyToTexture(sourceRenderSurfaceTexture: RenderTarget, destinationTexture: Texture, originSrc: {
x: number;
y: number;
}, size: {
width: number;
height: number;
}, originDest: {
x: number;
y: number;
}): Texture<TextureSource<any>>;
/**
* ensures that we have a depth stencil buffer available to render to
* This is used by the mask system to make sure we have a stencil buffer.
*/
ensureDepthStencil(): void;
/** nukes the render target system */
destroy(): void;
private _initRenderTarget;
getGpuRenderTarget(renderTarget: RenderTarget): RENDER_TARGET;
resetState(): void;
}
/**
* The WebGPU adaptor for the render target system. Allows the Render Target System to
* be used with the WebGPU renderer
* @category rendering
* @ignore
*/
export declare class GpuRenderTargetAdaptor implements RenderTargetAdaptor<GpuRenderTarget> {
private _renderTargetSystem;
private _renderer;
init(renderer: WebGPURenderer, renderTargetSystem: RenderTargetSystem<GpuRenderTarget>): void;
copyToTexture(sourceRenderSurfaceTexture: RenderTarget, destinationTexture: Texture, originSrc: {
x: number;
y: number;
}, size: {
width: number;
height: number;
}, originDest: {
x: number;
y: number;
}): Texture<TextureSource<any>>;
startRenderPass(renderTarget: RenderTarget, clear?: CLEAR_OR_BOOL, clearColor?: RgbaArray, viewport?: Rectangle): void;
finishRenderPass(): void;
/**
* returns the gpu texture for the first color texture in the render target
* mainly used by the filter manager to get copy the texture for blending
* @param renderTarget
* @returns a gpu texture
*/
private _getGpuColorTexture;
getDescriptor(renderTarget: RenderTarget, clear: CLEAR_OR_BOOL, clearValue: RgbaArray): GPURenderPassDescriptor;
clear(renderTarget: RenderTarget, clear?: CLEAR_OR_BOOL, clearColor?: RgbaArray, viewport?: Rectangle): void;
initGpuRenderTarget(renderTarget: RenderTarget): GpuRenderTarget;
destroyGpuRenderTarget(gpuRenderTarget: GpuRenderTarget): void;
ensureDepthStencilTexture(renderTarget: RenderTarget): void;
resizeGpuRenderTarget(renderTarget: RenderTarget): void;
}
/**
* The WebGL adaptor for the render target system. Allows the Render Target System to be used with the WebGl renderer
* @category rendering
* @advanced
*/
export declare class GpuRenderTargetSystem extends RenderTargetSystem<GpuRenderTarget> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "renderTarget";
};
adaptor: GpuRenderTargetAdaptor;
constructor(renderer: WebGPURenderer);
}
/**
* Data structure for GPU program layout.
* Contains bind group layouts and pipeline layout.
* @category rendering
* @advanced
*/
export interface GPUProgramData {
bindGroups: GPUBindGroupLayout[];
pipeline: GPUPipelineLayout;
}
/**
* A system that manages the rendering of GpuPrograms.
* @category rendering
* @advanced
*/
export declare class GpuShaderSystem {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "shader";
};
private _gpu;
private readonly _gpuProgramData;
protected contextChange(gpu: GPU$1): void;
getProgramData(program: GpuProgram): GPUProgramData;
private _createGPUProgramData;
destroy(): void;
}
/**
* System plugin to the renderer to manage WebGL state machines.
* @category rendering
* @advanced
*/
export declare class GpuStateSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "state";
};
/**
* State ID
* @readonly
*/
stateId: number;
/**
* Polygon offset
* @readonly
*/
polygonOffset: number;
/**
* Blend mode
* @default 'none'
* @readonly
*/
blendMode: BLEND_MODES;
/** Whether current blend equation is different */
protected _blendEq: boolean;
/**
* GL context
* @type {WebGLRenderingContext}
* @readonly
*/
protected gpu: GPU$1;
/**
* Default WebGL State
* @readonly
*/
protected defaultState: State;
constructor();
protected contextChange(gpu: GPU$1): void;
/**
* Gets the blend mode data for the current state
* @param state - The state to get the blend mode from
* @param count - The number of color targets to create
*/
getColorTargets(state: State, count: number): GPUColorTargetState[];
destroy(): void;
}
/**
* An effect that can be applied to a container. This is used to create effects such as filters/masks etc.
* @category rendering
* @advanced
*/
export interface Effect {
pipe: string;
priority: number;
addBounds?(bounds: Bounds, skipUpdateTransform?: boolean): void;
addLocalBounds?(bounds: Bounds, localRoot: Container): void;
containsPoint?(point: PointData, hitTestFn: (container: Container, point: Point) => boolean): boolean;
destroy(): void;
}
/**
* The constructor for an Effect.
* It is used to create instances of effects that can be applied to containers.
* @param options - The options for the effect.
* @returns A new instance of the effect.
* @category rendering
* @advanced
*/
export interface EffectConstructor {
new (options?: any): Effect;
test?(options: any): boolean;
}
/**
* Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand.
* @category utils
* @advanced
*/
export declare class ViewableBuffer {
/** The size of the buffer in bytes. */
size: number;
/** Underlying `ArrayBuffer` that holds all the data and is of capacity `this.size`. */
rawBinaryData: ArrayBuffer;
/** View on the raw binary data as a `Uint32Array`. */
uint32View: Uint32Array;
/** View on the raw binary data as a `Float32Array`. */
float32View: Float32Array;
/** View on the raw binary data as a `Uint16Array`. */
uint16View: Uint16Array;
private _int8View;
private _uint8View;
private _int16View;
private _int32View;
private _float64Array;
private _bigUint64Array;
/**
* @param length - The size of the buffer in bytes.
*/
constructor(length: number);
/**
* @param arrayBuffer - The source array buffer.
*/
constructor(arrayBuffer: ArrayBuffer);
/** View on the raw binary data as a `Int8Array`. */
get int8View(): Int8Array;
/** View on the raw binary data as a `Uint8Array`. */
get uint8View(): Uint8Array;
/** View on the raw binary data as a `Int16Array`. */
get int16View(): Int16Array;
/** View on the raw binary data as a `Int32Array`. */
get int32View(): Int32Array;
/** View on the raw binary data as a `Float64Array`. */
get float64View(): Float64Array;
/** View on the raw binary data as a `BigUint64Array`. */
get bigUint64View(): BigUint64Array;
/**
* Returns the view of the given type.
* @param type - One of `int8`, `uint8`, `int16`,
* `uint16`, `int32`, `uint32`, and `float32`.
* @returns - typed array of given type
*/
view(type: string): TypedArray;
/** Destroys all buffer references. Do not use after calling this. */
destroy(): void;
/**
* Returns the size of the given type in bytes.
* @param type - One of `int8`, `uint8`, `int16`,
* `uint16`, `int32`, `uint32`, and `float32`.
* @returns - size of the type in bytes
*/
static sizeOf(type: string): number;
}
/**
* Used by the batcher to build texture batches. Holds list of textures and their respective locations.
* @category rendering
* @advanced
*/
export declare class BatchTextureArray {
/** Inside textures array. */
textures: TextureSource[];
/** Respective locations for textures. */
ids: Record<number, number>;
/** Number of filled elements. */
count: number;
constructor();
/** Clear the textures and their locations. */
clear(): void;
}
/**
* An instruction that can be executed by the renderer
* @category rendering
* @advanced
*/
export interface Instruction {
/** a the id of the render pipe that can run this instruction */
renderPipeId: string;
/** the name of the instruction */
action?: string;
/** true if this instruction can be compiled into a WebGPU bundle */
canBundle: boolean;
}
/**
* The action types for a batch.
* @category rendering
* @advanced
*/
export type BatchAction = "startBatch" | "renderBatch";
/**
* A batch pool is used to store batches when they are not currently in use.
* @category rendering
* @advanced
*/
export declare class Batch implements Instruction {
renderPipeId: string;
action: BatchAction;
start: number;
size: number;
textures: BatchTextureArray;
blendMode: BLEND_MODES;
topology: Topology;
canBundle: boolean;
/**
* breaking rules slightly here in the name of performance..
* storing references to these bindgroups here is just faster for access!
* keeps a reference to the GPU bind group to set when rendering this batch for WebGPU. Will be null is using WebGL.
*/
gpuBindGroup: GPUBindGroup;
/**
* breaking rules slightly here in the name of performance..
* storing references to these bindgroups here is just faster for access!
* keeps a reference to the bind group to set when rendering this batch for WebGPU. Will be null if using WebGl.
*/
bindGroup: BindGroup;
batcher: Batcher;
destroy(): void;
}
/**
* Represents an element that can be batched for rendering.
* @interface
* @category rendering
* @advanced
*/
export interface BatchableElement {
/**
* The name of the batcher to use. Must be registered.
* @type {string}
*/
batcherName: string;
/**
* The texture to be used for rendering.
* @type {Texture}
*/
texture: Texture;
/**
* The blend mode to be applied.
* @type {BLEND_MODES}
*/
blendMode: BLEND_MODES;
/**
* The size of the index data.
* @type {number}
*/
indexSize: number;
/**
* The size of the attribute data.
* @type {number}
*/
attributeSize: number;
/**
* The topology to be used for rendering.
* @type {Topology}
*/
topology: Topology;
/**
* Whether the element should be packed as a quad for better performance.
* @type {boolean}
*/
packAsQuad: boolean;
/**
* The texture ID, stored for efficient updating.
* @type {number}
* @private
*/
_textureId: number;
/**
* The starting position in the attribute buffer.
* @type {number}
* @private
*/
_attributeStart: number;
/**
* The starting position in the index buffer.
* @type {number}
* @private
*/
_indexStart: number;
/**
* Reference to the batcher.
* @type {Batcher}
* @private
*/
_batcher: Batcher;
/**
* Reference to the batch.
* @type {Batch}
* @private
*/
_batch: Batch;
}
/**
* Represents a batchable quad element.
* @extends BatchableElement
* @category rendering
* @advanced
*/
export interface BatchableQuadElement extends BatchableElement {
/**
* Indicates that this element should be packed as a quad.
* @type {true}
*/
packAsQuad: true;
/**
* The size of the attribute data for this quad element.
* @type {4}
*/
attributeSize: 4;
/**
* The size of the index data for this quad element.
* @type {6}
*/
indexSize: 6;
/**
* The bounds data for this quad element.
* @type {BoundsData}
*/
bounds: BoundsData;
}
/**
* Represents a batchable mesh element.
* @extends BatchableElement
* @category rendering
* @advanced
*/
export interface BatchableMeshElement extends BatchableElement {
/**
* The UV coordinates of the mesh.
* @type {number[] | Float32Array}
*/
uvs: number[] | Float32Array;
/**
* The vertex positions of the mesh.
* @type {number[] | Float32Array}
*/
positions: number[] | Float32Array;
/**
* The indices of the mesh.
* @type {number[] | Uint16Array | Uint32Array}
*/
indices: number[] | Uint16Array | Uint32Array;
/**
* The offset in the index buffer.
* @type {number}
*/
indexOffset: number;
/**
* The offset in the attribute buffer.
* @type {number}
*/
attributeOffset: number;
/**
* Indicates that this element should not be packed as a quad.
* @type {false}
*/
packAsQuad: false;
}
/**
* The options for the batcher.
* @category rendering
* @advanced
*/
export interface BatcherOptions {
/** The maximum number of textures per batch. */
maxTextures: number;
/** The initial size of the attribute buffer. */
attributesInitialSize?: number;
/** The initial size of the index buffer. */
indicesInitialSize?: number;
}
/**
* A batcher is used to batch together objects with the same texture.
* It is an abstract class that must be extended. see DefaultBatcher for an example.
* @category rendering
* @advanced
*/
export declare abstract class Batcher {
static defaultOptions: Partial<BatcherOptions>;
/** unique id for this batcher */
readonly uid: number;
/** The buffer containing attribute data for all elements in the batch. */
attributeBuffer: ViewableBuffer;
/** The buffer containing index data for all elements in the batch. */
indexBuffer: IndexBufferArray;
/** The current size of the attribute data in the batch. */
attributeSize: number;
/** The current size of the index data in the batch. */
indexSize: number;
/** The total number of elements currently in the batch. */
elementSize: number;
/** The starting index of elements in the current batch. */
elementStart: number;
/** Indicates whether the batch data has been modified and needs updating. */
dirty: boolean;
/** The current index of the batch being processed. */
batchIndex: number;
/** An array of all batches created during the current rendering process. */
batches: Batch[];
private _elements;
private _batchIndexStart;
private _batchIndexSize;
/** The maximum number of textures per batch. */
readonly maxTextures: number;
/** The name of the batcher. Must be implemented by subclasses. */
abstract name: string;
/** The vertex size of the batcher. Must be implemented by subclasses. */
protected abstract vertexSize: number;
/** The geometry used by this batcher. Must be implemented by subclasses. */
abstract geometry: Geometry;
/**
* The shader used by this batcher. Must be implemented by subclasses.
* this can be shared by multiple batchers of the same type.
*/
abstract shader: Shader;
/**
* Packs the attributes of a BatchableMeshElement into the provided views.
* Must be implemented by subclasses.
* @param element - The BatchableMeshElement to pack.
* @param float32View - The Float32Array view to pack into.
* @param uint32View - The Uint32Array view to pack into.
* @param index - The starting index in the views.
* @param textureId - The texture ID to use.
*/
abstract packAttributes(element: BatchableMeshElement, float32View: Float32Array, uint32View: Uint32Array, index: number, textureId: number): void;
/**
* Packs the attributes of a BatchableQuadElement into the provided views.
* Must be implemented by subclasses.
* @param element - The BatchableQuadElement to pack.
* @param float32View - The Float32Array view to pack into.
* @param uint32View - The Uint32Array view to pack into.
* @param index - The starting index in the views.
* @param textureId - The texture ID to use.
*/
abstract packQuadAttributes(element: BatchableQuadElement, float32View: Float32Array, uint32View: Uint32Array, index: number, textureId: number): void;
constructor(options: BatcherOptions);
begin(): void;
add(batchableObject: BatchableElement): void;
checkAndUpdateTexture(batchableObject: BatchableElement, texture: Texture): boolean;
updateElement(batchableObject: BatchableElement): void;
/**
* breaks the batcher. This happens when a batch gets too big,
* or we need to switch to a different type of rendering (a filter for example)
* @param instructionSet
*/
break(instructionSet: InstructionSet): void;
private _finishBatch;
finish(instructionSet: InstructionSet): void;
/**
* Resizes the attribute buffer to the given size (1 = 1 float32)
* @param size - the size in vertices to ensure (not bytes!)
*/
ensureAttributeBuffer(size: number): void;
/**
* Resizes the index buffer to the given size (1 = 1 float32)
* @param size - the size in vertices to ensure (not bytes!)
*/
ensureIndexBuffer(size: number): void;
private _resizeAttributeBuffer;
private _resizeIndexBuffer;
packQuadIndex(indexBuffer: IndexBufferArray, index: number, indicesOffset: number): void;
packIndex(element: BatchableMeshElement, indexBuffer: IndexBufferArray, index: number, indicesOffset: number): void;
/**
* Destroys the batch and its resources.
* @param options - destruction options
* @param options.shader - whether to destroy the associated shader
*/
destroy(options?: {
shader?: boolean;
}): void;
}
/**
* An interface for a pipe that can be used to build instructions for the renderer.
* InstructionPipes are specifically used to manage the state of the renderer.
* For example, the BlendModePipe is used to set the blend mode of the renderer.
* @category rendering
* @advanced
*/
export interface InstructionPipe<INSTRUCTION extends Instruction> {
/**
* called just before we execute the draw calls , this is where the pipes have an opportunity to
* upload data to the GPU. This is only called if data changes.
* @param instructionSet - the instruction set currently being built
*/
upload?: (instructionSet: InstructionSet) => void;
/**
* this is where the actual instruction is executed - eg make the draw call
* activate a filter. Any instructions that have the same renderPipeId have their
* execute method called
* @param instruction - the instruction to execute
*/
execute?: (instruction: INSTRUCTION) => void;
buildReset?: (instructionSet: InstructionSet) => void;
buildStart?: (instructionSet: InstructionSet) => void;
buildEnd?: (instructionSet: InstructionSet) => void;
/** Called just after the render ends giving the RenderPipes a chance to do any cleanup */
renderEnd?: () => void;
/** Called just before the render starts giving the RenderPipes a chance to do any setup */
renderStart?: () => void;
/**
* Used by the effect pipes push and pop effects to the renderer. A push effect allows
* the renderer to change its state to support the effect. A pop effect allows the renderer
* to return to its previous state. An example of this would be the filter effect.
* @param effect - the effect to push
* @param targetContainer - the container that the effect is being applied to
* @param instructionSet - the instruction set currently being built
*/
push?: (effect: Effect, targetContainer: Container, instructionSet: InstructionSet) => void;
/**
* Used by effect pipes to pop effects from the renderer.
* @param effect - the effect to pop
* @param targetContainer - the container that the effect is being applied to
* @param instructionSet - the instruction set currently being built
*/
pop?: (effect: Effect, targetContainer: Container, instructionSet: InstructionSet) => void;
}
/**
* An interface for a pipe that can be used to build instructions for the renderer.
* RenderPipes are specifically used to render Renderables like a Mesh.
* @category rendering
* @advanced
*/
export interface RenderPipe<RENDERABLE = Renderable> {
/**
* This is where the renderable is added to the instruction set. This is called once per renderable.
* For instance, a MeshRenderPipe could be used to enqueue a 'draw mesh' command
* to the rendering instruction set, catering to the rendering of mesh geometry.
* In more complex scenarios, such as the SpritePipe, this seamlessly coordinates
* with a batchPipe to efficiently batch and add batch instructions to the instructions set
*
* Add is called when the instructions set is being built.
* @param renderable - the renderable that needs to be rendered
* @param instructionSet - the instruction set currently being built
*/
addRenderable: (renderable: RENDERABLE, instructionSet: InstructionSet) => void;
/**
* Called whenever a renderable has been been updated, eg its position has changed.
* This is only called in the render loop if the instructions set is being reused
* from the last frame. Otherwise addRenderable is called.
* @param renderable - the renderable that needs to be rendered
*/
updateRenderable: (renderable: RENDERABLE) => void;
/**
* Called whenever a renderable is destroyed, often the pipes keep a webGL / webGPU specific representation
* of the renderable that needs to be tidied up when the renderable is destroyed.
* @param renderable - the renderable that needs to be rendered
*/
destroyRenderable?: (renderable: RENDERABLE) => void;
/**
* This function is called when the renderer is determining if it can use the same instruction set again to
* improve performance. If this function returns true, the renderer will rebuild the whole instruction set
* for the scene. This is only called if the scene has not its changed its structure .
* @param renderable
* @returns {boolean}
*/
validateRenderable: (renderable: RENDERABLE) => boolean;
}
/**
* An interface for a pipe that can be used to build instructions for the renderer.
* BatchPipes are specifically used to build and render Batches.
* @category rendering
* @advanced
*/
export interface BatchPipe {
/**
* Add a add a batchable object to the batch.
* @param renderable - a batchable object that can be added to the batch
* @param instructionSet - the instruction set currently being built
*/
addToBatch: (renderable: BatchableElement, instructionSet: InstructionSet) => void;
/**
* Forces the batch to break. This can happen if for example you need to render everything and then
* change the render target.
* @param instructionSet - the instruction set currently being built
*/
break: (instructionSet: InstructionSet) => void;
}
/**
* A helpful type that can be used to create a new RenderPipe, BatchPipe or InstructionPipe
* @category rendering
* @advanced
*/
export interface PipeConstructor {
new (renderer: Renderer, adaptor?: any): RenderPipe | BatchPipe | InstructionPipe<any>;
}
/**
* A function that takes a renderer and does the custom rendering logic.
* This is the function that will be called each frame.
* @param renderer - The current renderer
* @example
* ```js
* import { RenderContainer } from 'pixi.js';
*
* // create a new render container
* const renderContainer = new RenderContainer((renderer) => {
* // custom render logic here
* renderer.clear({
* clearColor: 'green', // clear the screen to green when rendering this item
* });
* });
* ```
* @category scene
* @advanced
*/
export type RenderFunction = (renderer: Renderer) => void;
/**
* Options for the {@link RenderContainer} constructor.
* @category scene
* @advanced
* @noInheritDoc
*/
export interface RenderContainerOptions extends ContainerOptions {
/** the optional custom render function if you want to inject the function via the constructor */
render?: RenderFunction;
/** how to know if the custom render logic contains a point or not, used for interaction */
containsPoint?: (point: Point) => boolean;
/** how to add the bounds of this object when measuring */
addBounds?: (bounds: BoundsData) => void;
}
/**
* A container that allows for custom rendering logic. Its essentially calls the render function each frame
* and allows for custom rendering logic - the render could be a WebGL renderer or WebGPU render or even a canvas render.
* Its up to you to define the logic.
*
* This can be used in two ways, either by extending the class and overriding the render method,
* or by passing a custom render function
* @example
* ```js
* import { RenderContainer } from 'pixi.js';
*
* // extend the class
* class MyRenderContainer extends RenderContainer
* {
* render(renderer)
* {
* renderer.clear({
* clearColor: 'green', // clear the screen to green when rendering this item
* });
* }
* }
*
* // override the render method
* const renderContainer = new RenderContainer(
* (renderer) => {
* renderer.clear({
* clearColor: 'green', // clear the screen to green when rendering this item
* });
* })
* ```
* @category scene
* @advanced
*/
export declare class RenderContainer extends ViewContainer implements Instruction {
/** @internal */
readonly renderPipeId: string;
/** @internal */
batched: boolean;
/**
* Adds the bounds of this text to the bounds object.
* @param bounds - The output bounds object.
*/
addBounds: (bounds: Bounds) => void;
/**
* @param options - The options for the container.
*/
constructor(options: RenderContainerOptions | RenderFunction);
/** @private */
protected updateBounds(): void;
/**
* An overridable function that can be used to render the object using the current renderer.
* @param _renderer - The current renderer
*/
render(_renderer: Renderer): void;
}
/**
* The CustomRenderPipe is a render pipe that allows for custom rendering logic for your renderable objects.
* @example
* import { RenderContainer } from 'pixi.js';
*
* const renderContainer = new RenderContainer(
* (renderer) => {
* renderer.clear({
* clearColor: 'green', // clear the screen to green when rendering this item
* });
* })
* @category rendering
* @internal
*/
export declare class CustomRenderPipe implements InstructionPipe<RenderContainer>, RenderPipe<RenderContainer> {
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "customRender";
};
private _renderer;
constructor(renderer: Renderer);
updateRenderable(): void;
destroyRenderable(): void;
validateRenderable(): boolean;
addRenderable(container: RenderContainer, instructionSet: InstructionSet): void;
execute(container: RenderContainer): void;
destroy(): void;
}
/**
* This class represents a geometry used for batching in the rendering system.
* It defines the structure of vertex attributes and index buffers for batched rendering.
* @category rendering
* @advanced
*/
export declare class BatchGeometry extends Geometry {
constructor();
}
/**
* DefaultShader is a specialized shader class designed for batch rendering.
* It extends the base Shader class and provides functionality for handling
* color, texture batching, and pixel rounding in both WebGL and WebGPU contexts.
*
* It is used by the default batcher
* @extends Shader
* @category rendering
* @advanced
*/
export declare class DefaultShader extends Shader {
/** @internal */
maxTextures?: number;
constructor(maxTextures: number);
}
/**
* Represents the common elements for default batch rendering.
* This interface defines the properties that are used by the DefaultBatcher
* to render elements efficiently in a batch.
* @category rendering
* @advanced
*/
export interface DefaultBatchElements {
/**
* The color of the element that will be multiplied with the texture color.
* This is typically represented as a 32-bit integer in RGBA format.
*/
color: number;
/**
* Determines whether the element should be rounded to the nearest pixel.
* - 0: No rounding (default)
* - 1: Round to nearest pixel
* This can help with visual consistency, especially for pixel art styles.
*/
roundPixels: 0 | 1;
/**
* The transform matrix of the element.
* This matrix represents the position, scale, rotation, and skew of the element.
*/
transform: Matrix;
}
/**
* Represents a batchable quad element with default batch properties.
* @category rendering
* @advanced
*/
export interface DefaultBatchableQuadElement extends BatchableQuadElement, DefaultBatchElements {
}
/**
* Represents a batchable mesh element with default batch properties.
* @category rendering
* @advanced
*/
export interface DefaultBatchableMeshElement extends BatchableMeshElement, DefaultBatchElements {
}
/**
* The default batcher is used to batch quads and meshes. This batcher will batch the following elements:
* - tints
* - roundPixels
* - texture
* - transform
* @category rendering
* @advanced
*/
export declare class DefaultBatcher extends Batcher {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.Batcher
];
readonly name: "default";
};
geometry: BatchGeometry;
shader: DefaultShader;
name: "default";
/** The size of one attribute. 1 = 32 bit. x, y, u, v, color, textureIdAndRound -> total = 6 */
vertexSize: number;
constructor(options: BatcherOptions);
/**
* Packs the attributes of a DefaultBatchableMeshElement into the provided views.
* @param element - The DefaultBatchableMeshElement to pack.
* @param float32View - The Float32Array view to pack into.
* @param uint32View - The Uint32Array view to pack into.
* @param index - The starting index in the views.
* @param textureId - The texture ID to use.
*/
packAttributes(element: DefaultBatchableMeshElement, float32View: Float32Array, uint32View: Uint32Array, index: number, textureId: number): void;
/**
* Packs the attributes of a DefaultBatchableQuadElement into the provided views.
* @param element - The DefaultBatchableQuadElement to pack.
* @param float32View - The Float32Array view to pack into.
* @param uint32View - The Uint32Array view to pack into.
* @param index - The starting index in the views.
* @param textureId - The texture ID to use.
*/
packQuadAttributes(element: DefaultBatchableQuadElement, float32View: Float32Array, uint32View: Uint32Array, index: number, textureId: number): void;
/**
* Updates the maximum number of textures that can be used in the shader.
* @param maxTextures - The maximum number of textures that can be used in the shader.
* @internal
*/
_updateMaxTextures(maxTextures: number): void;
destroy(): void;
}
/**
* A batchable sprite object.
* @internal
*/
export declare class BatchableSprite implements DefaultBatchableQuadElement, GPUData {
batcherName: string;
topology: Topology;
readonly attributeSize = 4;
readonly indexSize = 6;
readonly packAsQuad = true;
transform: Matrix;
renderable: Container;
texture: Texture;
bounds: BoundsData;
roundPixels: 0 | 1;
_indexStart: number;
_textureId: number;
_attributeStart: number;
_batcher: Batcher;
_batch: Batch;
get blendMode(): BLEND_MODES;
get color(): number;
reset(): void;
destroy(): void;
}
/**
* Options for caching a container as a texture.
* @category rendering
* @advanced
*/
export interface CacheAsTextureOptions {
/**
* If true, the texture will be antialiased. This smooths out the edges of the texture.
* @default false
*/
antialias?: boolean;
/**
* The resolution of the texture. A higher resolution means a sharper texture but uses more memory.
* By default the resolution is 1 which is the same as the rendererers resolution.
*/
resolution?: number;
/**
* Scale Mode to use for the cached texture
* @type {SCALE_MODE}
* @default 'linear'
* @example
* ```ts
* const container = new Container();
* container.cacheAsTexture({ scaleMode: 'nearest' });
* ```
* @see {@link SCALE_MODE}
*/
scaleMode?: SCALE_MODE;
}
/**
* A RenderGroup is a class that is responsible for I generating a set of instructions that are used to render the
* root container and its children. It also watches for any changes in that container or its children,
* these changes are analysed and either the instruction set is rebuild or the instructions data is updated.
* @category rendering
* @advanced
*/
export declare class RenderGroup implements Instruction {
renderPipeId: string;
root: Container;
canBundle: boolean;
renderGroupParent: RenderGroup;
renderGroupChildren: RenderGroup[];
worldTransform: Matrix;
worldColorAlpha: number;
worldColor: number;
worldAlpha: number;
readonly childrenToUpdate: Record<number, {
list: Container[];
index: number;
}>;
updateTick: number;
gcTick: number;
readonly childrenRenderablesToUpdate: {
list: Container[];
index: number;
};
structureDidChange: boolean;
instructionSet: InstructionSet;
private readonly _onRenderContainers;
/**
* Indicates if the cached texture needs to be updated.
* @default true
*/
textureNeedsUpdate: boolean;
/**
* Indicates if the container should be cached as a texture.
* @default false
*/
isCachedAsTexture: boolean;
/**
* The texture used for caching the container. this is only set if isCachedAsTexture is true.
* It can only be accessed after a render pass.
* @type {Texture | undefined}
*/
texture?: Texture;
/**
* The bounds of the cached texture.
* @type {Bounds | undefined}
* @ignore
*/
_textureBounds?: Bounds;
/**
* The options for caching the container as a texture.
* @type {CacheAsTextureOptions}
*/
textureOptions: CacheAsTextureOptions;
/**
* holds a reference to the batchable render sprite
* @ignore
*/
_batchableRenderGroup: BatchableSprite;
/**
* Holds a reference to the closest parent RenderGroup that has isCachedAsTexture enabled.
* This is used to properly transform coordinates when rendering into cached textures.
* @type {RenderGroup | null}
* @ignore
*/
_parentCacheAsTextureRenderGroup: RenderGroup;
private _inverseWorldTransform;
private _textureOffsetInverseTransform;
private _inverseParentTextureTransform;
private _matrixDirty;
init(root: Container): void;
enableCacheAsTexture(options?: CacheAsTextureOptions): void;
disableCacheAsTexture(): void;
updateCacheTexture(): void;
reset(): void;
get localTransform(): Matrix;
addRenderGroupChild(renderGroupChild: RenderGroup): void;
private _removeRenderGroupChild;
addChild(child: Container): void;
removeChild(child: Container): void;
removeChildren(children: Container[]): void;
onChildUpdate(child: Container): void;
updateRenderable(renderable: ViewContainer): void;
onChildViewUpdate(child: Container): void;
get isRenderable(): boolean;
/**
* adding a container to the onRender list will make sure the user function
* passed in to the user defined 'onRender` callBack
* @param container - the container to add to the onRender list
*/
addOnRender(container: Container): void;
removeOnRender(container: Container): void;
runOnRender(renderer: Renderer): void;
destroy(): void;
getChildren(out?: Container[]): Container[];
private _getChildren;
invalidateMatrices(): void;
/**
* Returns the inverse of the world transform matrix.
* @returns {Matrix} The inverse of the world transform matrix.
*/
get inverseWorldTransform(): Matrix;
/**
* Returns the inverse of the texture offset transform matrix.
* @returns {Matrix} The inverse of the texture offset transform matrix.
*/
get textureOffsetInverseTransform(): Matrix;
/**
* Returns the inverse of the parent texture transform matrix.
* This is used to properly transform coordinates when rendering into cached textures.
* @returns {Matrix} The inverse of the parent texture transform matrix.
*/
get inverseParentTextureTransform(): Matrix;
/**
* Returns a matrix that transforms coordinates to the correct coordinate space of the texture being rendered to.
* This is the texture offset inverse transform of the closest parent RenderGroup that is cached as a texture.
* @returns {Matrix | null} The transform matrix for the cached texture coordinate space,
* or null if no parent is cached as texture.
*/
get cacheToLocalTransform(): Matrix;
}
/**
* The RenderGroupPipe is a render pipe for rendering RenderGroups.
* @internal
*/
export declare class RenderGroupPipe implements InstructionPipe<RenderGroup> {
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "renderGroup";
};
private _renderer;
constructor(renderer: Renderer);
addRenderGroup(renderGroup: RenderGroup, instructionSet: InstructionSet): void;
execute(renderGroup: RenderGroup): void;
destroy(): void;
private _addRenderableDirect;
private _addRenderableCacheAsTexture;
private _executeCacheAsTexture;
private _executeDirect;
}
/**
* The view system manages the main canvas that is attached to the DOM.
* This main role is to deal with how the holding the view reference and dealing with how it is resized.
* @category rendering
* @internal
*/
export declare class RenderGroupSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "renderGroup";
};
private readonly _renderer;
constructor(renderer: Renderer);
protected render({ container, transform }: {
container: Container;
transform: Matrix;
}): void;
destroy(): void;
private _updateCachedRenderGroups;
private _updateRenderGroups;
private _updateRenderables;
/**
* @param renderGroup
* @param renderPipes
* @deprecated since 8.3.0
*/
private _buildInstructions;
}
/**
* Defines a size with a width and a height.
* @category maths
* @standard
*/
export interface Size {
/** The width. */
width: number;
/** The height. */
height: number;
}
/**
* A utility type that makes all properties of T optional except for the specified keys K.
* @category utils
* @internal
*/
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
/** @ignore */
export interface MeasureMixinConstructor {
/**
* The width of the display object, in pixels.
* @example
* ```ts
* new Container({ width: 100});
* ```
* @default 0
*/
width?: number;
/**
* The height of the display object, in pixels.
* @example
* ```ts
* new Container({ height: 100});
* ```
* @default 0
*/
height?: number;
}
/**
* The MeasureMixin interface provides methods for measuring and manipulating the size and bounds of a display object.
* It includes methods to get and set the size of the object, retrieve its local bounds,
* and calculate its global bounds.
* @category scene
* @advanced
*/
export interface MeasureMixin extends Required<MeasureMixinConstructor> {
getSize(out?: Size): Size;
setSize(width: number, height?: number): void;
setSize(value: Optional<Size, "height">): void;
/**
* Retrieves the local bounds of the container as a Bounds object.
* Uses cached values when possible for better performance.
* @example
* ```ts
* // Basic bounds check
* const bounds = container.getLocalBounds();
* console.log(`Width: ${bounds.width}, Height: ${bounds.height}`);
* // subsequent calls will reuse the cached bounds
* const cachedBounds = container.getLocalBounds();
* console.log(bounds === cachedBounds); // true
* ```
* @returns The bounding area
* @see {@link Container#getBounds} For world space bounds
* @see {@link Bounds} For bounds properties
*/
getLocalBounds(): Bounds;
/**
* Calculates and returns the (world) bounds of the display object as a Rectangle.
* Takes into account transforms and child bounds.
* @example
* ```ts
* // Basic bounds calculation
* const bounds = sprite.getBounds();
* console.log(`World bounds: ${bounds.x}, ${bounds.y}, ${bounds.width}, ${bounds.height}`);
*
* // Reuse bounds object for performance
* const recycleBounds = new Bounds();
* sprite.getBounds(false, recycleBounds);
*
* // Skip update for performance
* const fastBounds = sprite.getBounds(true);
* ```
* @remarks
* - Includes transform calculations
* - Updates scene graph by default
* - Can reuse bounds objects
* - Common in hit testing
* @param {boolean} skipUpdate - Setting to `true` will stop the transforms of the scene graph from
* being updated. This means the calculation returned MAY be out of date BUT will give you a
* nice performance boost.
* @param {Bounds} bounds - Optional bounds to store the result of the bounds calculation
* @returns The minimum axis-aligned rectangle in world space that fits around this object
* @see {@link Container#getLocalBounds} For untransformed bounds
* @see {@link Bounds} For bounds properties
*/
getBounds(skipUpdate?: boolean, bounds?: Bounds): Bounds;
/** @private */
_localBoundsCacheData: LocalBoundsCacheData;
/** @private */
_localBoundsCacheId: number;
/** @private */
_setWidth(width: number, localWidth: number): void;
/** @private */
_setHeight(height: number, localHeight: number): void;
}
interface LocalBoundsCacheData {
data: number[];
index: number;
didChange: boolean;
localBounds: Bounds;
}
/** @internal */
export declare const measureMixin: Partial<Container>;
/**
* Options for configuring a Sprite instance. Defines the texture, anchor point, and rendering behavior.
* @example
* ```ts
* // Create a basic sprite with texture
* const sprite = new Sprite({
* texture: Texture.from('sprite.png')
* });
*
* // Create a centered sprite with rounded position
* const centeredSprite = new Sprite({
* texture: Texture.from('centered.png'),
* anchor: 0.5, // Center point
* roundPixels: true, // Crisp rendering
* x: 100, // Position from ViewContainerOptions
* y: 100
* });
*
* // Create a sprite with specific anchor points
* const anchoredSprite = new Sprite({
* texture: Texture.from('corner.png'),
* anchor: {
* x: 1, // Right-aligned
* y: 0 // Top-aligned
* }
* });
* ```
* @extends ViewContainerOptions
* @category scene
* @standard
* @noInheritDoc
*/
export interface SpriteOptions extends PixiMixins.SpriteOptions, ViewContainerOptions {
/**
* The texture to use for the sprite. If not provided, uses Texture.EMPTY
* @default Texture.EMPTY
* @example
* ```ts
* // Create a sprite with a texture
* const sprite = new Sprite({
* texture: Texture.from('path/to/image.png')
* });
* // Update the texture later
* sprite.texture = Texture.from('path/to/another-image.png');
* ```
*/
texture?: Texture;
/**
* The anchor point of the sprite (0-1 range).
* Controls the origin point for rotation, scaling, and positioning.
* Can be a number for uniform anchor or a PointData for separate x/y values.
* @default 0
* @example
* ```ts
* // Centered anchor
* anchor: 0.5
* // Separate x/y anchor
* anchor: { x: 0.5, y: 0.5 }
* // Right-aligned anchor
* anchor: { x: 1, y: 0 }
* ```
*/
anchor?: PointData | number;
/**
* Whether or not to round the x/y position to whole pixels.
* Useful for crisp pixel art style rendering.
* @default false
* @example
* ```ts
* const sprite = new Sprite({
* texture: Texture.from('sprite.png'),
* roundPixels: true // Ensures crisp rendering
* });
* ```
*/
roundPixels?: boolean;
}
export interface Sprite extends PixiMixins.Sprite, ViewContainer<BatchableSprite> {
}
/**
* The Sprite object is one of the most important objects in PixiJS. It is a
* drawing item that can be added to a scene and rendered to the screen.
* Sprites can display images, handle input events, and be transformed in various ways.
* @example
* ```ts
* // Create a sprite directly from an image path
* const sprite = Sprite.from('assets/image.png');
* sprite.position.set(100, 100);
* app.stage.addChild(sprite);
*
* // Create from a spritesheet (more efficient)
* const sheet = await Assets.load('assets/spritesheet.json');
* const sprite = new Sprite(sheet.textures['image.png']);
*
* // Create with specific options
* const configuredSprite = new Sprite({
* texture: Texture.from('sprite.png'),
* anchor: 0.5, // Center anchor point
* position: { x: 100, y: 100 },
* scale: { x: 2, y: 2 }, // Double size
* rotation: Math.PI / 4 // 45 degrees
* });
*
* // Animate sprite properties
* app.ticker.add(() => {
* sprite.rotation += 0.1; // Rotate
* sprite.scale.x = Math.sin(performance.now() / 1000) + 1; // Pulse scale
* });
* ```
* @category scene
* @standard
* @see {@link SpriteOptions} For configuration options
* @see {@link Texture} For texture management
* @see {@link Assets} For asset loading
*/
export declare class Sprite extends ViewContainer<BatchableSprite> {
/**
* Creates a new sprite based on a source texture, image, video, or canvas element.
* This is a convenience method that automatically creates and manages textures.
* @example
* ```ts
* // Create from path or URL
* const sprite = Sprite.from('assets/image.png');
*
* // Create from existing texture
* const sprite = Sprite.from(texture);
*
* // Create from canvas
* const canvas = document.createElement('canvas');
* const sprite = Sprite.from(canvas, true); // Skip caching new texture
* ```
* @param source - The source to create the sprite from. Can be a path to an image, a texture,
* or any valid texture source (canvas, video, etc.)
* @param skipCache - Whether to skip adding to the texture cache when creating a new texture
* @returns A new sprite based on the source
* @see {@link Texture.from} For texture creation details
* @see {@link Assets} For asset loading and management
*/
static from(source: Texture | TextureSourceLike, skipCache?: boolean): Sprite;
/** @internal */
readonly renderPipeId: string;
/** @internal */
batched: boolean;
/** @internal */
readonly _anchor: ObservablePoint;
/** @internal */
_texture: Texture;
private readonly _visualBounds;
private _width;
private _height;
/**
* @param options - The options for creating the sprite.
*/
constructor(options?: SpriteOptions | Texture);
set texture(value: Texture);
/**
* The texture that is displayed by the sprite. When changed, automatically updates
* the sprite dimensions and manages texture event listeners.
* @example
* ```ts
* // Create sprite with texture
* const sprite = new Sprite({
* texture: Texture.from('sprite.png')
* });
*
* // Update texture
* sprite.texture = Texture.from('newSprite.png');
*
* // Use texture from spritesheet
* const sheet = await Assets.load('spritesheet.json');
* sprite.texture = sheet.textures['frame1.png'];
*
* // Reset to empty texture
* sprite.texture = Texture.EMPTY;
* ```
* @see {@link Texture} For texture creation and management
* @see {@link Assets} For asset loading
*/
get texture(): Texture;
/**
* The bounds of the sprite, taking into account the texture's trim area.
* @example
* ```ts
* const texture = new Texture({
* source: new TextureSource({ width: 300, height: 300 }),
* frame: new Rectangle(196, 66, 58, 56),
* trim: new Rectangle(4, 4, 58, 56),
* orig: new Rectangle(0, 0, 64, 64),
* rotate: 2,
* });
* const sprite = new Sprite(texture);
* const visualBounds = sprite.visualBounds;
* // console.log(visualBounds); // { minX: -4, maxX: 62, minY: -4, maxY: 60 }
*/
get visualBounds(): BoundsData;
/**
* @deprecated
* @ignore
*/
get sourceBounds(): BoundsData;
/** @private */
protected updateBounds(): void;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* sprite.destroy();
* sprite.destroy(true);
* sprite.destroy({ texture: true, textureSource: true });
*/
destroy(options?: DestroyOptions): void;
/**
* The anchor sets the origin point of the sprite. The default value is taken from the {@link Texture}
* and passed to the constructor.
*
* - The default is `(0,0)`, this means the sprite's origin is the top left.
* - Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered.
* - Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner.
*
* If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
* @example
* ```ts
* // Center the anchor point
* sprite.anchor = 0.5; // Sets both x and y to 0.5
* sprite.position.set(400, 300); // Sprite will be centered at this position
*
* // Set specific x/y anchor points
* sprite.anchor = {
* x: 1, // Right edge
* y: 0 // Top edge
* };
*
* // Using individual coordinates
* sprite.anchor.set(0.5, 1); // Center-bottom
*
* // For rotation around center
* sprite.anchor.set(0.5);
* sprite.rotation = Math.PI / 4; // 45 degrees around center
*
* // For scaling from center
* sprite.anchor.set(0.5);
* sprite.scale.set(2); // Scales from center point
* ```
*/
get anchor(): ObservablePoint;
set anchor(value: PointData | number);
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set.
* @example
* ```ts
* // Set width directly
* sprite.width = 200;
* console.log(sprite.scale.x); // Scale adjusted to match width
*
* // Set width while preserving aspect ratio
* const ratio = sprite.height / sprite.width;
* sprite.width = 300;
* sprite.height = 300 * ratio;
*
* // For better performance when setting both width and height
* sprite.setSize(300, 400); // Avoids recalculating bounds twice
*
* // Reset to original texture size
* sprite.width = sprite.texture.orig.width;
* ```
*/
get width(): number;
set width(value: number);
/**
* The height of the sprite, setting this will actually modify the scale to achieve the value set.
* @example
* ```ts
* // Set height directly
* sprite.height = 150;
* console.log(sprite.scale.y); // Scale adjusted to match height
*
* // Set height while preserving aspect ratio
* const ratio = sprite.width / sprite.height;
* sprite.height = 200;
* sprite.width = 200 * ratio;
*
* // For better performance when setting both width and height
* sprite.setSize(300, 400); // Avoids recalculating bounds twice
*
* // Reset to original texture size
* sprite.height = sprite.texture.orig.height;
* ```
*/
get height(): number;
set height(value: number);
/**
* Retrieves the size of the Sprite as a [Size]{@link Size} object based on the texture dimensions and scale.
* This is faster than getting width and height separately as it only calculates the bounds once.
* @example
* ```ts
* // Basic size retrieval
* const sprite = new Sprite(Texture.from('sprite.png'));
* const size = sprite.getSize();
* console.log(`Size: ${size.width}x${size.height}`);
*
* // Reuse existing size object
* const reuseSize = { width: 0, height: 0 };
* sprite.getSize(reuseSize);
* ```
* @param out - Optional object to store the size in, to avoid allocating a new object
* @returns The size of the Sprite
* @see {@link Sprite#width} For getting just the width
* @see {@link Sprite#height} For getting just the height
* @see {@link Sprite#setSize} For setting both width and height
*/
getSize(out?: Size): Size;
/**
* Sets the size of the Sprite to the specified width and height.
* This is faster than setting width and height separately as it only recalculates bounds once.
* @example
* ```ts
* // Basic size setting
* const sprite = new Sprite(Texture.from('sprite.png'));
* sprite.setSize(100, 200); // Width: 100, Height: 200
*
* // Set uniform size
* sprite.setSize(100); // Sets both width and height to 100
*
* // Set size with object
* sprite.setSize({
* width: 200,
* height: 300
* });
*
* // Reset to texture size
* sprite.setSize(
* sprite.texture.orig.width,
* sprite.texture.orig.height
* );
* ```
* @param value - This can be either a number or a {@link Size} object
* @param height - The height to set. Defaults to the value of `width` if not provided
* @see {@link Sprite#width} For setting width only
* @see {@link Sprite#height} For setting height only
* @see {@link Sprite#texture} For the source dimensions
*/
setSize(value: number | Optional<Size, "height">, height?: number): void;
}
/** @internal */
export declare class SpritePipe implements RenderPipe<Sprite> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "sprite";
};
private _renderer;
constructor(renderer: Renderer);
addRenderable(sprite: Sprite, instructionSet: InstructionSet): void;
updateRenderable(sprite: Sprite): void;
validateRenderable(sprite: Sprite): boolean;
private _updateBatchableSprite;
private _getGpuSprite;
private _initGPUSprite;
destroy(): void;
}
/**
* Options for {@link autoDetectRenderer}.
* @category rendering
* @advanced
*/
export interface AutoDetectOptions extends RendererOptions {
/** The preferred renderer type. WebGPU is recommended as its generally faster than WebGL. */
preference?: "webgl" | "webgpu";
/** Optional WebGPUOptions to pass only to WebGPU renderer. */
webgpu?: Partial<WebGPUOptions>;
/** Optional WebGLOptions to pass only to the WebGL renderer */
webgl?: Partial<WebGLOptions>;
}
/**
* Automatically determines the most appropriate renderer for the current environment.
*
* The function will prioritize the WebGL renderer as it is the most tested safe API to use.
* In the near future as WebGPU becomes more stable and ubiquitous, it will be prioritized over WebGL.
*
* The selected renderer's code is then dynamically imported to optimize
* performance and minimize the initial bundle size.
*
* To maximize the benefits of dynamic imports, it's recommended to use a modern bundler
* that supports code splitting. This will place the renderer code in a separate chunk,
* which is loaded only when needed.
* @example
*
* // create a renderer
* const renderer = await autoDetectRenderer({
* width: 800,
* height: 600,
* antialias: true,
* });
*
* // custom for each renderer
* const renderer = await autoDetectRenderer({
* width: 800,
* height: 600,
* webgpu:{
* antialias: true,
* backgroundColor: 'red'
* },
* webgl:{
* antialias: true,
* backgroundColor: 'green'
* }
* });
* @param options - A partial configuration object based on the `AutoDetectOptions` type.
* @returns A Promise that resolves to an instance of the selected renderer.
* @category rendering
* @standard
*/
export declare function autoDetectRenderer(options: Partial<AutoDetectOptions>): Promise<Renderer>;
/**
* Interface for creating Application plugins. Any plugin that's usable for Application must implement these methods.
*
* To create a plugin:
* 1. Create a class that implements this interface
* 2. Add the required static extension property
* 3. Register the plugin using extensions.add()
* @example
* ```ts
* import { ApplicationPlugin, ExtensionType, extensions } from 'pixi.js';
*
* class MyPlugin {
* // Required: Declare the extension type
* public static extension = ExtensionType.Application;
*
* // Required: Implement init method
* public static init(options: Partial<ApplicationOptions>): void {
* // Add properties/methods to the Application instance (this)
* Object.defineProperty(this, 'myFeature', {
* value: () => console.log('My feature!'),
* });
*
* // Use options if needed
* console.log('Plugin initialized with:', options);
* }
*
* // Required: Implement destroy method
* public static destroy(): void {
* // Clean up any resources
* console.log('Plugin destroyed');
* }
* }
*
* // Register the plugin
* extensions.add(MyPlugin);
*
* // Usage in application
* const app = new Application();
* await app.init();
* app.myFeature(); // Output: "My feature!"
* ```
* > [!IMPORTANT]
* > - Plugins are initialized in the order they are added
* > - Plugins are destroyed in reverse order
* > - The `this` context in both methods refers to the Application instance
* @see {@link ExtensionType} For different types of extensions
* @see {@link extensions} For the extension registration system
* @see {@link ApplicationOptions} For available application options
* @category app
* @advanced
*/
export interface ApplicationPlugin {
/**
* Called when Application is constructed, scoped to Application instance.
* Passes in `options` as the only argument, which are Application `init()` options.
* @param {object} options - Application options.
*/
init(options: Partial<ApplicationOptions>): void;
/** Called when destroying Application, scoped to Application instance. */
destroy(): void;
}
/**
* Application options supplied to the {@link Application#init} method.
* These options configure how your PixiJS application behaves.
* @category app
* @standard
* @example
* ```js
* import { Application } from 'pixi.js';
*
* const app = new Application();
*
* // Initialize with common options
* await app.init({
* // Rendering options
* width: 800, // Canvas width
* height: 600, // Canvas height
* backgroundColor: 0x1099bb, // Background color
* antialias: true, // Enable antialiasing
* resolution: window.devicePixelRatio, // Screen resolution
*
* // Performance options
* autoStart: true, // Auto-starts the render loop
* sharedTicker: true, // Use shared ticker for better performance
*
* // Automatic resize options
* resizeTo: window, // Auto-resize to window
* autoDensity: true, // Adjust for device pixel ratio
*
* // Advanced options
* preference: 'webgl', // Renderer preference ('webgl' or 'webgpu')
* powerPreference: 'high-performance' // GPU power preference
* });
* ```
* @see {@link WebGLOptions} For resize-related options
* @see {@link WebGPUOptions} For resize-related options
* @see {@link TickerPlugin} For ticker-related options
* @see {@link ResizePlugin} For resize-related options
*/
export interface ApplicationOptions extends AutoDetectOptions, PixiMixins.ApplicationOptions {
}
export interface Application extends PixiMixins.Application {
}
/**
* Convenience class to create a new PixiJS application.
*
* The Application class is the main entry point for creating a PixiJS application. It handles the setup of all core
* components needed to start rendering and managing your game or interactive experience.
*
* Key features:
* - Automatically creates and manages the renderer
* - Provides a stage (root container) for your display objects
* - Handles canvas creation and management
* - Supports plugins for extending functionality
* - {@link ResizePlugin} for automatic resizing
* - {@link TickerPlugin} for managing frame updates
* - {@link CullerPlugin} for culling off-screen objects
* @example
* ```js
* import { Assets, Application, Sprite } from 'pixi.js';
*
* // Create a new application
* const app = new Application();
*
* // Initialize with options
* await app.init({
* width: 800, // Canvas width
* height: 600, // Canvas height
* backgroundColor: 0x1099bb, // Background color
* antialias: true, // Enable antialiasing
* resolution: 1, // Resolution / device pixel ratio
* preference: 'webgl', // or 'webgpu' // Renderer preference
* });
*
* // Add the canvas to your webpage
* document.body.appendChild(app.canvas);
*
* // Start adding content to your application
* const texture = await Assets.load('your-image.png');
* const sprite = new Sprite(texture);
* app.stage.addChild(sprite);
* ```
* > [!IMPORTANT] From PixiJS v8.0.0, the application must be initialized using the async `init()` method
* > rather than passing options to the constructor.
* @category app
* @standard
* @see {@link ApplicationOptions} For all available initialization options
* @see {@link Container} For information about the stage container
* @see {@link Renderer} For details about the rendering system
*/
export declare class Application<R extends Renderer = Renderer> {
/**
* Collection of installed plugins.
* @internal
*/
static _plugins: ApplicationPlugin[];
/**
* The root display container for your application.
* All visual elements should be added to this container or its children.
* @example
* ```js
* // Create a sprite and add it to the stage
* const sprite = Sprite.from('image.png');
* app.stage.addChild(sprite);
*
* // Create a container for grouping objects
* const container = new Container();
* app.stage.addChild(container);
* ```
*/
stage: Container;
/**
* The renderer instance that handles all drawing operations.
*
* Unless specified, it will automatically create a WebGL renderer if available.
* If WebGPU is available and the `preference` is set to `webgpu`, it will create a WebGPU renderer.
* @example
* ```js
* // Create a new application
* const app = new Application();
* await app.init({
* width: 800,
* height: 600,
* preference: 'webgl', // or 'webgpu'
* });
*
* // Access renderer properties
* console.log(app.renderer.width, app.renderer.height);
* ```
*/
renderer: R;
/** Create new Application instance */
constructor();
/** @deprecated since 8.0.0 */
constructor(options?: Partial<ApplicationOptions>);
/**
* Initializes the PixiJS application with the specified options.
*
* This method must be called after creating a new Application instance.
* @param options - Configuration options for the application and renderer
* @returns A promise that resolves when initialization is complete
* @example
* ```js
* const app = new Application();
*
* // Initialize with custom options
* await app.init({
* width: 800,
* height: 600,
* backgroundColor: 0x1099bb,
* preference: 'webgl', // or 'webgpu'
* });
* ```
*/
init(options?: Partial<ApplicationOptions>): Promise<void>;
/**
* Renders the current stage to the screen.
*
* When using the default setup with {@link TickerPlugin} (enabled by default), you typically don't need to call
* this method directly as rendering is handled automatically.
*
* Only use this method if you've disabled the {@link TickerPlugin} or need custom
* render timing control.
* @example
* ```js
* // Example 1: Default setup (TickerPlugin handles rendering)
* const app = new Application();
* await app.init();
* // No need to call render() - TickerPlugin handles it
*
* // Example 2: Custom rendering loop (if TickerPlugin is disabled)
* const app = new Application();
* await app.init({ autoStart: false }); // Disable automatic rendering
*
* function animate() {
* app.render();
* requestAnimationFrame(animate);
* }
* animate();
* ```
*/
render(): void;
/**
* Reference to the renderer's canvas element. This is the HTML element
* that displays your application's graphics.
* @readonly
* @type {HTMLCanvasElement}
* @example
* ```js
* // Create a new application
* const app = new Application();
* // Initialize the application
* await app.init({...});
* // Add canvas to the page
* document.body.appendChild(app.canvas);
*
* // Access the canvas directly
* console.log(app.canvas); // HTMLCanvasElement
* ```
*/
get canvas(): R["canvas"];
/**
* Reference to the renderer's canvas element.
* @type {HTMLCanvasElement}
* @deprecated since 8.0.0
* @see {@link Application#canvas}
*/
get view(): R["canvas"];
/**
* Reference to the renderer's screen rectangle. This represents the visible area of your application.
*
* It's commonly used for:
* - Setting filter areas for full-screen effects
* - Defining hit areas for screen-wide interaction
* - Determining the visible bounds of your application
* @readonly
* @example
* ```js
* // Use as filter area for a full-screen effect
* const blurFilter = new BlurFilter();
* sprite.filterArea = app.screen;
*
* // Use as hit area for screen-wide interaction
* const screenSprite = new Sprite();
* screenSprite.hitArea = app.screen;
*
* // Get screen dimensions
* console.log(app.screen.width, app.screen.height);
* ```
* @see {@link Rectangle} For all available properties and methods
*/
get screen(): Rectangle;
/**
* Destroys the application and all of its resources.
*
* This method should be called when you want to completely
* clean up the application and free all associated memory.
* @param rendererDestroyOptions - Options for destroying the renderer:
* - `false` or `undefined`: Preserves the canvas element (default)
* - `true`: Removes the canvas element
* - `{ removeView: boolean }`: Object with removeView property to control canvas removal
* @param options - Options for destroying the application:
* - `false` or `undefined`: Basic cleanup (default)
* - `true`: Complete cleanup including children
* - Detailed options object:
* - `children`: Remove children
* - `texture`: Destroy textures
* - `textureSource`: Destroy texture sources
* - `context`: Destroy WebGL context
* @example
* ```js
* // Basic cleanup
* app.destroy();
*
* // Remove canvas and do complete cleanup
* app.destroy(true, true);
*
* // Remove canvas with explicit options
* app.destroy({ removeView: true }, true);
*
* // Detailed cleanup with specific options
* app.destroy(
* { removeView: true },
* {
* children: true,
* texture: true,
* textureSource: true,
* context: true
* }
* );
* ```
* > [!WARNING] After calling destroy, the application instance should no longer be used.
* > All properties will be null and further operations will throw errors.
*/
destroy(rendererDestroyOptions?: RendererDestroyOptions, options?: DestroyOptions): void;
}
declare global {
var __PIXI_APP_INIT__: undefined | ((arg: Application | Renderer, version: string) => void);
var __PIXI_RENDERER_INIT__: undefined | ((arg: Application | Renderer, version: string) => void);
}
/**
* Calls global __PIXI_APP_INIT__ hook with the application instance, after the application is initialized.
* @category app
* @internal
*/
export declare class ApplicationInitHook {
/** @ignore */
static extension: ExtensionMetadata;
static init(): void;
static destroy(): void;
}
/**
* Calls global __PIXI_RENDERER_INIT__ hook with the renderer instance, after the renderer is initialized.
* @category rendering
* @internal
*/
export declare class RendererInitHook implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "initHook";
readonly priority: -10;
};
private _renderer;
constructor(renderer: Renderer);
init(): void;
destroy(): void;
}
/** @internal */
export interface BatcherAdaptor {
start(batchPipe: BatcherPipe, geometry: Geometry, shader: Shader): void;
init?(batchPipe: BatcherPipe): void;
execute(batchPipe: BatcherPipe, batch: Batch): void;
contextChange?(): void;
}
/**
* A pipe that batches elements into batches and sends them to the renderer.
*
* You can install new Batchers using ExtensionType.Batcher. Each render group will
* have a default batcher and any required ones will be created on demand.
* @category rendering
* @advanced
*/
export declare class BatcherPipe implements InstructionPipe<Batch>, BatchPipe {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "batch";
};
state: State;
renderer: Renderer;
private readonly _batchersByInstructionSet;
private _adaptor;
/** A record of all active batchers, keyed by their names */
private _activeBatches;
/** The currently active batcher being used to batch elements */
private _activeBatch;
static _availableBatchers: Record<string, new () => Batcher>;
static getBatcher(name: string): Batcher;
constructor(renderer: Renderer, adaptor: BatcherAdaptor);
buildStart(instructionSet: InstructionSet): void;
addToBatch(batchableObject: BatchableElement, instructionSet: InstructionSet): void;
break(instructionSet: InstructionSet): void;
buildEnd(instructionSet: InstructionSet): void;
upload(instructionSet: InstructionSet): void;
execute(batch: Batch): void;
destroy(): void;
}
/**
* The filter pipeline is responsible for applying filters scene items!
*
* KNOWN BUGS:
* 1. Global bounds calculation is incorrect if it is used when flip flopping filters. The maths can be found below
* eg: filters [noiseFilter, blurFilter] noiseFilter will calculate the global bounds incorrectly.
*
* 2. RenderGroups do not work with filters. This is because the renderGroup matrix is not currently taken into account.
*
* Implementation notes:
* 1. Gotcha - nesting filters that require blending will not work correctly. This creates a chicken and egg problem
* the complexity and performance required to do this is not worth it i feel.. but lets see if others agree!
*
* 2. Filters are designed to be changed on the fly, this is means that changing filter information each frame will
* not trigger an instruction rebuild. If you are constantly turning a filter on and off.. its therefore better to set
* enabled to true or false on the filter. Or setting an empty array.
*
* 3. Need to look at perhaps aliasing when flip flopping filters. Really we should only need to antialias the FIRST
* Texture we render too. The rest can be non aliased. This might help performance.
* Currently we flip flop with an antialiased texture if antialiasing is enabled on the filter.
* @internal
*/
export interface FilterInstruction extends Instruction {
renderPipeId: "filter";
action: "pushFilter" | "popFilter";
container?: Container;
renderables?: Renderable[];
filterEffect: FilterEffect;
}
/**
* System that manages the filter pipeline
* @category rendering
* @advanced
*/
export declare class FilterSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "filter";
};
readonly renderer: Renderer;
private _filterStackIndex;
private _filterStack;
private readonly _filterGlobalUniforms;
private readonly _globalFilterBindGroup;
private _activeFilterData;
private _passthroughFilter;
constructor(renderer: Renderer);
/**
* The back texture of the currently active filter. Requires the filter to have `blendRequired` set to true.
* @readonly
*/
get activeBackTexture(): Texture | undefined;
/**
* Pushes a filter instruction onto the filter stack.
* @param instruction - The instruction containing the filter effect and container.
* @internal
*/
push(instruction: FilterInstruction): void;
/**
* Applies filters to a texture.
*
* This method takes a texture and a list of filters, applies the filters to the texture,
* and returns the resulting texture.
* @param {object} params - The parameters for applying filters.
* @param {Texture} params.texture - The texture to apply filters to.
* @param {Filter[]} params.filters - The filters to apply.
* @returns {Texture} The resulting texture after all filters have been applied.
* @example
*
* ```ts
* // Create a texture and a list of filters
* const texture = new Texture(...);
* const filters = [new BlurFilter(), new ColorMatrixFilter()];
*
* // Apply the filters to the texture
* const resultTexture = filterSystem.applyToTexture({ texture, filters });
*
* // Use the resulting texture
* sprite.texture = resultTexture;
* ```
*
* Key Points:
* 1. padding is not currently supported here - so clipping may occur with filters that use padding.
* 2. If all filters are disabled or skipped, the original texture is returned.
*/
generateFilteredTexture({ texture, filters }: {
texture: Texture;
filters: Filter[];
}): Texture;
/** @internal */
pop(): void;
/**
* Copies the last render surface to a texture.
* @param lastRenderSurface - The last render surface to copy from.
* @param bounds - The bounds of the area to copy.
* @param previousBounds - The previous bounds to use for offsetting the copy.
*/
getBackTexture(lastRenderSurface: RenderTarget, bounds: Bounds, previousBounds?: Bounds): Texture<TextureSource<any>>;
/**
* Applies a filter to a texture.
* @param filter - The filter to apply.
* @param input - The input texture.
* @param output - The output render surface.
* @param clear - Whether to clear the output surface before applying the filter.
*/
applyFilter(filter: Filter, input: Texture, output: RenderSurface, clear: boolean): void;
/**
* Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
*
* Use `outputMatrix * vTextureCoord` in the shader.
* @param outputMatrix - The matrix to output to.
* @param {Sprite} sprite - The sprite to map to.
* @returns The mapped matrix.
*/
calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix;
destroy(): void;
private _getPassthroughFilter;
/**
* Sets up the bind groups and renders the filter.
* @param filter - The filter to apply
* @param input - The input texture
* @param renderer - The renderer instance
*/
private _setupBindGroupsAndRender;
/**
* Sets up the filter textures including input texture and back texture if needed.
* @param filterData - The filter data to update
* @param bounds - The bounds for the texture
* @param renderer - The renderer instance
* @param previousFilterData - The previous filter data for back texture calculation
*/
private _setupFilterTextures;
/**
* Calculates and sets the global frame for the filter.
* @param filterData - The filter data to update
* @param offsetX - The X offset
* @param offsetY - The Y offset
* @param globalResolution - The global resolution
* @param sourceWidth - The source texture width
* @param sourceHeight - The source texture height
*/
private _calculateGlobalFrame;
/**
* Updates the filter uniforms with the current filter state.
* @param input - The input texture
* @param output - The output render surface
* @param filterData - The current filter data
* @param offsetX - The X offset for positioning
* @param offsetY - The Y offset for positioning
* @param resolution - The current resolution
* @param isFinalTarget - Whether this is the final render target
* @param clear - Whether to clear the output surface
*/
private _updateFilterUniforms;
/**
* Finds the correct resolution by looking back through the filter stack.
* @param rootResolution - The fallback root resolution to use
* @returns The resolution from the previous filter or root resolution
*/
private _findFilterResolution;
/**
* Finds the offset from the previous non-skipped filter in the stack.
* @returns The offset coordinates from the previous filter
*/
private _findPreviousFilterOffset;
/**
* Calculates the filter area bounds based on the instruction type.
* @param instruction - The filter instruction
* @param bounds - The bounds object to populate
*/
private _calculateFilterArea;
private _applyFiltersToTexture;
private _calculateFilterBounds;
private _popFilterData;
private _getPreviousFilterData;
private _pushFilterData;
}
/**
* The options to use when creating a new filter.
* @category filters
* @advanced
*/
export interface FilterOptions {
/** optional blend mode used by the filter when rendering (defaults to 'normal') */
blendMode?: BLEND_MODES;
/**
* the resolution the filter should be rendered at. The lower the resolution, the more performant
* the filter will be, but the lower the quality of the output. (default 1)
* If 'inherit', the resolution of the render target is used.
* Consider lowering this for things like blurs filters
*/
resolution?: number | "inherit";
/**
* the amount of pixels to pad the container with when applying the filter. For example a blur extends the
* container out as it blurs, so padding is applied to ensure that extra detail is rendered as well
* without clipping occurring. (default 0)
*/
padding?: number;
/**
* If true the filter will make use of antialiasing. Although it looks better this can have a performance impact.
* If set to 'inherit', the filter will detect the antialiasing of the render target and change this automatically.
* Definitely don't set this to true if the render target has antialiasing set to false. As it will antialias,
* but you won't see the difference. (default 'off')
*
* This can be a boolean or [FilterAntialias]{@link FilterAntialias} string.
*/
antialias?: FilterAntialias | boolean;
/**
* If this is set to true, the filter system will grab a snap shot of the area being rendered
* to and pass this into the shader. This is useful for blend modes that need to be aware of the pixels
* they are rendering to. Only use if you need that data, otherwise its an extra gpu copy you don't need!
* (default false)
*
* If given, the shader should have a uniform named `uBackTexture`, which is where the pixels of the
* area being rendered to can be sampled from.
*/
blendRequired?: boolean;
/**
* If this is set to true, the filter system will clip filter texture into viewport
* This is useful for filters that applied to whole texture.
* (default true)
*/
clipToViewport?: boolean;
}
/**
* Filter options mixed with shader resources. A filter needs a shader and some resources to work.
* @category filters
* @advanced
* @see {@link FilterOptions}
*/
export type FilterWithShader = FilterOptions & IShaderWithResources;
/**
* The antialiasing mode of the filter. This can be either:
* - `on` - the filter is always antialiased regardless of the render target settings
* - `off` - (default) the filter is never antialiased regardless of the render target settings
* - `inherit` - the filter uses the antialias settings of the render target
* @category filters
* @advanced
*/
export type FilterAntialias = "on" | "off" | "inherit";
/**
* The Filter class is the base for all filter effects used in Pixi.js
* As it extends a shader, it requires that a glProgram is parsed in to work with WebGL and a gpuProgram for WebGPU.
* If you don't proved one, then the filter is skipped and just rendered as if it wasn't there for that renderer.
*
* A filter can be applied to anything that extends Container in Pixi.js which also includes Sprites, Graphics etc.
*
* Its worth noting Performance-wise filters can be pretty expensive if used too much in a single scene.
* The following happens under the hood when a filter is applied:
*
* .1. Break the current batch
* <br>
* .2. The target is measured using getGlobalBounds
* (recursively go through all children and figure out how big the object is)
* <br>
* .3. Get the closest Po2 Textures from the texture pool
* <br>
* .4. Render the target to that texture
* <br>
* .5. Render that texture back to the main frame buffer as a quad using the filters program.
* <br>
* <br>
* Some filters (such as blur) require multiple passes too which can result in an even bigger performance hit. So be careful!
* Its not generally the complexity of the shader that is the bottle neck,
* but all the framebuffer / shader switching that has to take place.
* One filter applied to a container with many objects is MUCH faster than many filter applied to many objects.
* @category filters
* @advanced
* @example
* import { Filter } from 'pixi.js';
*
* const customFilter = new Filter({
* glProgram: new GlProgram({
* fragment,
* vertex,
* }),
* resources: {
* timeUniforms: {
* uTime: { value: 0.0, type: 'f32' },
* },
* },
* });
*
* // Apply the filter
* sprite.filters = [customFilter];
*
* // Update uniform
* app.ticker.add((ticker) => {
* filter.resources.timeUniforms.uniforms.uTime += 0.04 * ticker.deltaTime;
* });
*/
export declare class Filter extends Shader {
/** The default filter settings */
static defaultOptions: FilterOptions;
/**
* The padding of the filter. Some filters require extra space to breath such as a blur.
* Increasing this will add extra width and height to the bounds of the object that the
* filter is applied to.
* @default 0
*/
padding: number;
/**
* should the filter use antialiasing?
* @default inherit
*/
antialias: FilterAntialias;
/** If enabled is true the filter is applied, if false it will not. */
enabled: boolean;
/**
* The gpu state the filter requires to render.
* @internal
*/
_state: State;
/**
* The resolution of the filter. Setting this to be lower will lower the quality but
* increase the performance of the filter.
* @default 1
*/
resolution: number | "inherit";
/**
* Whether or not this filter requires the previous render texture for blending.
* @default false
*/
blendRequired: boolean;
/**
* Clip texture into viewport or not
* @default true
*/
clipToViewport: boolean;
/**
* @param options - The optional parameters of this filter.
*/
constructor(options: FilterWithShader);
/**
* Applies the filter
* @param filterManager - The renderer to retrieve the filter from
* @param input - The input render target.
* @param output - The target to output to.
* @param clearMode - Should the output be cleared before rendering to it
*/
apply(filterManager: FilterSystem, input: Texture, output: RenderSurface, clearMode: boolean): void;
/**
* Get the blend mode of the filter.
* @default "normal"
*/
get blendMode(): BLEND_MODES;
/** Sets the blend mode of the filter. */
set blendMode(value: BLEND_MODES);
/**
* A short hand function to create a filter based of a vertex and fragment shader src.
* @param options
* @returns A shiny new PixiJS filter!
*/
static from(options: FilterOptions & ShaderFromResources): Filter;
}
/**
* A filter effect is an effect that can be applied to a container that involves applying special pixel effects
* to that container as it is rendered. Used internally when the filters property is modified on a container.
* @internal
*/
export declare class FilterEffect implements Effect {
/** read only filters array - to modify, set it again! */
filters: readonly Filter[];
/**
* If specified, rather than calculating the bounds of the container that the filter
* will apply to, we use this rect instead. This is a local rect - so will have the containers transform
* applied to it
*/
filterArea?: Rectangle;
/** the pipe that knows how to handle this effect */
pipe: string;
/** the priority of this effect */
priority: number;
destroy(): void;
}
/**
* A generic class for managing a pool of items.
* @template T The type of items in the pool. Must implement {@link PoolItem}.
* @category utils
* @advanced
*/
export declare class Pool<T extends PoolItem> {
/** @internal */
readonly _classType: PoolItemConstructor<T>;
private readonly _pool;
private _count;
private _index;
/**
* Constructs a new Pool.
* @param ClassType - The constructor of the items in the pool.
* @param {number} [initialSize] - The initial size of the pool.
*/
constructor(ClassType: PoolItemConstructor<T>, initialSize?: number);
/**
* Prepopulates the pool with a given number of items.
* @param total - The number of items to add to the pool.
*/
prepopulate(total: number): void;
/**
* Gets an item from the pool. Calls the item's `init` method if it exists.
* If there are no items left in the pool, a new one will be created.
* @param {unknown} [data] - Optional data to pass to the item's constructor.
* @returns {T} The item from the pool.
*/
get(data?: unknown): T;
/**
* Returns an item to the pool. Calls the item's `reset` method if it exists.
* @param {T} item - The item to return to the pool.
*/
return(item: T): void;
/**
* Gets the number of items in the pool.
* @readonly
*/
get totalSize(): number;
/**
* Gets the number of items in the pool that are free to use without needing to create more.
* @readonly
*/
get totalFree(): number;
/**
* Gets the number of items in the pool that are currently in use.
* @readonly
*/
get totalUsed(): number;
/** clears the pool */
clear(): void;
}
/**
* An object that can be stored in a {@link Pool}.
* @category utils
* @advanced
*/
export type PoolItem = {
init?: (data?: any) => void;
reset?: () => void;
destroy?: () => void;
[key: string]: any;
};
/**
* The constructor of an object that can be stored in a {@link Pool}.
* @typeParam K - The type of the object that can be stored in a {@link Pool}.
* @category utils
* @advanced
*/
export type PoolItemConstructor<K extends PoolItem> = new () => K;
/**
* AlphaMask is an effect that applies a mask to a container using the alpha channel of a sprite.
* It can be used to create complex masking effects by using a sprite as the mask.
* The mask can be inverted, and it can render the mask to a texture if the mask is not a sprite.
* @category rendering
* @advanced
*/
export declare class AlphaMask implements Effect, PoolItem {
static extension: ExtensionMetadata;
priority: number;
mask: Container;
inverse: boolean;
pipe: string;
renderMaskToTexture: boolean;
constructor(options?: {
mask: Container;
});
init(mask: Container): void;
reset(): void;
addBounds(bounds: Bounds, skipUpdateTransform?: boolean): void;
addLocalBounds(bounds: Bounds, localRoot: Container): void;
containsPoint(point: Point, hitTestFn: (container: Container, point: Point) => boolean): boolean;
destroy(): void;
static test(mask: any): boolean;
}
type MaskMode = "pushMaskBegin" | "pushMaskEnd" | "popMaskBegin" | "popMaskEnd";
declare class AlphaMaskEffect extends FilterEffect implements PoolItem {
constructor();
get sprite(): Sprite;
set sprite(value: Sprite);
get inverse(): boolean;
set inverse(value: boolean);
init: () => void;
}
/** @internal */
export interface AlphaMaskInstruction extends Instruction {
renderPipeId: "alphaMask";
action: MaskMode;
mask: AlphaMask;
inverse: boolean;
maskedContainer: Container;
renderMask: boolean;
}
/** @internal */
export interface AlphaMaskData {
filterEffect: AlphaMaskEffect;
maskedContainer: Container;
previousRenderTarget?: RenderTarget;
filterTexture?: Texture;
}
/** @internal */
export declare class AlphaMaskPipe implements InstructionPipe<AlphaMaskInstruction> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "alphaMask";
};
private _renderer;
private _activeMaskStage;
constructor(renderer: Renderer);
push(mask: Effect, maskedContainer: Container, instructionSet: InstructionSet): void;
pop(mask: Effect, _maskedContainer: Container, instructionSet: InstructionSet): void;
execute(instruction: AlphaMaskInstruction): void;
destroy(): void;
}
/** @internal */
export interface ColorMaskInstruction extends Instruction {
renderPipeId: "colorMask";
colorMask: number;
}
/** @internal */
export declare class ColorMaskPipe implements InstructionPipe<ColorMaskInstruction> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "colorMask";
};
private readonly _renderer;
private _colorStack;
private _colorStackIndex;
private _currentColor;
constructor(renderer: Renderer);
buildStart(): void;
push(mask: Effect, _container: Container, instructionSet: InstructionSet): void;
pop(_mask: Effect, _container: Container, instructionSet: InstructionSet): void;
execute(instruction: ColorMaskInstruction): void;
destroy(): void;
}
/**
* A mask that uses the stencil buffer to clip the rendering of a container.
* This is useful for complex masks that cannot be achieved with simple shapes.
* It is more performant than using a `Graphics` mask, but requires WebGL support.
* It is also useful for masking with `Container` objects that have complex shapes.
* @category rendering
* @advanced
*/
export declare class StencilMask implements Effect, PoolItem {
static extension: ExtensionMetadata;
priority: number;
mask: Container;
pipe: string;
constructor(options: {
mask: Container;
});
init(mask: Container): void;
reset(): void;
addBounds(bounds: Bounds, skipUpdateTransform: boolean): void;
addLocalBounds(bounds: Bounds, localRoot: Container): void;
containsPoint(point: Point, hitTestFn: (container: Container, point: Point) => boolean): boolean;
destroy(): void;
static test(mask: any): boolean;
}
type MaskMode$1 = "pushMaskBegin" | "pushMaskEnd" | "popMaskBegin" | "popMaskEnd";
/** @internal */
export interface StencilMaskInstruction extends Instruction {
renderPipeId: "stencilMask";
action: MaskMode$1;
inverse: boolean;
mask: StencilMask;
}
/** @internal */
export declare class StencilMaskPipe implements InstructionPipe<StencilMaskInstruction> {
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "stencilMask";
};
private _renderer;
private _maskStackHash;
private _maskHash;
constructor(renderer: Renderer);
push(mask: Effect, _container: Container, instructionSet: InstructionSet): void;
pop(mask: Effect, _container: Container, instructionSet: InstructionSet): void;
execute(instruction: StencilMaskInstruction): void;
destroy(): void;
}
interface AdvancedBlendInstruction extends Instruction {
renderPipeId: "blendMode";
blendMode: BLEND_MODES;
activeBlend: Renderable[];
}
/**
* This Pipe handles the blend mode switching of the renderer.
* It will insert instructions into the {@link InstructionSet} to switch the blend mode according to the
* blend modes of the scene graph.
*
* This pipe is were wwe handle Advanced blend modes. Advanced blend modes essentially wrap the renderables
* in a filter that applies the blend mode.
*
* You only need to use this class if you are building your own render instruction set rather than letting PixiJS build
* the instruction set for you by traversing the scene graph
* @category rendering
* @internal
*/
export declare class BlendModePipe implements InstructionPipe<AdvancedBlendInstruction> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "blendMode";
};
private _renderer;
private _renderableList?;
private _activeBlendMode;
private readonly _blendModeStack;
private _isAdvanced;
private _filterHash;
constructor(renderer: Renderer);
prerender(): void;
/**
* Push a blend mode onto the internal stack and apply it to the instruction set if needed.
* @param renderable - The renderable or {@link RenderGroup} associated with the change.
* @param blendMode - The blend mode to activate.
* @param instructionSet - The instruction set being built.
*/
pushBlendMode(renderable: Renderable | RenderGroup, blendMode: BLEND_MODES, instructionSet: InstructionSet): void;
/**
* Pop the last blend mode from the stack and apply the new top-of-stack mode.
* @param instructionSet - The instruction set being built.
*/
popBlendMode(instructionSet: InstructionSet): void;
/**
* Ensure a blend mode switch is added to the instruction set when the mode changes.
* If an advanced blend mode is active, subsequent renderables will be collected so they can be
* rendered within a single filter pass.
* @param renderable - The renderable or {@link RenderGroup} to associate with the change, or null when unwinding.
* @param blendMode - The target blend mode.
* @param instructionSet - The instruction set being built.
*/
setBlendMode(renderable: Renderable | RenderGroup | null, blendMode: BLEND_MODES, instructionSet: InstructionSet): void;
private _beginAdvancedBlendMode;
private _ensureFilterEffect;
private _endAdvancedBlendMode;
/**
* called when the instruction build process is starting this will reset internally to the default blend mode
* @internal
*/
buildStart(): void;
/**
* called when the instruction build process is finished, ensuring that if there is an advanced blend mode
* active, we add the final render instructions added to the instruction set
* @param instructionSet - The instruction set we are adding to
* @internal
*/
buildEnd(instructionSet: InstructionSet): void;
/** @internal */
destroy(): void;
}
declare const imageTypes: {
png: string;
jpg: string;
webp: string;
};
type Formats = keyof typeof imageTypes;
/**
* Options for creating an image from a renderer.
* Controls the output format and quality of extracted images.
* @example
* ```ts
* // Extract as PNG (default)
* const pngImage = await renderer.extract.image({
* target: sprite,
* format: 'png'
* });
*
* // Extract as JPEG with quality setting
* const jpgImage = await renderer.extract.image({
* target: sprite,
* format: 'jpg',
* quality: 0.8
* });
*
* // Extract as WebP for better compression
* const webpImage = await renderer.extract.image({
* target: sprite,
* format: 'webp',
* quality: 0.9
* });
* ```
* @category rendering
* @advanced
*/
export interface ImageOptions {
/**
* The format of the extracted image.
* - 'png': Lossless format, best for images with text or sharp edges
* - 'jpg': Lossy format, smaller file size, good for photos
* - 'webp': Modern format with better compression
* @example
* ```ts
* // Extract as PNG
* const pngImage = await renderer.extract.image({
* target: sprite,
* format: 'png'
* });
* // Extract as JPEG
* const jpgImage = await renderer.extract.image({
* target: sprite,
* format: 'jpg',
* });
* ```
* @default 'png'
*/
format?: Formats;
/**
* The quality of the extracted image, between 0 and 1.
* Only applies to lossy formats (jpg, webp).
* - 1: Maximum quality
* - 0: Maximum compression
* @example
* ```ts
* // Extract as JPEG with 80% quality
* const jpgImage = await renderer.extract.image({
* target: sprite,
* format: 'jpg',
* quality: 0.8
* });
* // Extract as WebP with 90% quality
* const webpImage = await renderer.extract.image({
* target: sprite,
* format: 'webp',
* quality: 0.9
* });
* ```
* @default 1
*/
quality?: number;
}
/**
* Options for extracting content from a renderer.
* These options control how content is extracted and processed from the renderer.
* @example
* ```ts
* // Basic extraction
* const pixels = renderer.extract.pixels({
* target: sprite,
* });
*
* // Extract with custom region and resolution
* const canvas = renderer.extract.canvas({
* target: container,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2,
* });
*
* // Extract with background color and anti-aliasing
* const image = await renderer.extract.image({
* target: graphics,
* clearColor: '#ff0000',
* antialias: true
* });
* ```
* @category rendering
* @advanced
*/
export interface BaseExtractOptions {
/**
* The target to extract. Can be a Container or Texture.
* @example
* ```ts
* // Extract from a sprite
* const sprite = new Sprite(texture);
* renderer.extract.pixels({ target: sprite });
*
* // Extract from a texture directly
* renderer.extract.pixels({ target: texture });
* ```
*/
target: Container | Texture;
/**
* The region of the target to extract. If not specified, extracts the entire target.
* @example
* ```ts
* // Extract a specific region
* renderer.extract.canvas({
* target: sprite,
* frame: new Rectangle(10, 10, 100, 100)
* });
* ```
*/
frame?: Rectangle;
/**
* The resolution of the extracted content. Higher values create sharper images.
* @default 1
* @example
* ```ts
* // Extract at 2x resolution for retina displays
* renderer.extract.image({
* target: sprite,
* resolution: 2
* });
* ```
*/
resolution?: number;
/**
* The color used to clear the extracted content before rendering.
* Can be a hex number, string, or array of numbers.
* @example
* ```ts
* // Clear with red background
* renderer.extract.canvas({
* target: sprite,
* clearColor: '#ff0000'
* });
*
* // Clear with semi-transparent black
* renderer.extract.canvas({
* target: sprite,
* clearColor: [0, 0, 0, 0.5]
* });
* ```
*/
clearColor?: ColorSource;
/**
* Whether to enable anti-aliasing during extraction.
* Improves quality but may affect performance.
* @default false
* @example
* ```ts
* // Enable anti-aliasing for smoother edges
* renderer.extract.image({
* target: graphics,
* antialias: true
* });
* ```
*/
antialias?: boolean;
}
/**
* Options for extracting an HTMLImage from the renderer.
* Combines base extraction options with image-specific settings.
* @example
* ```ts
* // Basic PNG extraction
* const image = await renderer.extract.image({
* target: sprite,
* format: 'png'
* });
*
* // High-quality JPEG with custom region
* const image = await renderer.extract.image({
* target: container,
* format: 'jpg',
* quality: 0.9,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2
* });
*
* // WebP with background and anti-aliasing
* const image = await renderer.extract.image({
* target: graphics,
* format: 'webp',
* quality: 0.8,
* clearColor: '#ff0000',
* antialias: true
* });
* ```
*
* Combines all options from:
* - {@link BaseExtractOptions} for basic extraction settings
* - {@link ImageOptions} for image format and quality settings
*
* Common use cases:
* - Capturing game screenshots
* - Saving rendered content
* - Creating image thumbnails
* - Exporting canvas content
* @see {@link ExtractSystem.image} For the method that uses these options
* @see {@link ExtractSystem.base64} For base64 encoding
* @category rendering
* @advanced
* @interface
*/
export type ExtractImageOptions = BaseExtractOptions & ImageOptions;
/**
* Options for extracting and downloading content from a renderer.
* Combines base extraction options with download-specific settings.
* @example
* ```ts
* // Basic download with default filename
* renderer.extract.download({
* target: sprite
* });
*
* // Download with custom filename and region
* renderer.extract.download({
* target: container,
* filename: 'screenshot.png',
* frame: new Rectangle(0, 0, 100, 100)
* });
*
* // Download with high resolution and background
* renderer.extract.download({
* target: stage,
* filename: 'hd-capture.png',
* resolution: 2,
* clearColor: '#ff0000'
* });
*
* // Download with anti-aliasing
* renderer.extract.download({
* target: graphics,
* filename: 'smooth.png',
* antialias: true
* });
* ```
*
* Combines all options from:
* - {@link BaseExtractOptions} for basic extraction settings
* - Additional download-specific options
*
* Common use cases:
* - Saving game screenshots
* - Exporting rendered content
* - Creating downloadable assets
* - Saving canvas state
* @see {@link ExtractSystem.download} For the method that uses these options
* @see {@link ExtractSystem.image} For creating images without download
* @category rendering
* @advanced
* @interface
*/
export type ExtractDownloadOptions = BaseExtractOptions & {
/**
* The filename to use when downloading the content.
* Should include the desired file extension (e.g., .png).
* @default 'image.png'
* @example
* ```ts
* renderer.extract.download({
* target: sprite,
* filename: 'my-screenshot.png'
* });
* ```
*/
filename: string;
};
/**
* Options for extracting content from a renderer. Represents a union of all possible extraction option types.
* Used by various extraction methods to support different output formats and configurations.
* @example
* ```ts
* // Basic canvas extraction
* const canvas = renderer.extract.canvas({
* target: sprite
* });
*
* // Image extraction with format
* const image = await renderer.extract.image({
* target: sprite,
* format: 'png',
* quality: 1
* });
*
* // Download with filename
* renderer.extract.download({
* target: sprite,
* filename: 'screenshot.png'
* });
*
* // Advanced extraction with multiple options
* const image = await renderer.extract.image({
* target: container,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2,
* clearColor: '#ff0000',
* antialias: true,
* format: 'webp',
* quality: 0.8
* });
* ```
*
* Supports three types of options:
* - {@link BaseExtractOptions} - Basic extraction settings
* - {@link ExtractImageOptions} - Image-specific settings with format and quality
* - {@link ExtractDownloadOptions} - Download settings with filename
*
* Common use cases:
* - Extracting raw pixels
* - Creating canvas elements
* - Generating downloadable images
* - Taking screenshots
* - Creating thumbnails
* @see {@link ExtractSystem.canvas} For canvas extraction
* @see {@link ExtractSystem.image} For image extraction
* @see {@link ExtractSystem.download} For downloading content
* @category rendering
* @advanced
*/
export type ExtractOptions = BaseExtractOptions | ExtractImageOptions | ExtractDownloadOptions;
/**
* System for exporting content from a renderer. It provides methods to extract content as images,
* canvases, or raw pixel data. Available through `renderer.extract`.
* @example
* ```ts
* import { Application, Graphics } from 'pixi.js';
*
* // Create a new application
* const app = new Application();
* await app.init();
*
* // Draw something to extract
* const graphics = new Graphics()
* .circle(0, 0, 50)
* .fill(0xFF0000);
*
* // Basic extraction examples
* const image = await app.renderer.extract.image(graphics); // As IImage (HTMLImageElement)
* const canvas = app.renderer.extract.canvas(graphics); // As Canvas
* const pixels = app.renderer.extract.pixels(graphics); // As pixel data
* const base64 = await app.renderer.extract.base64(graphics); // As base64 string
*
* // Advanced extraction with options
* const customImage = await app.renderer.extract.image({
* target: graphics,
* format: 'png',
* resolution: 2,
* frame: new Rectangle(0, 0, 100, 100),
* clearColor: '#00000000'
* });
*
* // Download content
* app.renderer.extract.download({
* target: graphics,
* filename: 'my-image.png'
* });
*
* // Debug visualization
* app.renderer.extract.log(graphics);
* ```
*
* Features:
* - Extract as various formats (PNG, JPEG, WebP)
* - Control output quality and resolution
* - Extract specific regions
* - Download extracted content
* - Debug visualization
*
* Common Use Cases:
* - Creating thumbnails
* - Saving game screenshots
* - Processing visual content
* - Debugging renders
* - Creating textures from rendered content
*
* Performance Considerations:
* - Extraction operations are relatively expensive
* - Consider caching results for frequently used content
* - Be mindful of resolution and format choices
* - Large extractions may impact performance
* @category rendering
* @standard
*/
export declare class ExtractSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "extract";
};
/**
* Default options for image extraction.
* @example
* ```ts
* // Customize default options
* ExtractSystem.defaultImageOptions.format = 'webp';
* ExtractSystem.defaultImageOptions.quality = 0.8;
*
* // Use defaults
* const image = await renderer.extract.image(sprite);
* ```
*/
static defaultImageOptions: ImageOptions;
private _renderer;
/** @param renderer - The renderer this System works for. */
constructor(renderer: Renderer);
private _normalizeOptions;
/**
* Creates an IImage from a display object or texture.
* @param options - Options for creating the image, or the target to extract
* @returns Promise that resolves with the generated IImage
* @example
* ```ts
* // Basic usage with a sprite
* const sprite = new Sprite(texture);
* const image = await renderer.extract.image(sprite);
* document.body.appendChild(image);
*
* // Advanced usage with options
* const image = await renderer.extract.image({
* target: container,
* format: 'webp',
* quality: 0.8,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2,
* clearColor: '#ff0000',
* antialias: true
* });
*
* // Extract directly from a texture
* const texture = Texture.from('myTexture.png');
* const image = await renderer.extract.image(texture);
* ```
* @see {@link ExtractImageOptions} For detailed options
* @see {@link ExtractSystem.base64} For base64 string output
* @see {@link ExtractSystem.canvas} For canvas output
* @see {@link ImageLike} For the image interface
* @category rendering
*/
image(options: ExtractImageOptions | Container | Texture): Promise<ImageLike>;
/**
* Converts the target into a base64 encoded string.
*
* This method works by first creating
* a canvas using `Extract.canvas` and then converting it to a base64 string.
* @param options - The options for creating the base64 string, or the target to extract
* @returns Promise that resolves with the base64 encoded string
* @example
* ```ts
* // Basic usage with a sprite
* const sprite = new Sprite(texture);
* const base64 = await renderer.extract.base64(sprite);
* console.log(base64); // data:image/png;base64,...
*
* // Advanced usage with options
* const base64 = await renderer.extract.base64({
* target: container,
* format: 'webp',
* quality: 0.8,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2
* });
* ```
* @throws Will throw an error if the platform doesn't support any of:
* - ICanvas.toDataURL
* - ICanvas.toBlob
* - ICanvas.convertToBlob
* @see {@link ExtractImageOptions} For detailed options
* @see {@link ExtractSystem.canvas} For canvas output
* @see {@link ExtractSystem.image} For HTMLImage output
* @category rendering
*/
base64(options: ExtractImageOptions | Container | Texture): Promise<string>;
/**
* Creates a Canvas element, renders the target to it and returns it.
* This method is useful for creating static images or when you need direct canvas access.
* @param options - The options for creating the canvas, or the target to extract
* @returns A Canvas element with the texture rendered on
* @example
* ```ts
* // Basic canvas extraction from a sprite
* const sprite = new Sprite(texture);
* const canvas = renderer.extract.canvas(sprite);
* document.body.appendChild(canvas);
*
* // Extract with custom region
* const canvas = renderer.extract.canvas({
* target: container,
* frame: new Rectangle(0, 0, 100, 100)
* });
*
* // Extract with high resolution
* const canvas = renderer.extract.canvas({
* target: sprite,
* resolution: 2,
* clearColor: '#ff0000'
* });
*
* // Extract directly from a texture
* const texture = Texture.from('myTexture.png');
* const canvas = renderer.extract.canvas(texture);
*
* // Extract with anti-aliasing
* const canvas = renderer.extract.canvas({
* target: graphics,
* antialias: true
* });
* ```
* @see {@link ExtractOptions} For detailed options
* @see {@link ExtractSystem.image} For HTMLImage output
* @see {@link ExtractSystem.pixels} For raw pixel data
* @category rendering
*/
canvas(options: ExtractOptions | Container | Texture): ICanvas;
/**
* Returns a one-dimensional array containing the pixel data of the entire texture in RGBA order,
* with integer values between 0 and 255 (inclusive).
* > [!NOE] The returned array is a flat Uint8Array where every 4 values represent RGBA
* @param options - The options for extracting the image, or the target to extract
* @returns One-dimensional Uint8Array containing the pixel data in RGBA format
* @example
* ```ts
* // Basic pixel extraction
* const sprite = new Sprite(texture);
* const pixels = renderer.extract.pixels(sprite);
* console.log(pixels[0], pixels[1], pixels[2], pixels[3]); // R,G,B,A values
*
* // Extract with custom region
* const pixels = renderer.extract.pixels({
* target: sprite,
* frame: new Rectangle(0, 0, 100, 100)
* });
*
* // Extract with high resolution
* const pixels = renderer.extract.pixels({
* target: sprite,
* resolution: 2
* });
* ```
* @see {@link ExtractOptions} For detailed options
* @see {@link ExtractSystem.canvas} For canvas output
* @see {@link ExtractSystem.image} For image output
* @category rendering
*/
pixels(options: ExtractOptions | Container | Texture): GetPixelsOutput;
/**
* Creates a texture from a display object or existing texture.
*
* This is useful for creating
* reusable textures from rendered content or making copies of existing textures.
* > [!NOTE] The returned texture should be destroyed when no longer needed
* @param options - The options for creating the texture, or the target to extract
* @returns A new texture containing the extracted content
* @example
* ```ts
* // Basic texture extraction from a sprite
* const sprite = new Sprite(texture);
* const extractedTexture = renderer.extract.texture(sprite);
*
* // Extract with custom region
* const regionTexture = renderer.extract.texture({
* target: container,
* frame: new Rectangle(0, 0, 100, 100)
* });
*
* // Extract with high resolution
* const hiResTexture = renderer.extract.texture({
* target: sprite,
* resolution: 2,
* clearColor: '#ff0000'
* });
*
* // Create a new sprite from extracted texture
* const newSprite = new Sprite(
* renderer.extract.texture({
* target: graphics,
* antialias: true
* })
* );
*
* // Clean up when done
* extractedTexture.destroy(true);
* ```
* @see {@link ExtractOptions} For detailed options
* @see {@link Texture} For texture management
* @see {@link GenerateTextureSystem} For texture generation
* @category rendering
*/
texture(options: ExtractOptions | Container | Texture): Texture;
/**
* Extracts and downloads content from the renderer as an image file.
* This is a convenient way to save screenshots or export rendered content.
* > [!NOTE] The download will use PNG format regardless of the filename extension
* @param options - The options for downloading and extracting the image, or the target to extract
* @example
* ```ts
* // Basic download with default filename
* const sprite = new Sprite(texture);
* renderer.extract.download(sprite); // Downloads as 'image.png'
*
* // Download with custom filename
* renderer.extract.download({
* target: sprite,
* filename: 'screenshot.png'
* });
*
* // Download with custom region
* renderer.extract.download({
* target: container,
* filename: 'region.png',
* frame: new Rectangle(0, 0, 100, 100)
* });
*
* // Download with high resolution and background
* renderer.extract.download({
* target: stage,
* filename: 'hd-screenshot.png',
* resolution: 2,
* clearColor: '#ff0000'
* });
*
* // Download with anti-aliasing
* renderer.extract.download({
* target: graphics,
* filename: 'smooth.png',
* antialias: true
* });
* ```
* @see {@link ExtractDownloadOptions} For detailed options
* @see {@link ExtractSystem.image} For creating images without download
* @see {@link ExtractSystem.canvas} For canvas output
* @category rendering
*/
download(options: ExtractDownloadOptions | Container | Texture): void;
/**
* Logs the target to the console as an image. This is a useful way to debug what's happening in the renderer.
* The image will be displayed in the browser's console using CSS background images.
* @param options - The options for logging the image, or the target to log
* @param options.width - The width of the logged image preview in the console (in pixels)
* @example
* ```ts
* // Basic usage
* const sprite = new Sprite(texture);
* renderer.extract.log(sprite);
* ```
* @see {@link ExtractSystem.canvas} For getting raw canvas output
* @see {@link ExtractSystem.pixels} For raw pixel data
* @category rendering
* @advanced
*/
log(options: (ExtractOptions & {
width?: number;
}) | Container | Texture): void;
destroy(): void;
}
/**
* A BatcherAdaptor that uses WebGL to render batches.
* @category rendering
* @ignore
*/
export declare class GlBatchAdaptor implements BatcherAdaptor {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipesAdaptor
];
readonly name: "batch";
};
private readonly _tempState;
/**
* We only want to sync the a batched shaders uniforms once on first use
* this is a hash of shader uids to a boolean value. When the shader is first bound
* we set the value to true. When the shader is bound again we check the value and
* if it is true we know that the uniforms have already been synced and we skip it.
*/
private _didUploadHash;
init(batcherPipe: BatcherPipe): void;
contextChange(): void;
start(batchPipe: BatcherPipe, geometry: Geometry, shader: Shader): void;
execute(batchPipe: BatcherPipe, batch: Batch): void;
}
/**
* @param maxIfs
* @param gl
* @internal
*/
export declare function checkMaxIfStatementsInShader(maxIfs: number, gl: GlRenderingContext): number;
/**
* Returns the maximum number of textures that can be batched. This uses WebGL1's `MAX_TEXTURE_IMAGE_UNITS`.
* The response for this is that to get this info via WebGPU, we would need to make a context, which
* would make this function async, and we want to avoid that.
* @private
* @deprecated Use `Renderer.limits.maxBatchableTextures` instead.
* @returns {number} The maximum number of textures that can be batched
*/
export declare function getMaxTexturesPerBatch(): number;
/**
* @param maxTextures
* @internal
*/
export declare function generateGPULayout(maxTextures: number): GPUBindGroupLayoutEntry[];
/**
* @param maxTextures
* @internal
*/
export declare function generateLayout(maxTextures: number): Record<string, number>;
/**
* @param textures
* @param size
* @param maxTextures
* @internal
*/
export declare function getTextureBatchBindGroup(textures: TextureSource[], size: number, maxTextures: number): BindGroup;
/**
* A BatcherAdaptor that uses the GPU to render batches.
* @category rendering
* @ignore
*/
export declare class GpuBatchAdaptor implements BatcherAdaptor {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUPipesAdaptor
];
readonly name: "batch";
};
private _shader;
private _geometry;
start(batchPipe: BatcherPipe, geometry: Geometry, shader: Shader): void;
execute(batchPipe: BatcherPipe, batch: Batch): void;
}
/**
* the vertex source code, an obj
* @internal
*/
export type Vertex = {
/** stick uniforms and functions in here all headers will be compiled at the top of the shader */
header?: string;
/** code will be added at the start of the shader */
start?: string;
/** code will be run here before lighting happens */
main?: string;
/** code here will to modify anything before it is passed to the fragment shader */
end?: string;
};
/** @internal */
export type Fragment = {
/** stick uniforms and functions in here all headers will be compiled at the top of the shader */
header?: string;
/** code will be added at the start of the shader */
start?: string;
/** code will be run here before lighting happens */
main?: string;
/** code here will to modify anything before it is passed to the fragment shader */
end?: string;
};
/**
* HighShaderBit is a part of a shader.
* it is used to compile HighShaders.
*
* Internally shaders are made up of many of these.
* You can even write your own and compile them in.
* @internal
*/
export interface HighShaderBit {
/** used to make the shader easier to understand! */
name?: string;
/** the snippets of vertex code */
vertex?: Vertex;
/** the snippets of fragment code */
fragment?: Fragment;
}
/**
* source code to compile a shader. this can be directly used by pixi and should be good to go!
* It contains the vertex and fragment source code.
* This is the final output of the HighShader compiler.
* It is used to create a shader program.
* @internal
*/
export interface HighShaderSource {
fragment: string;
vertex: string;
}
/**
* @param root0
* @param root0.bits
* @param root0.name
* @internal
*/
export declare function compileHighShaderGpuProgram({ bits, name }: {
bits: HighShaderBit[];
name: string;
}): GpuProgram;
/**
* @param root0
* @param root0.bits
* @param root0.name
* @internal
*/
export declare function compileHighShaderGlProgram({ bits, name }: {
bits: HighShaderBit[];
name: string;
}): GlProgram;
/**
* A high template consists of vertex and fragment source
* @internal
*/
export interface HighShaderTemplate {
name?: string;
fragment: string;
vertex: string;
}
/** @internal */
export interface CompileHighShaderOptions {
template: HighShaderTemplate;
bits: HighShaderBit[];
}
/**
* This function will take a HighShader template, some High fragments and then merge them in to a shader source.
* @param options
* @param options.template
* @param options.bits
* @internal
*/
export declare function compileHighShader({ template, bits }: CompileHighShaderOptions): HighShaderSource;
/**
* This function will take a HighShader template, some High fragments and then merge them in to a shader source.
* It is specifically for WebGL and does not compile inputs and outputs.
* @param options
* @param options.template - The HighShader template containing vertex and fragment source.
* @param options.bits - An array of HighShaderBit objects to be compiled into the shader.
* @returns A HighShaderSource object containing the compiled vertex and fragment shaders.
* @internal
*/
export declare function compileHighShaderGl({ template, bits }: CompileHighShaderOptions): HighShaderSource;
/**
* takes the HighFragment source parts and adds them to the hook hash
* @param srcParts - the hash of hook arrays
* @param parts - the code to inject into the hooks
* @param name - optional the name of the part to add
* @internal
*/
export declare function addBits(srcParts: Record<string, string>, parts: Record<string, string[]>, name?: string): void;
/**
* takes a program string and returns an hash mapping the hooks to empty arrays
* @param programSrc - the program containing hooks
* @internal
*/
export declare function compileHooks(programSrc: string): Record<string, string[]>;
/**
* @param fragments
* @param template
* @param sort
* @internal
*/
export declare function compileInputs(fragments: any[], template: string, sort?: boolean): string;
/**
* @param fragments
* @param template
* @internal
*/
export declare function compileOutputs(fragments: any[], template: string): string;
/**
* formats a shader so its more pleasant to read
* @param shader - a glsl shader program source
* @category utils
* @advanced
*/
export declare function formatShader(shader: string): string;
/**
* takes a shader src and replaces any hooks with the HighFragment code.
* @param templateSrc - the program src template
* @param fragmentParts - the fragments to inject
* @internal
*/
export declare function injectBits(templateSrc: string, fragmentParts: Record<string, string[]>): string;
/** @ignore */
export declare const vertexGPUTemplate = "\n @in aPosition: vec2<f32>;\n @in aUV: vec2<f32>;\n\n @out @builtin(position) vPosition: vec4<f32>;\n @out vUV : vec2<f32>;\n @out vColor : vec4<f32>;\n\n {{header}}\n\n struct VSOutput {\n {{struct}}\n };\n\n @vertex\n fn main( {{in}} ) -> VSOutput {\n\n var worldTransformMatrix = globalUniforms.uWorldTransformMatrix;\n var modelMatrix = mat3x3<f32>(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0\n );\n var position = aPosition;\n var uv = aUV;\n\n {{start}}\n\n vColor = vec4<f32>(1., 1., 1., 1.);\n\n {{main}}\n\n vUV = uv;\n\n var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix;\n\n vPosition = vec4<f32>((modelViewProjectionMatrix * vec3<f32>(position, 1.0)).xy, 0.0, 1.0);\n\n vColor *= globalUniforms.uWorldColorAlpha;\n\n {{end}}\n\n {{return}}\n };\n";
/** @ignore */
export declare const fragmentGPUTemplate = "\n @in vUV : vec2<f32>;\n @in vColor : vec4<f32>;\n\n {{header}}\n\n @fragment\n fn main(\n {{in}}\n ) -> @location(0) vec4<f32> {\n\n {{start}}\n\n var outColor:vec4<f32>;\n\n {{main}}\n\n var finalColor:vec4<f32> = outColor * vColor;\n\n {{end}}\n\n return finalColor;\n };\n";
/** @ignore */
export declare const vertexGlTemplate = "\n in vec2 aPosition;\n in vec2 aUV;\n\n out vec4 vColor;\n out vec2 vUV;\n\n {{header}}\n\n void main(void){\n\n mat3 worldTransformMatrix = uWorldTransformMatrix;\n mat3 modelMatrix = mat3(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0\n );\n vec2 position = aPosition;\n vec2 uv = aUV;\n\n {{start}}\n\n vColor = vec4(1.);\n\n {{main}}\n\n vUV = uv;\n\n mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix;\n\n gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n\n vColor *= uWorldColorAlpha;\n\n {{end}}\n }\n";
/** @ignore */
export declare const fragmentGlTemplate = "\n\n in vec4 vColor;\n in vec2 vUV;\n\n out vec4 finalColor;\n\n {{header}}\n\n void main(void) {\n\n {{start}}\n\n vec4 outColor;\n\n {{main}}\n\n finalColor = outColor * vColor;\n\n {{end}}\n }\n";
/** @internal */
export declare const colorBit: {
name: string;
vertex: {
header: string;
main: string;
};
};
/** @internal */
export declare const colorBitGl: {
name: string;
vertex: {
header: string;
main: string;
};
};
/**
* @param maxTextures
* @internal
*/
export declare function generateTextureBatchBit(maxTextures: number): HighShaderBit;
/**
* @param maxTextures
* @internal
*/
export declare function generateTextureBatchBitGl(maxTextures: number): HighShaderBit;
/** @internal */
export declare const globalUniformsBit: {
name: string;
vertex: {
header: string;
};
};
/** @internal */
export declare const globalUniformsUBOBitGl: {
name: string;
vertex: {
header: string;
};
};
/** @internal */
export declare const globalUniformsBitGl: {
name: string;
vertex: {
header: string;
};
};
/** @internal */
export declare const localUniformBit: {
name: string;
vertex: {
header: string;
main: string;
end: string;
};
};
/** @internal */
export declare const localUniformBitGroup2: {
vertex: {
header: string;
main: string;
end: string;
};
name: string;
};
/** @internal */
export declare const localUniformBitGl: {
name: string;
vertex: {
header: string;
main: string;
end: string;
};
};
/** @internal */
export declare const roundPixelsBit: {
name: string;
vertex: {
header: string;
};
};
/** @internal */
export declare const roundPixelsBitGl: {
name: string;
vertex: {
header: string;
};
};
/** @internal */
export declare const textureBit: {
name: string;
vertex: {
header: string;
main: string;
};
fragment: {
header: string;
main: string;
};
};
/** @internal */
export declare const textureBitGl: {
name: string;
vertex: {
header: string;
main: string;
};
fragment: {
header: string;
main: string;
};
};
/**
* The ColorMask effect allows you to apply a color mask to the rendering process.
* This can be useful for selectively rendering certain colors or for creating
* effects based on color values.
* @category rendering
* @advanced
*/
export declare class ColorMask implements Effect, PoolItem {
static extension: ExtensionMetadata;
priority: number;
mask: number;
pipe: string;
constructor(options: {
mask: number;
});
init(mask: number): void;
destroy(): void;
static test(mask: any): boolean;
}
interface MaskConversionTest {
test: (item: any) => boolean;
maskClass: new (item: any) => Effect & PoolItem;
}
/**
* Represents a mask effect that can be applied to a container.
* @category rendering
* @advanced
*/
export type MaskEffect = {
mask: unknown;
} & Effect;
/**
* A class that manages the conversion of masks to mask effects.
* @category rendering
* @ignore
*/
export declare class MaskEffectManagerClass {
/** @private */
readonly _effectClasses: EffectConstructor[];
private readonly _tests;
private _initialized;
init(): void;
add(test: MaskConversionTest): void;
getMaskEffect(item: any): MaskEffect;
returnMaskEffect(effect: Effect & PoolItem): void;
}
/**
* A class that manages the conversion of masks to mask effects.
* @class
* @category rendering
* @advanced
*/
export declare const MaskEffectManager: MaskEffectManagerClass;
/**
* ScissorMask is an effect that applies a scissor mask to a container.
* It restricts rendering to the area defined by the mask.
* The mask is a Container that defines the area to be rendered.
* The mask must be a Container that is not renderable or measurable.
* This effect is used to create clipping regions in the rendering process.
* @category rendering
* @advanced
*/
export declare class ScissorMask implements Effect {
priority: number;
mask: Container;
pipe: string;
constructor(mask: Container);
addBounds(bounds: Bounds, skipUpdateTransform?: boolean): void;
addLocalBounds(bounds: Bounds, localRoot: Container): void;
containsPoint(point: Point, hitTestFn: (container: Container, point: Point) => boolean): boolean;
reset(): void;
destroy(): void;
}
/**
* @param mask
* @param bounds
* @param skipUpdateTransform
* @internal
*/
export declare function addMaskBounds(mask: Container, bounds: Bounds, skipUpdateTransform: boolean): void;
/**
* @param mask
* @param bounds
* @param localRoot
* @internal
*/
export declare function addMaskLocalBounds(mask: Container, bounds: Bounds, localRoot: Container): void;
/**
* System plugin to the renderer to manage buffers.
*
* WebGL uses Buffers as a way to store objects to the GPU.
* This system makes working with them a lot easier.
*
* Buffers are used in three main places in WebGL
* - geometry information
* - Uniform information (via uniform buffer objects - a WebGL 2 only feature)
* - Transform feedback information. (WebGL 2 only feature)
*
* This system will handle the binding of buffers to the GPU as well as uploading
* them. With this system, you never need to work directly with GPU buffers, but instead work with
* the Buffer class.
* @class
* @category rendering
* @advanced
*/
export declare class GlBufferSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "buffer";
};
/** @internal */
_gl: GlRenderingContext;
protected _managedBuffers: GCManagedHash<Buffer$1>;
/** Cache keeping track of the base bound buffer bases */
private _boundBufferBases;
private _renderer;
private _minBaseLocation;
private _maxBindings;
private _nextBindBaseIndex;
private _bindCallId;
/**
* @param {Renderer} renderer - The renderer this System works for.
*/
constructor(renderer: WebGLRenderer);
/** @ignore */
destroy(): void;
/** Sets up the renderer context and necessary buffers. */
protected contextChange(): void;
getGlBuffer(buffer: Buffer$1): GlBuffer;
/**
* This binds specified buffer. On first run, it will create the webGL buffers for the context too
* @param buffer - the buffer to bind to the renderer
*/
bind(buffer: Buffer$1): void;
/**
* Binds an uniform buffer to at the given index.
*
* A cache is used so a buffer will not be bound again if already bound.
* @param glBuffer - the buffer to bind
* @param index - the base index to bind it to.
*/
bindBufferBase(glBuffer: GlBuffer, index: number): void;
nextBindBase(hasTransformFeedback: boolean): void;
freeLocationForBufferBase(glBuffer: GlBuffer): number;
getLastBindBaseLocation(glBuffer: GlBuffer): number;
/**
* Binds a buffer whilst also binding its range.
* This will make the buffer start from the offset supplied rather than 0 when it is read.
* @param glBuffer - the buffer to bind
* @param index - the base index to bind at, defaults to 0
* @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc
* @param size - the size to bind at (this is blocks of 256).
*/
bindBufferRange(glBuffer: GlBuffer, index?: number, offset?: number, size?: number): void;
/**
* Will ensure the data in the buffer is uploaded to the GPU.
* @param {Buffer} buffer - the buffer to update
*/
updateBuffer(buffer: Buffer$1): GlBuffer;
/**
* dispose all WebGL resources of all managed buffers
* @param contextLost
*/
destroyAll(contextLost?: boolean): void;
protected onBufferUnload(buffer: Buffer$1, contextLost?: boolean): void;
/**
* creates and attaches a GLBuffer object tied to the current context.
* @param buffer
* @protected
*/
protected createGLBuffer(buffer: Buffer$1): GlBuffer;
resetState(): void;
}
/**
* WebGL extensions for compressed textures using the PVRTC format.
* @category rendering
* @advanced
*/
interface WEBGL_compressed_texture_pvrtc$1 {
COMPRESSED_RGB_PVRTC_4BPPV1_IMG: number;
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: number;
COMPRESSED_RGB_PVRTC_2BPPV1_IMG: number;
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: number;
}
/**
* WebGL extensions for texture compression using the ETC format.
* @category rendering
* @advanced
*/
interface WEBGL_compressed_texture_etc$1 {
COMPRESSED_R11_EAC: number;
COMPRESSED_SIGNED_R11_EAC: number;
COMPRESSED_RG11_EAC: number;
COMPRESSED_SIGNED_RG11_EAC: number;
COMPRESSED_RGB8_ETC2: number;
COMPRESSED_RGBA8_ETC2_EAC: number;
COMPRESSED_SRGB8_ETC2: number;
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: number;
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: number;
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: number;
}
/**
* WebGL extensions for texture compression using the ETC1 format.
* @category rendering
* @advanced
*/
interface WEBGL_compressed_texture_etc1$1 {
COMPRESSED_RGB_ETC1_WEBGL: number;
}
/**
* WebGL extensions for texture compression using the ATC format.
* @category rendering
* @advanced
*/
export interface WEBGL_compressed_texture_atc {
COMPRESSED_RGB_ATC_WEBGL: number;
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: number;
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: number;
}
/**
* WebGL extensions for texture compression using the BPTC format.
* @category rendering
* @advanced
*/
interface EXT_texture_compression_bptc$1 {
COMPRESSED_RGBA_BPTC_UNORM_EXT: number;
COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT: number;
COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT: number;
COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT: number;
}
/**
* WebGL extensions for texture compression using the RGTC format.
* @category rendering
* @advanced
*/
interface EXT_texture_compression_rgtc$1 {
COMPRESSED_RED_RGTC1_EXT: number;
COMPRESSED_SIGNED_RED_RGTC1_EXT: number;
COMPRESSED_RED_GREEN_RGTC2_EXT: number;
COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: number;
}
/**
* WebGL extensions that are available in the current context.
* @category rendering
* @advanced
*/
export interface WebGLExtensions {
drawBuffers?: WEBGL_draw_buffers;
depthTexture?: OES_texture_float;
loseContext?: WEBGL_lose_context;
vertexArrayObject?: OES_vertex_array_object;
anisotropicFiltering?: EXT_texture_filter_anisotropic;
uint32ElementIndex?: OES_element_index_uint;
floatTexture?: OES_texture_float;
floatTextureLinear?: OES_texture_float_linear;
textureHalfFloat?: OES_texture_half_float;
textureHalfFloatLinear?: OES_texture_half_float_linear;
colorBufferFloat?: EXT_color_buffer_float;
vertexAttribDivisorANGLE?: ANGLE_instanced_arrays;
s3tc?: WEBGL_compressed_texture_s3tc;
s3tc_sRGB?: WEBGL_compressed_texture_s3tc_srgb;
etc?: WEBGL_compressed_texture_etc$1;
etc1?: WEBGL_compressed_texture_etc1$1;
pvrtc?: WEBGL_compressed_texture_pvrtc$1;
atc?: WEBGL_compressed_texture_atc;
astc?: WEBGL_compressed_texture_astc;
bptc?: EXT_texture_compression_bptc$1;
rgtc?: EXT_texture_compression_rgtc$1;
srgb?: EXT_sRGB;
}
/**
* Options for the context system.
* @category rendering
* @advanced
* @property {WebGL2RenderingContext | null} [context=null] - User-provided WebGL rendering context object.
* @property {GpuPowerPreference} [powerPreference='default'] - An optional hint indicating what configuration
* of GPU is suitable for the WebGL context, can be `'high-performance'` or `'low-power'`. Setting to `'high-performance'`
* will prioritize rendering performance over power consumption, while setting to `'low-power'` will prioritize power saving
* over rendering performance.
* @property {boolean} [premultipliedAlpha=true] - Whether the compositor will assume the drawing buffer contains
* colors with premultiplied alpha.
* @property {boolean} [preserveDrawingBuffer=false] - Whether to enable drawing buffer preservation.
* If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @property {boolean} [antialias] - Whether to enable antialiasing.
* @property {1 | 2} [preferWebGLVersion=2] - The preferred WebGL version to use.
*/
export interface ContextSystemOptions {
/**
* User-provided WebGL rendering context object.
* @default null
*/
context: WebGL2RenderingContext | null;
/**
* An optional hint indicating what configuration of GPU is suitable for the WebGL context,
* can be `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @default undefined
*/
powerPreference?: GpuPowerPreference;
/**
* Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
* @default true
*/
premultipliedAlpha: boolean;
/**
* Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @default false
*/
preserveDrawingBuffer: boolean;
antialias?: boolean;
/**
* The preferred WebGL version to use.
* @default 2
*/
preferWebGLVersion?: 1 | 2;
/**
* Whether to enable multi-view rendering. Set to true when rendering to multiple
* canvases on the dom.
* @default false
*/
multiView: boolean;
}
/**
* System plugin to the renderer to manage the context
* @category rendering
* @advanced
*/
export declare class GlContextSystem implements System<ContextSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "context";
};
/** The default options for the system. */
static defaultOptions: ContextSystemOptions;
protected CONTEXT_UID: number;
protected gl: WebGL2RenderingContext;
/**
* Features supported by current renderer.
* @type {object}
* @readonly
*/
supports: {
/** Support for 32-bit indices buffer. */
uint32Indices: boolean;
/** Support for UniformBufferObjects */
uniformBufferObject: boolean;
/** Support for VertexArrayObjects */
vertexArrayObject: boolean;
/** Support for SRGB texture format */
srgbTextures: boolean;
/** Support for wrapping modes if a texture is non-power of two */
nonPowOf2wrapping: boolean;
/** Support for MSAA (antialiasing of dynamic textures) */
msaa: boolean;
/** Support for mipmaps if a texture is non-power of two */
nonPowOf2mipmaps: boolean;
};
/**
* Extensions available.
* @type {object}
* @readonly
* @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension
* @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension
* @property {OES_texture_float} floatTexture - WebGL v1 extension
* @property {WEBGL_lose_context} loseContext - WebGL v1 extension
* @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension
* @property {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension
*/
extensions: WebGLExtensions;
webGLVersion: 1 | 2;
/**
* Whether to enable multi-view rendering. Set to true when rendering to multiple
* canvases on the dom.
* @default false
*/
multiView: boolean;
/**
* The canvas that the WebGL Context is rendering to.
* This will be the view canvas. But if multiView is enabled, this canvas will not be attached to the DOM.
* It will be rendered to and then copied to the target canvas.
* @readonly
*/
canvas: ICanvas;
private _renderer;
private _contextLossForced;
/** @param renderer - The renderer this System works for. */
constructor(renderer: WebGLRenderer);
/**
* `true` if the context is lost
* @readonly
*/
get isLost(): boolean;
/**
* Handles the context change event.
* @param {WebGLRenderingContext} gl - New WebGL context.
*/
protected contextChange(gl: WebGL2RenderingContext): void;
init(options: ContextSystemOptions): void;
ensureCanvasSize(targetCanvas: ICanvas): void;
/**
* Initializes the context.
* @protected
* @param {WebGLRenderingContext} gl - WebGL context
*/
protected initFromContext(gl: WebGL2RenderingContext): void;
/**
* Initialize from context options
* @protected
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
* @param preferWebGLVersion
* @param {object} options - context attributes
*/
protected createContext(preferWebGLVersion: 1 | 2, options: WebGLContextAttributes): void;
/** Auto-populate the {@link GlContextSystem.extensions extensions}. */
protected getExtensions(): void;
/**
* Handles a lost webgl context
* @param {WebGLContextEvent} event - The context lost event.
*/
protected handleContextLost(event: WebGLContextEvent): void;
/** Handles a restored webgl context. */
protected handleContextRestored(): void;
destroy(): void;
/**
* this function can be called to force a webGL context loss
* this will release all resources on the GPU.
* Useful if you need to put Pixi to sleep, and save some GPU memory
*
* As soon as render is called - all resources will be created again.
*/
forceContextLoss(): void;
/**
* Validate context.
* @param {WebGLRenderingContext} gl - Render context.
*/
protected validateContext(gl: WebGL2RenderingContext): void;
}
/**
* @param format
* @internal
*/
export declare function getGlTypeFromFormat(format: VertexFormat): number;
/**
* The options for the back buffer system.
* @category rendering
* @property {boolean} [useBackBuffer=false] - if true will use the back buffer where required
* @property {boolean} [antialias=false] - if true will ensure the texture is antialiased
* @advanced
*/
export interface GlBackBufferOptions {
/**
* if true will use the back buffer where required
* @default false
*/
useBackBuffer?: boolean;
/** if true will ensure the texture is antialiased */
antialias?: boolean;
}
/**
* For blend modes you need to know what pixels you are actually drawing to. For this to be possible in WebGL
* we need to render to a texture and then present that texture to the screen. This system manages that process.
*
* As the main scene is rendered to a texture, it means we can sample it and copy its pixels,
* something not possible on the main canvas.
*
* If antialiasing is set to to true and useBackBuffer is set to true, then the back buffer will be antialiased.
* and the main gl context will not.
*
* You only need to activate this back buffer if you are using a blend mode that requires it.
*
* to activate is simple, you pass `useBackBuffer:true` to your render options
* @category rendering
* @advanced
*/
export declare class GlBackBufferSystem implements System<GlBackBufferOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "backBuffer";
readonly priority: 1;
};
/** default options for the back buffer system */
static defaultOptions: GlBackBufferOptions;
/** if true, the back buffer is used */
useBackBuffer: boolean;
private _backBufferTexture;
private readonly _renderer;
private _targetTexture;
private _useBackBufferThisRender;
private _antialias;
private _state;
private _bigTriangleShader;
constructor(renderer: WebGLRenderer);
init(options?: GlBackBufferOptions): void;
/**
* This is called before the RenderTargetSystem is started. This is where
* we replace the target with the back buffer if required.
* @param options - The options for this render.
*/
protected renderStart(options: RenderOptions): void;
protected renderEnd(): void;
private _presentBackBuffer;
private _getBackBufferTexture;
/** destroys the back buffer */
destroy(): void;
}
/**
* The system that handles color masking for the WebGL.
* @category rendering
* @advanced
*/
export declare class GlColorMaskSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "colorMask";
};
private readonly _renderer;
private _colorMaskCache;
constructor(renderer: WebGLRenderer);
setMask(colorMask: number): void;
destroy?: () => void;
}
/**
* The system that handles encoding commands for the WebGL.
* @category rendering
* @advanced
*/
export declare class GlEncoderSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "encoder";
};
readonly commandFinished: Promise<void>;
private readonly _renderer;
constructor(renderer: WebGLRenderer);
setGeometry(geometry: Geometry, shader?: Shader): void;
finishRenderPass(): void;
draw(options: {
geometry: Geometry;
shader: Shader;
state?: State;
topology?: Topology;
size?: number;
start?: number;
instanceCount?: number;
skipSync?: boolean;
}): void;
destroy(): void;
}
/**
* The GpuLimitsSystem provides information about the capabilities and limitations of the underlying GPU.
* These limits, such as the maximum number of textures that can be used in a shader
* (`maxTextures`) or the maximum number of textures that can be batched together (`maxBatchableTextures`),
* are determined by the specific graphics hardware and driver.
*
* The values for these limits are not available immediately upon instantiation of the class.
* They are populated when the GL rendering context is successfully initialized and ready,
* which occurs after the `renderer.init()` method has completed.
* Attempting to access these properties before the context is ready will result in undefined or default values.
*
* This system allows the renderer to adapt its behavior and resource allocation strategies
* to stay within the supported boundaries of the GPU, ensuring optimal performance and stability.
* @example
* ```ts
* const renderer = new WebGlRenderer();
* await renderer.init();
*
* console.log(renderer.limits.maxTextures);
* ```
* @category rendering
* @advanced
*/
export declare class GlLimitsSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "limits";
};
/** The maximum number of textures that can be used by a shader */
maxTextures: number;
/** The maximum number of batchable textures */
maxBatchableTextures: number;
/** The maximum number of uniform bindings */
maxUniformBindings: number;
private readonly _renderer;
constructor(renderer: WebGLRenderer);
contextChange(): void;
destroy(): void;
}
/**
* This manages the stencil buffer. Used primarily for masking
* @category rendering
* @advanced
*/
export declare class GlStencilSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "stencil";
};
private _gl;
private readonly _stencilCache;
private _renderTargetStencilState;
private _stencilOpsMapping;
private _comparisonFuncMapping;
private _activeRenderTarget;
constructor(renderer: WebGLRenderer);
protected contextChange(gl: WebGLRenderingContext): void;
protected onRenderTargetChange(renderTarget: RenderTarget): void;
resetState(): void;
setStencilMode(stencilMode: STENCIL_MODES, stencilReference: number): void;
destroy?: () => void;
}
/**
* System plugin to the renderer to manage uniform buffers. But with an WGSL adaptor.
* @category rendering
* @advanced
*/
export declare class GlUboSystem extends UboSystem {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "ubo";
};
constructor();
}
/**
* The precision types available in WebGL shaders.
*
* These types define the precision of floating-point calculations in shaders.
* - `highp`: High precision, typically 32-bit floating-point.
* - `mediump`: Medium precision, typically 16-bit floating-point.
* - `lowp`: Low precision, typically 8-bit floating-point.
* @category rendering
* @advanced
*/
export type PRECISION = `highp` | `mediump` | `lowp`;
/** @private */
export declare class IGLUniformData {
location: WebGLUniformLocation;
value: number | boolean | Float32Array | Int32Array | Uint32Array | boolean[];
}
/**
* Helper class to create a WebGL Program
* @private
*/
export declare class GlProgramData {
/** The shader program. */
program: WebGLProgram;
/**
* Holds the uniform data which contains uniform locations
* and current uniform values used for caching and preventing unneeded GPU commands.
*/
uniformData: Record<string, any>;
/**
* UniformGroups holds the various upload functions for the shader. Each uniform group
* and program have a unique upload function generated.
*/
uniformGroups: Record<string, any>;
/** A hash that stores where UBOs are bound to on the program. */
uniformBlockBindings: Record<string, any>;
/** A hash for lazily-generated uniform uploading functions. */
uniformSync: Record<string, any>;
/**
* A place where dirty ticks are stored for groups
* If a tick here does not match with the Higher level Programs tick, it means
* we should re upload the data.
*/
uniformDirtyGroups: Record<string, any>;
/**
* Makes a new Pixi program.
* @param program - webgl program
* @param uniformData - uniforms
*/
constructor(program: WebGLProgram, uniformData: {
[key: string]: IGLUniformData;
});
/** Destroys this program. */
destroy(): void;
}
/** @internal */
export interface ShaderSyncData {
textureCount: number;
blockIndex: number;
}
/** @internal */
export type ShaderSyncFunction = (renderer: WebGLRenderer, shader: Shader, syncData: ShaderSyncData) => void;
/**
* System plugin to the renderer to manage the shaders for WebGL.
* @category rendering
* @advanced
*/
export declare class GlShaderSystem {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "shader";
};
/** @internal */
_activeProgram: GlProgram;
private _programDataHash;
private readonly _renderer;
/** @internal */
_gl: WebGL2RenderingContext;
private _shaderSyncFunctions;
constructor(renderer: WebGLRenderer);
protected contextChange(gl: GlRenderingContext): void;
/**
* Changes the current shader to the one given in parameter.
* @param shader - the new shader
* @param skipSync - false if the shader should automatically sync its uniforms.
* @returns the glProgram that belongs to the shader.
*/
bind(shader: Shader, skipSync?: boolean): void;
/**
* Updates the uniform group.
* @param uniformGroup - the uniform group to update
*/
updateUniformGroup(uniformGroup: UniformGroup): void;
/**
* Binds a uniform block to the shader.
* @param uniformGroup - the uniform group to bind
* @param name - the name of the uniform block
* @param index - the index of the uniform block
*/
bindUniformBlock(uniformGroup: UniformGroup | BufferResource, name: string, index?: number): void;
private _setProgram;
/**
* @param program - the program to get the data for
* @internal
*/
_getProgramData(program: GlProgram): GlProgramData;
private _createProgramData;
destroy(): void;
/**
* Creates a function that can be executed that will sync the shader as efficiently as possible.
* Overridden by the unsafe eval package if you don't want eval used in your project.
* @param shader - the shader to generate the sync function for
* @param shaderSystem - the shader system to use
* @returns - the generated sync function
* @ignore
*/
_generateShaderSync(shader: Shader, shaderSystem: GlShaderSystem): ShaderSyncFunction;
resetState(): void;
}
/**
* Generates the a function that will efficiently sync shader resources with the GPU.
* @param shader - The shader to generate the code for
* @param shaderSystem - An instance of the shader system
* @internal
*/
export declare function generateShaderSyncCode(shader: Shader, shaderSystem: GlShaderSystem): ShaderSyncFunction;
/**
* Automatically generates a uniform group that holds the texture samplers for a shader.
* This is used mainly by the shaders that batch textures!
* @param maxTextures - the number of textures that this uniform group will contain.
* @returns a uniform group that holds the texture samplers.
* @internal
*/
export declare function getBatchSamplersUniformGroup(maxTextures: number): UniformGroup<any>;
/**
* System plugin to the renderer to manage shaders.
* @category rendering
* @advanced
*/
export declare class GlUniformGroupSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "uniformGroup";
};
/**
* The current WebGL rendering context.
* @type {WebGLRenderingContext}
*/
protected gl: GlRenderingContext;
/** Cache to holds the generated functions. Stored against UniformObjects unique signature. */
private _cache;
private _renderer;
private _uniformGroupSyncHash;
/** @param renderer - The renderer this System works for. */
constructor(renderer: WebGLRenderer);
protected contextChange(gl: GlRenderingContext): void;
/**
* Uploads the uniforms values to the currently bound shader.
* @param group - the uniforms values that be applied to the current shader
* @param program
* @param syncData
* @param syncData.textureCount
*/
updateUniformGroup(group: UniformGroup, program: GlProgram, syncData: {
textureCount: number;
}): void;
/**
* Overridable by the pixi.js/unsafe-eval package to use static syncUniforms instead.
* @param group
* @param program
*/
private _getUniformSyncFunction;
private _createUniformSyncFunction;
private _generateUniformsSync;
/**
* Takes a uniform group and data and generates a unique signature for them.
* @param group - The uniform group to get signature of
* @param group.uniforms
* @param uniformData - Uniform information generated by the shader
* @param preFix
* @returns Unique signature of the uniform group
*/
private _getSignature;
/** Destroys this System and removes all its textures. */
destroy(): void;
}
/**
* @param fragmentShader
* @internal
*/
export declare function migrateFragmentFromV7toV8(fragmentShader: string): string;
/**
* @private
* @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram}
* @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
* @param {string} src - The vertex shader source as an array of strings.
* @returns {WebGLShader} the shader
*/
export declare function compileShader(gl: WebGLRenderingContextBase, type: number, src: string): WebGLShader;
/**
* @param {string} type - Type of value
* @param {number} size
* @private
*/
export declare function defaultValue(type: string, size: number): number | Float32Array | Int32Array | Uint32Array | boolean | boolean[];
/**
* This function looks at the attribute information provided to the geometry and attempts
* to fill in any gaps. We do this by looking at the extracted data from the shader and
* making best guesses.
*
* Most of the time users don't need to provide all the attribute info beyond the data itself, so we
* can fill in the gaps for them. If you are using attributes in a more advanced way,
* don't forget to add all the info at creation!
* @param geometry - the geometry to ensure attributes for
* @param extractedData - the extracted data from the shader
* @internal
*/
export declare function ensureAttributes(geometry: Geometry, extractedData: Record<string, ExtractedAttributeData>): void;
/**
* generates a WebGL Program object from a high level Pixi Program.
* @param gl - a rendering context on which to generate the program
* @param program - the high level Pixi Program.
* @private
*/
export declare function generateProgram(gl: GlRenderingContext, program: GlProgram): GlProgramData;
/** @internal */
export declare function getMaxFragmentPrecision(): PRECISION;
/**
* returns a little WebGL context to use for program inspection.
* @private
* @returns {WebGLRenderingContext} a gl context to test with
*/
export declare function getTestContext(): GlRenderingContext;
/**
* returns the uniform block data from the program
* @private
* @param program - the webgl program
* @param gl - the WebGL context
* @returns {object} the uniform data for this program
*/
export declare function getUboData(program: WebGLProgram, gl: WebGL2RenderingContext): Record<string, GlUniformBlockData>;
/**
* returns the uniform data from the program
* @private
* @param program - the webgl program
* @param gl - the WebGL context
* @returns {object} the uniform data for this program
*/
export declare function getUniformData(program: WebGLProgram, gl: WebGLRenderingContextBase): {
[key: string]: GlUniformData;
};
/**
*
* logs out any program errors
* @param gl - The current WebGL context
* @param program - the WebGL program to display errors for
* @param vertexShader - the fragment WebGL shader program
* @param fragmentShader - the vertex WebGL shader program
* @private
*/
export declare function logProgramError(gl: WebGLRenderingContext, program: WebGLProgram, vertexShader: WebGLShader, fragmentShader: WebGLShader): void;
/**
* @private
* @param {string} type
*/
export declare function mapSize(type: string): number;
/**
* @param gl
* @param type
* @internal
*/
export declare function mapType(gl: any, type: number): string;
/**
* @param gl
* @param type
* @internal
*/
export declare function mapGlToVertexFormat(gl: any, type: number): VertexFormat;
/**
* @param src
* @param isES300
* @param isFragment
* @internal
*/
export declare function addProgramDefines(src: string, isES300: boolean, isFragment?: boolean): string;
interface EnsurePrecisionOptions {
requestedVertexPrecision: PRECISION;
requestedFragmentPrecision: PRECISION;
maxSupportedVertexPrecision: PRECISION;
maxSupportedFragmentPrecision: PRECISION;
}
/**
* Sets the float precision on the shader, ensuring the device supports the request precision.
* If the precision is already present, it just ensures that the device is able to handle it.
* @param src
* @param options
* @param options.requestedVertexPrecision
* @param options.requestedFragmentPrecision
* @param options.maxSupportedVertexPrecision
* @param options.maxSupportedFragmentPrecision
* @param isFragment
* @private
*/
export declare function ensurePrecision(src: string, options: EnsurePrecisionOptions, isFragment: boolean): string;
/**
* @param src
* @param isES300
* @internal
*/
export declare function insertVersion(src: string, isES300: boolean): string;
/**
* @param src
* @param root0
* @param root0.name
* @param isFragment
* @internal
*/
export declare function setProgramName(src: string, { name }: {
name: string;
}, isFragment?: boolean): string;
/**
* @param src
* @param isES300
* @internal
*/
export declare function stripVersion(src: string, isES300: boolean): string;
/** @internal */
export declare const WGSL_TO_STD40_SIZE: Record<string, number>;
/**
* @param uniformData
* @internal
*/
export declare function createUboElementsSTD40(uniformData: UniformData[]): UboLayout;
/**
* @param uboElements
* @internal
*/
export declare function createUboSyncFunctionSTD40(uboElements: UboElement[]): UniformsSyncCallback;
/**
* This generates a function that will sync an array to the uniform buffer
* following the std140 layout
* @param uboElement - the element to generate the array sync for
* @param offsetToAdd - the offset to append at the start of the code
* @returns - the generated code
* @internal
*/
export declare function generateArraySyncSTD40(uboElement: UboElement, offsetToAdd: number): string;
/**
* @param group
* @param uniformData
* @internal
*/
export declare function generateUniformsSync(group: UniformGroup, uniformData: Record<string, any>): UniformsSyncCallback;
/** @internal */
export declare const UNIFORM_TO_SINGLE_SETTERS: Record<UNIFORM_TYPES | string, string>;
/** @internal */
export declare const UNIFORM_TO_ARRAY_SETTERS: Record<UNIFORM_TYPES | string, string>;
/**
* System plugin to the renderer to manage WebGL state machines
* @category rendering
* @advanced
*/
export declare class GlStateSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "state";
};
/**
* State ID
* @readonly
*/
stateId: number;
/**
* Polygon offset
* @readonly
*/
polygonOffset: number;
/**
* Blend mode
* @default 'none'
* @readonly
*/
blendMode: BLEND_MODES;
/** Whether current blend equation is different */
protected _blendEq: boolean;
/**
* GL context
* @type {WebGLRenderingContext}
* @readonly
*/
protected gl: GlRenderingContext;
protected blendModesMap: Record<BLEND_MODES, number[]>;
/**
* Collection of calls
* @type {Function[]}
*/
protected readonly map: ((value: boolean) => void)[];
/**
* Collection of check calls
* @type {Function[]}
*/
protected readonly checks: ((system: this, state: State) => void)[];
/**
* Default WebGL State
* @readonly
*/
protected defaultState: State;
/**
* Whether to invert the front face when rendering
* This is used for render textures where the Y-coordinate is flipped
* @default false
*/
private _invertFrontFace;
private _glFrontFace;
private _cullFace;
private _frontFaceDirty;
private _frontFace;
constructor(renderer: WebGLRenderer);
protected onRenderTargetChange(renderTarget: RenderTarget): void;
protected contextChange(gl: GlRenderingContext): void;
/**
* Sets the current state
* @param {*} state - The state to set.
*/
set(state: State): void;
/**
* Sets the state, when previous state is unknown.
* @param {*} state - The state to set
*/
forceState(state: State): void;
/**
* Sets whether to enable or disable blending.
* @param value - Turn on or off WebGl blending.
*/
setBlend(value: boolean): void;
/**
* Sets whether to enable or disable polygon offset fill.
* @param value - Turn on or off webgl polygon offset testing.
*/
setOffset(value: boolean): void;
/**
* Sets whether to enable or disable depth test.
* @param value - Turn on or off webgl depth testing.
*/
setDepthTest(value: boolean): void;
/**
* Sets whether to enable or disable depth mask.
* @param value - Turn on or off webgl depth mask.
*/
setDepthMask(value: boolean): void;
/**
* Sets whether to enable or disable cull face.
* @param {boolean} value - Turn on or off webgl cull face.
*/
setCullFace(value: boolean): void;
/**
* Sets the gl front face.
* @param {boolean} value - true is clockwise and false is counter-clockwise
*/
setFrontFace(value: boolean): void;
/**
* Sets the blend mode.
* @param {number} value - The blend mode to set to.
*/
setBlendMode(value: BLEND_MODES): void;
/**
* Sets the polygon offset.
* @param {number} value - the polygon offset
* @param {number} scale - the polygon offset scale
*/
setPolygonOffset(value: number, scale: number): void;
/** Resets all the logic and disables the VAOs. */
resetState(): void;
/**
* Checks to see which updates should be checked based on which settings have been activated.
*
* For example, if blend is enabled then we should check the blend modes each time the state is changed
* or if polygon fill is activated then we need to check if the polygon offset changes.
* The idea is that we only check what we have too.
* @param func - the checking function to add or remove
* @param value - should the check function be added or removed.
*/
private _updateCheck;
/**
* A private little wrapper function that we call to check the blend mode.
* @param system - the System to perform the state check on
* @param state - the state that the blendMode will pulled from
*/
private static _checkBlendMode;
/**
* A private little wrapper function that we call to check the polygon offset.
* @param system - the System to perform the state check on
* @param state - the state that the blendMode will pulled from
*/
private static _checkPolygonOffset;
/** @ignore */
destroy(): void;
}
/**
* Maps gl blend combinations to WebGL.
* @param gl
* @returns {object} Map of gl blend combinations to WebGL.
* @internal
*/
export declare function mapWebGLBlendModesToPixi(gl: GlRenderingContext): Record<BLEND_MODES, number[]>;
/**
* The system for managing textures in WebGL.
* @category rendering
* @advanced
*/
export declare class GlTextureSystem implements System, CanvasGenerator {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "texture";
};
private readonly _renderer;
private readonly _managedTextures;
/**
* @deprecated since 8.15.0
*/
get managedTextures(): Readonly<TextureSource[]>;
private _glSamplers;
private _boundTextures;
private _activeTextureLocation;
private _boundSamplers;
private readonly _uploads;
private _gl;
private _mapFormatToInternalFormat;
private _mapFormatToType;
private _mapFormatToFormat;
private _premultiplyAlpha;
private readonly _useSeparateSamplers;
constructor(renderer: WebGLRenderer);
protected contextChange(gl: GlRenderingContext): void;
/**
* Initializes a texture source, if it has already been initialized nothing will happen.
* @param source - The texture source to initialize.
* @returns The initialized texture source.
*/
initSource(source: TextureSource): void;
bind(texture: BindableTexture, location?: number): void;
bindSource(source: TextureSource, location?: number): void;
private _bindSampler;
unbind(texture: BindableTexture): void;
private _activateLocation;
private _initSource;
protected onStyleChange(source: TextureSource): void;
protected updateStyle(source: TextureSource, firstCreation: boolean): void;
protected onSourceUnload(source: TextureSource, contextLost?: boolean): void;
protected onSourceUpdate(source: TextureSource): void;
protected onUpdateMipmaps(source: TextureSource, bind?: boolean): void;
private _initSampler;
private _getGlSampler;
getGlSource(source: TextureSource): GlTexture;
generateCanvas(texture: Texture): ICanvas;
getPixels(texture: Texture): GetPixelsOutput;
destroy(): void;
resetState(): void;
}
/** @internal */
export interface GLTextureUploader {
id: string;
upload(source: TextureSource, glTexture: GlTexture, gl: GlRenderingContext, webGLVersion: number): void;
}
/** @internal */
export declare const glUploadBufferImageResource: GLTextureUploader;
/** @internal */
export declare const glUploadCompressedTextureResource: GLTextureUploader;
/** @internal */
export declare const glUploadImageResource: GLTextureUploader;
/** @internal */
export declare const glUploadVideoResource: GLTextureUploader;
/**
* @param style
* @param gl
* @param mipmaps
* @param anisotropicExt
* @param glFunctionName
* @param firstParam
* @param forceClamp
* @param firstCreation
* @internal
*/
export declare function applyStyleParams(style: TextureStyle, gl: WebGL2RenderingContext, mipmaps: boolean, anisotropicExt: EXT_texture_filter_anisotropic, glFunctionName: "samplerParameteri" | "texParameteri", firstParam: 3553 | WebGLSampler, forceClamp: boolean,
/** if true we can skip setting certain values if the values is the same as the default gl values */
firstCreation: boolean): void;
/** @internal */
export declare function getSupportedGlCompressedTextureFormats(): TEXTURE_FORMATS[];
/**
* Returns a lookup table that maps each type-format pair to a compatible internal format.
* @function mapTypeAndFormatToInternalFormat
* @private
* @param {WebGLRenderingContext} gl - The rendering context.
* @returns Lookup table.
*/
export declare function mapFormatToGlFormat(gl: GlRenderingContext): Record<string, number>;
/**
* Returns a lookup table that maps each type-format pair to a compatible internal format.
* @function mapTypeAndFormatToInternalFormat
* @private
* @param gl - The rendering context.
* @param extensions - The WebGL extensions.
* @returns Lookup table.
*/
export declare function mapFormatToGlInternalFormat(gl: GlRenderingContext, extensions: WebGLExtensions): Record<string, number>;
/**
* Returns a lookup table that maps each type-format pair to a compatible internal format.
* @function mapTypeAndFormatToInternalFormat
* @private
* @param {WebGLRenderingContext} gl - The rendering context.
* @returns Lookup table.
*/
export declare function mapFormatToGlType(gl: GlRenderingContext): Record<string, number>;
/** @internal */
export declare const scaleModeToGlFilter: {
linear: number;
nearest: number;
};
/** @internal */
export declare const mipmapScaleModeToGlFilter: {
linear: {
linear: number;
nearest: number;
};
nearest: {
linear: number;
nearest: number;
};
};
/** @internal */
export declare const wrapModeToGlAddress: {
"clamp-to-edge": number;
repeat: number;
"mirror-repeat": number;
};
/** @internal */
export declare const compareModeToGlCompare: {
never: number;
less: number;
equal: number;
"less-equal": number;
greater: number;
"not-equal": number;
"greater-equal": number;
always: number;
};
/**
* @param pixels
* @internal
*/
export declare function unpremultiplyAlpha(pixels: Uint8Array | Uint8ClampedArray): void;
/** @internal */
export declare class UboBatch {
data: Float32Array;
private readonly _minUniformOffsetAlignment;
byteIndex: number;
constructor({ minUniformOffsetAlignment }: {
minUniformOffsetAlignment: number;
});
clear(): void;
addEmptyGroup(size: number): number;
addGroup(array: Float32Array): number;
destroy(): void;
}
/**
* @param pm
* @param x
* @param y
* @param width
* @param height
* @param flipY
* @internal
*/
export declare function calculateProjection(pm: Matrix, x: number, y: number, width: number, height: number, flipY: boolean): Matrix;
/** @internal */
export declare const WGSL_ALIGN_SIZE_DATA: Record<UNIFORM_TYPES | string, {
align: number;
size: number;
}>;
/**
* @param uniformData
* @internal
*/
export declare function createUboElementsWGSL(uniformData: UniformData[]): UboLayout;
/**
* @param uboElements
* @internal
*/
export declare function createUboSyncFunctionWGSL(uboElements: UboElement[]): UniformsSyncCallback;
/**
* @param root0
* @param root0.source
* @param root0.entryPoint
* @internal
*/
export declare function extractAttributesFromGpuProgram({ source, entryPoint }: ProgramSource): Record<string, ExtractedAttributeData>;
/**
* This generates a function that will sync an array to the uniform buffer
* following the wgsl layout
* @param uboElement - the element to generate the array sync for
* @param offsetToAdd - the offset to append at the start of the code
* @returns - the generated code
* @internal
*/
export declare function generateArraySyncWGSL(uboElement: UboElement, offsetToAdd: number): string;
/**
* @param root0
* @param root0.groups
* @internal
*/
export declare function generateGpuLayoutGroups({ groups }: StructsAndGroups): ProgramPipelineLayoutDescription;
/**
* @param root0
* @param root0.groups
* @internal
*/
export declare function generateLayoutHash({ groups }: StructsAndGroups): ProgramLayout;
/**
* @param vertexStructsAndGroups
* @param fragmentStructsAndGroups
* @internal
*/
export declare function removeStructAndGroupDuplicates(vertexStructsAndGroups: StructsAndGroups, fragmentStructsAndGroups: StructsAndGroups): {
structs: {
name: string;
members: Record<string, string>;
}[];
groups: {
group: number;
binding: number;
name: string;
isUniform: boolean;
type: string;
}[];
};
/** @internal */
export declare const GpuBlendModesToPixi: Partial<Record<BLEND_MODES, GPUBlendState>>;
/**
* The stencil state for the GPU renderer.
* This is used to define how the stencil buffer should be configured.
* @category rendering
* @advanced
*/
export interface StencilState {
stencilWriteMask?: number;
stencilReadMask?: number;
stencilFront?: {
compare: "always" | "equal" | "not-equal";
passOp: "increment-clamp" | "decrement-clamp" | "keep" | "replace";
};
stencilBack?: {
compare: "always" | "equal" | "not-equal";
passOp: "increment-clamp" | "decrement-clamp" | "keep" | "replace";
};
}
/** @internal */
export declare const GpuStencilModesToPixi: StencilState[];
/** @internal */
export interface GpuTextureUploader<T extends TextureSource = TextureSource> {
type: string;
upload(source: T, gpuTexture: GPUTexture, gpu: GPU$1): void;
}
/** @internal */
export declare const gpuUploadBufferImageResource: GpuTextureUploader<BufferImageSource>;
/**
* A texture source that uses a compressed resource, such as an array of Uint8Arrays.
* It is used for compressed textures that can be uploaded to the GPU.
* @category rendering
* @advanced
*/
export declare class CompressedSource extends TextureSource<Uint8Array[]> {
readonly uploadMethodId = "compressed";
constructor(options: TextureSourceOptions);
}
/** @internal */
export declare const blockDataMap: Record<string, {
blockBytes: number;
blockWidth: number;
blockHeight: number;
}>;
/** @internal */
export declare const gpuUploadCompressedTextureResource: GpuTextureUploader<CompressedSource>;
/** @internal */
export declare const gpuUploadImageResource: GpuTextureUploader<TextureSource<any>>;
/**
* A utility type that represents a tuple of length L containing elements of type T.
* @category utils
* @advanced
*/
export type ArrayFixed<T, L extends number> = [
T,
...Array<T>
] & {
length: L;
};
/**
* A dictionary type that maps string keys to values of type T.
* @category utils
* @advanced
*/
export type Dict<T> = {
[key: string]: T;
};
/**
* The type of resource used for video textures.
* This is typically an HTMLVideoElement.
* @category rendering
* @advanced
*/
export type VideoResource = HTMLVideoElement;
/**
* Options for video sources.
* @category rendering
* @advanced
*/
export interface VideoSourceOptions extends TextureSourceOptions<VideoResource> {
/** If true, the video will start loading immediately. */
autoLoad?: boolean;
/** If true, the video will start playing as soon as it is loaded. */
autoPlay?: boolean;
/** The number of times a second to update the texture from the video. Leave at 0 to update at every render. */
updateFPS?: number;
/** If true, the video will be loaded with the `crossorigin` attribute. */
crossorigin?: boolean | string;
/** If true, the video will loop when it ends. */
loop?: boolean;
/** If true, the video will be muted. */
muted?: boolean;
/** If true, the video will play inline. */
playsinline?: boolean;
/** If true, the video will be preloaded. */
preload?: boolean;
/** The time in milliseconds to wait for the video to preload before timing out. */
preloadTimeoutMs?: number;
/** The alpha mode of the video. */
alphaMode?: ALPHA_MODES;
}
/**
* A texture source that uses a video as its resource.
* It automatically resizes the texture based on the video dimensions.
* It also provides methods to control playback and handle video events.
* This class supports automatic loading, playback, and frame updates.
* It can also handle cross-origin videos and provides options for looping, muting, and inline playback.
* @category rendering
* @advanced
*/
export declare class VideoSource extends TextureSource<VideoResource> {
static extension: ExtensionMetadata;
/** The default options for video sources. */
static defaultOptions: VideoSourceOptions;
/** Whether or not the video is ready to play. */
isReady: boolean;
/** The upload method for this texture. */
uploadMethodId: string;
/**
* When set to true will automatically play videos used by this texture once
* they are loaded. If false, it will not modify the playing state.
* @default true
*/
protected autoPlay: boolean;
/**
* `true` to use Ticker.shared to auto update the base texture.
* @default true
*/
private _autoUpdate;
/**
* `true` if the instance is currently connected to Ticker.shared to auto update the base texture.
* @default false
*/
private _isConnectedToTicker;
/**
* Promise when loading.
* @default null
*/
private _load;
private _msToNextUpdate;
private _preloadTimeout;
/** Callback when completed with load. */
private _resolve;
private _reject;
private _updateFPS;
private _videoFrameRequestCallbackHandle;
constructor(options: VideoSourceOptions);
/** Update the video frame if the source is not destroyed and meets certain conditions. */
protected updateFrame(): void;
/** Callback to update the video frame and potentially request the next frame update. */
private _videoFrameRequestCallback;
/**
* Checks if the resource has valid dimensions.
* @returns {boolean} True if width and height are set, otherwise false.
*/
get isValid(): boolean;
/**
* Start preloading the video resource.
* @returns {Promise<this>} Handle the validate event
*/
load(): Promise<this>;
/**
* Handle video error events.
* @param event - The error event
*/
private _onError;
/**
* Checks if the underlying source is playing.
* @returns True if playing.
*/
private _isSourcePlaying;
/**
* Checks if the underlying source is ready for playing.
* @returns True if ready.
*/
private _isSourceReady;
/** Runs the update loop when the video is ready to play. */
private _onPlayStart;
/** Stops the update loop when a pause event is triggered. */
private _onPlayStop;
/** Handles behavior when the video completes seeking to the current playback position. */
private _onSeeked;
private _onCanPlay;
private _onCanPlayThrough;
/** Fired when the video is loaded and ready to play. */
private _mediaReady;
/** Cleans up resources and event listeners associated with this texture. */
destroy(): void;
/** Should the base texture automatically update itself, set to true by default. */
get autoUpdate(): boolean;
set autoUpdate(value: boolean);
/**
* How many times a second to update the texture from the video.
* Leave at 0 to update at every render.
* A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
*/
get updateFPS(): number;
set updateFPS(value: number);
/**
* Configures the updating mechanism based on the current state and settings.
*
* This method decides between using the browser's native video frame callback or a custom ticker
* for updating the video frame. It ensures optimal performance and responsiveness
* based on the video's state, playback status, and the desired frames-per-second setting.
*
* - If `_autoUpdate` is enabled and the video source is playing:
* - It will prefer the native video frame callback if available and no specific FPS is set.
* - Otherwise, it will use a custom ticker for manual updates.
* - If `_autoUpdate` is disabled or the video isn't playing, any active update mechanisms are halted.
*/
private _configureAutoUpdate;
/**
* Map of video MIME types that can't be directly derived from file extensions.
* @readonly
*/
static MIME_TYPES: Dict<string>;
static test(resource: any): resource is VideoResource;
}
/** @internal */
export declare const gpuUploadVideoResource: GpuTextureUploader<VideoSource>;
/** @internal */
export declare function getSupportedGPUCompressedTextureFormats(): Promise<TEXTURE_FORMATS[]>;
/**
* A class which generates mipmaps for a GPUTexture.
* Thanks to toji for the original implementation
* https://github.com/toji/web-texture-tool/blob/main/src/webgpu-mipmap-generator.js
* @category rendering
* @ignore
*/
export declare class GpuMipmapGenerator {
device: GPUDevice;
sampler: GPUSampler;
pipelines: Record<string, GPURenderPipeline>;
mipmapShaderModule: any;
constructor(device: GPUDevice);
private _getMipmapPipeline;
/**
* Generates mipmaps for the given GPUTexture from the data in level 0.
* @param {module:External.GPUTexture} texture - Texture to generate mipmaps for.
* @returns {module:External.GPUTexture} - The originally passed texture
*/
generateMipmap(texture: GPUTexture): GPUTexture;
}
/**
* Copies from one buffer to another.
* This is an optimised function that will use `Float64Array` window.
* This means it can copy twice as fast!
* @param sourceBuffer - the array buffer to copy from
* @param destinationBuffer - the array buffer to copy to
* @private
*/
export declare function fastCopy(sourceBuffer: ArrayBuffer, destinationBuffer: ArrayBuffer): void;
/**
* Takes a vertices array and a matrix and transforms the vertices based on the matrix.
* this out put is written to the uvs array
* @param vertices - the vertices to calculate uvs from
* @param verticesStride - the stride of the vertice
* @param verticesOffset - the offset of the vertices
* @param uvs - the uvs to fill
* @param uvsOffset - the offset of the uvs
* @param uvsStride - the stride of the uvs
* @param size - the size of the vertices
* @param matrix - the matrix to apply to the uvs
* @internal
*/
export declare function buildUvs(vertices: number[], verticesStride: number, verticesOffset: number, uvs: number[], uvsOffset: number, uvsStride: number, size: number, matrix?: Matrix): void;
/**
* @param uvs
* @param uvsOffset
* @param uvsStride
* @param size
* @internal
*/
export declare function buildSimpleUvs(uvs: number[], uvsOffset: number, uvsStride: number, size: number): void;
/**
* Converts something into a buffer. If it is already a buffer it will pass it through
* if it is a number array it will convert it to a float32 array before being passed into a buffer
* the buffer will be created with the correct usage flags for geometry attributes
* @param buffer - number array
* @param index - is this an index buffer?
* @returns a buffer
* @category rendering
* @internal
*/
export declare function ensureIsBuffer(buffer: Buffer$1 | TypedArray | number[], index: boolean): Buffer$1;
/**
* @param format
* @internal
*/
export declare function getAttributeInfoFromFormat(format: VertexFormat): {
size: number;
stride: number;
normalised: boolean;
};
/**
* Gets the 2D bounds of a geometry, based on a specific attribute.
* @param geometry - Geometry to to measure
* @param attributeId - AttributeId that contains the x,y data
* @param bounds - Bounds to store the result in
* @returns the bounds
* @internal
*/
export declare function getGeometryBounds(geometry: Geometry, attributeId: string, bounds: Bounds): Bounds;
/**
* Transforms the vertices in an array with the given matrix.
* @param vertices - the vertices to transform
* @param m - the matrix to apply to the vertices
* @param offset - the offset of the vertices (defaults to 0)
* @param stride - the stride of the vertices (defaults to 2)
* @param size - the size of the vertices (defaults to vertices.length / stride - offset)
* @category rendering
* @internal
*/
export declare function transformVertices(vertices: number[], m: Matrix, offset?: number, stride?: number, size?: number): void;
/**
* Checks if the render target is viewable on the screen
* Basically, is it a canvas element and is that canvas element in the DOM
* @param renderTarget - the render target to check
* @returns true if the render target is viewable on the screen
* @internal
*/
export declare function isRenderingToScreen(renderTarget: RenderTarget): boolean;
/**
* The SchedulerSystem manages scheduled tasks with specific intervals.
* @category rendering
* @advanced
*/
export declare class SchedulerSystem implements System<null> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "scheduler";
readonly priority: 0;
};
private readonly _tasks;
/** a small off set to apply to the repeat schedules. This is just to make sure they run at slightly different times */
private _offset;
/** Initializes the scheduler system and starts the ticker. */
init(): void;
/**
* Schedules a repeating task.
* @param func - The function to execute.
* @param duration - The interval duration in milliseconds.
* @param useOffset - this will spread out tasks so that they do not all run at the same time
* @returns The unique identifier for the scheduled task.
*/
repeat(func: (elapsed: number) => void, duration: number, useOffset?: boolean): number;
/**
* Cancels a scheduled task.
* @param id - The unique identifier of the task to cancel.
*/
cancel(id: number): void;
/**
* Updates and executes the scheduled tasks.
* @private
*/
private _update;
/**
* Destroys the scheduler system and removes all tasks.
* @internal
*/
destroy(): void;
}
/** @internal */
export declare enum ShaderStage {
VERTEX = 1,
FRAGMENT = 2,
COMPUTE = 4
}
/**
* System plugin to the renderer to manage the shaders.
* @category rendering
* @advanced
*/
export interface ShaderSystem extends System {
/** the maximum number of textures that can be bound to a shader */
readonly maxTextures: number;
}
/**
* @param uboElements
* @param parserCode
* @param arrayGenerationFunction
* @param singleSettersMap
* @internal
*/
export declare function createUboSyncFunction(uboElements: UboElement[], parserCode: "uboWgsl" | "uboStd40", arrayGenerationFunction: (uboElement: UboElement, offsetToAdd: number) => string, singleSettersMap: Record<UNIFORM_TYPES_SINGLE, string>): UniformsSyncCallback;
/**
* @param {string} type - Type of value
* @param {number} size
* @private
*/
export declare function getDefaultUniformValue(type: string, size: number): number | Float32Array | Int32Array | Uint32Array | boolean | boolean[];
/** @internal */
export declare const uboSyncFunctionsSTD40: Record<UNIFORM_TYPES_SINGLE, string>;
/** @internal */
export declare const uboSyncFunctionsWGSL: Record<UNIFORM_TYPES_SINGLE, string>;
interface UniformParserDefinition {
type: UNIFORM_TYPES;
test(data: UniformData): boolean;
ubo?: string;
uboWgsl?: string;
uboStd40?: string;
uniform?: string;
}
/** @internal */
export declare const uniformParsers: UniformParserDefinition[];
/**
* Options for the startup system.
* @property {boolean} [hello=false] - Whether to log the version and type information of renderer to console.
* @category rendering
* @advanced
*/
export interface HelloSystemOptions {
/**
* Whether to log the version and type information of renderer to console.
* @default false
*/
hello: boolean;
}
/**
* A simple system responsible for initiating the renderer.
* @category rendering
* @advanced
*/
export declare class HelloSystem implements System<HelloSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "hello";
readonly priority: -2;
};
/** The default options for the system. */
static defaultOptions: HelloSystemOptions;
private readonly _renderer;
constructor(renderer: Renderer);
/**
* It all starts here! This initiates every system, passing in the options for any system by name.
* @param options - the config for the renderer and all its systems
*/
init(options: HelloSystemOptions): void;
}
/**
* Adjusts a blend mode for the current alpha mode. Returns the blend mode that works with that format.
* eg 'normal' blend mode will return 'normal-npm' when rendering with premultiplied alpha.
* and 'normal' if the texture is already premultiplied (the default)
* @param blendMode - The blend mode to get the adjusted blend mode for.
* @param textureSource - The texture to test the format of.
* @returns - the blend mode that should be used to render this texture correctly based on its alphaMode
* @internal
*/
export declare function getAdjustedBlendModeBlend(blendMode: BLEND_MODES, textureSource: TextureSource): BLEND_MODES;
interface System$1 {
extension: {
name: string;
};
defaultOptions?: any;
new (...args: any): any;
}
type SystemsWithExtensionList = System$1[];
type InstanceType$1<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
type NameType<T extends SystemsWithExtensionList> = T[number]["extension"]["name"];
/**
* Create a mapped type where each property key is a 'name' value,
* and each property value is an ElementType with a matching 'name'
* @internal
*/
export type ExtractSystemTypes<T extends SystemsWithExtensionList> = {
[K in NameType<T>]: InstanceType$1<Extract<T[number], {
extension: {
name: K;
};
}>>;
};
type NotUnknown<T> = T extends unknown ? keyof T extends never ? never : T : T;
type KnownProperties<T> = {
[K in keyof T as NotUnknown<T[K]> extends never ? never : K]: T[K];
};
type FlattenOptions<T> = T extends {
[K: string]: infer U;
} ? U : never;
type OptionsUnion<T extends SystemsWithExtensionList> = FlattenOptions<SeparateOptions<T>>;
type DefaultOptionsTypes<T extends SystemsWithExtensionList> = {
[K in NameType<T>]: Extract<T[number], {
extension: {
name: K;
};
}>["defaultOptions"];
};
type SeparateOptions<T extends SystemsWithExtensionList> = KnownProperties<DefaultOptionsTypes<T>>;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/** @internal */
export type ExtractRendererOptions<T extends SystemsWithExtensionList> = UnionToIntersection<OptionsUnion<T>>;
/**
* A utility type that represents a canvas and its rendering context.
* @category rendering
* @internal
*/
export interface CanvasAndContext {
/** The canvas element. */
canvas: ICanvas;
/** The rendering context of the canvas. */
context: ICanvasRenderingContext2D;
}
/**
* CanvasPool is a utility class that manages a pool of reusable canvas elements
* @category rendering
* @internal
*/
export declare class CanvasPoolClass {
canvasOptions: ICanvasRenderingContext2DSettings;
/**
* Allow renderTextures of the same size as screen, not just pow2
*
* Automatically sets to true after `setScreenSize`
* @default false
*/
enableFullScreen: boolean;
private _canvasPool;
constructor(canvasOptions?: ICanvasRenderingContext2DSettings);
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
*/
private _createCanvasAndContext;
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param minWidth - The minimum width of the render texture.
* @param minHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @returns The new render texture.
*/
getOptimalCanvasAndContext(minWidth: number, minHeight: number, resolution?: number): CanvasAndContext;
/**
* Place a render texture back into the pool.
* @param canvasAndContext
*/
returnCanvasAndContext(canvasAndContext: CanvasAndContext): void;
clear(): void;
}
/**
* CanvasPool is a utility class that manages a pool of reusable canvas elements
* @category rendering
* @internal
*/
export declare const CanvasPool: CanvasPoolClass;
/**
* Options for the {@link RenderableGCSystem}.
* @category rendering
* @property {boolean} [renderableGCActive=true] - If set to true, this will enable the garbage collector on the renderables.
* @property {number} [renderableGCAMaxIdle=60000] -
* The maximum idle frames before a texture is destroyed by garbage collection.
* @property {number} [renderableGCCheckCountMax=60000] - time between two garbage collections.
* @advanced
*/
export interface RenderableGCSystemOptions {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
*/
renderableGCActive: boolean;
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
*/
renderableGCMaxUnusedTime: number;
/**
* Frames between two garbage collections.
* @default 600
*/
renderableGCFrequency: number;
}
/**
* The RenderableGCSystem is responsible for cleaning up GPU resources that are no longer being used.
*
* When rendering objects like sprites, text, etc - GPU resources are created and managed by the renderer.
* If these objects are no longer needed but not properly destroyed (via sprite.destroy()), their GPU resources
* would normally leak. This system prevents that by automatically cleaning up unused GPU resources.
*
* Key features:
* - Runs every 30 seconds by default to check for unused resources
* - Cleans up resources not rendered for over 1 minute
* - Works independently of rendering - will clean up even when not actively rendering
* - When cleaned up resources are needed again, new GPU objects are quickly assigned from a pool
* - Can be disabled with renderableGCActive:false for manual control
*
* Best practices:
* - Always call destroy() explicitly when done with renderables (e.g. sprite.destroy())
* - This system is a safety net, not a replacement for proper cleanup
* - Adjust frequency and timeouts via options if needed
* @example
* ```js
* // Sprite created but reference lost without destroy
* let sprite = new Sprite(texture);
*
* // internally the renderer will assign a resource to the sprite
* renderer.render(sprite);
*
* sprite = null; // Reference lost but GPU resources still exist
*
* // After 1 minute of not being rendered:
* // - RenderableGC will clean up the sprite's GPU resources
* // - JS garbage collector can then clean up the sprite itself
* ```
* @category rendering
* @advanced
*/
export declare class RenderableGCSystem implements System<RenderableGCSystemOptions> {
/**
* Extension metadata for registering this system with the renderer.
* @ignore
*/
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "renderableGC";
readonly priority: 0;
};
/**
* Default configuration options for the garbage collection system.
* These can be overridden when initializing the renderer.
*/
static defaultOptions: RenderableGCSystemOptions;
/** Maximum time in ms a resource can be unused before being garbage collected */
maxUnusedTime: number;
/** Reference to the renderer this system belongs to */
private _renderer;
/** Array of renderables being tracked for garbage collection */
private readonly _managedRenderables;
/** ID of the main GC scheduler handler */
private _handler;
/** How frequently GC runs in ms */
private _frequency;
/** Current timestamp used for age calculations */
private _now;
/** Array of hash objects being tracked for cleanup */
private readonly _managedHashes;
/** ID of the hash cleanup scheduler handler */
private _hashHandler;
/** Array of arrays being tracked for cleanup */
private readonly _managedArrays;
/** ID of the array cleanup scheduler handler */
private _arrayHandler;
/**
* Creates a new RenderableGCSystem instance.
* @param renderer - The renderer this garbage collection system works for
*/
constructor(renderer: Renderer);
/**
* Initializes the garbage collection system with the provided options.
* @param options - Configuration options for the renderer
*/
init(options: RenderableGCSystemOptions): void;
/**
* Gets whether the garbage collection system is currently enabled.
* @returns True if GC is enabled, false otherwise
*/
get enabled(): boolean;
/**
* Enables or disables the garbage collection system.
* When enabled, schedules periodic cleanup of resources.
* When disabled, cancels all scheduled cleanups.
*/
set enabled(value: boolean);
/**
* Adds a hash table to be managed by the garbage collector.
* @param context - The object containing the hash table
* @param hash - The property name of the hash table
*/
addManagedHash<T>(context: T, hash: string): void;
/**
* Adds an array to be managed by the garbage collector.
* @param context - The object containing the array
* @param hash - The property name of the array
*/
addManagedArray<T>(context: T, hash: string): void;
/**
* Updates the GC timestamp and tracking before rendering.
* @param options - The render options
* @param options.container - The container to render
*/
prerender({ container }: RenderOptions): void;
/**
* Starts tracking a renderable for garbage collection.
* @param renderable - The renderable to track
*/
addRenderable(renderable: Renderable): void;
/**
* Performs garbage collection by cleaning up unused renderables.
* Removes renderables that haven't been used for longer than maxUnusedTime.
*/
run(): void;
/** Cleans up the garbage collection system. Disables GC and removes all tracked resources. */
destroy(): void;
/**
* Removes a renderable from being tracked when it's destroyed.
* @param renderable - The renderable to stop tracking
*/
private _removeRenderable;
/**
* Updates the GC tick counter for a render group and its children.
* @param renderGroup - The render group to update
* @param gcTick - The new tick value
*/
private _updateInstructionGCTick;
}
/**
* Options for creating a CanvasSource.
* @category rendering
* @advanced
*/
export interface CanvasSourceOptions extends TextureSourceOptions<ICanvas> {
/**
* Should the canvas be resized to preserve its screen width and height regardless
* of the resolution of the renderer, this is only supported for HTMLCanvasElement
* and will be ignored if the canvas is an OffscreenCanvas.
*/
autoDensity?: boolean;
/** if true, this canvas will be set up to be transparent where possible */
transparent?: boolean;
}
/**
* A texture source that uses a canvas as its resource.
* It automatically resizes the canvas based on the width, height, and resolution.
* It also provides a 2D rendering context for drawing.
* @category rendering
* @advanced
*/
export declare class CanvasSource extends TextureSource<ICanvas> {
static extension: ExtensionMetadata;
uploadMethodId: string;
autoDensity: boolean;
transparent: boolean;
private _context2D;
constructor(options: CanvasSourceOptions);
resizeCanvas(): void;
resize(width?: number, height?: number, resolution?: number): boolean;
static test(resource: any): resource is ICanvas;
/**
* Returns the 2D rendering context for the canvas.
* Caches the context after creating it.
* @returns The 2D rendering context of the canvas.
*/
get context2D(): CanvasRenderingContext2D;
}
/**
* The type of image-like resource that can be used as a texture source.
*
* - `ImageBitmap` is used for bitmap images.
* - `HTMLCanvasElement` and `OffscreenCanvas` are used for canvas elements.
* - `ICanvas` is an interface for canvas-like objects.
* - `VideoFrame` is used for video frames.
* - `HTMLImageElement` is used for HTML image elements.
* - `HTMLVideoElement` is used for HTML video elements.
* @category rendering
* @advanced
*/
export type ImageResource = ImageBitmap | HTMLCanvasElement | OffscreenCanvas | ICanvas | VideoFrame | HTMLImageElement | HTMLVideoElement;
/**
* A texture source that uses an image-like resource as its resource.
* It can handle HTMLImageElement, ImageBitmap, VideoFrame, and HTMLVideoElement.
* It is used for textures that can be uploaded to the GPU.
* @category rendering
* @advanced
*/
export declare class ImageSource extends TextureSource<ImageResource> {
static extension: ExtensionMetadata;
uploadMethodId: string;
constructor(options: TextureSourceOptions<ImageResource>);
static test(resource: any): resource is ImageResource;
}
/**
* Options for the {@link TextureGCSystem}.
* @category rendering
* @advanced
* @deprecated since 8.15.0
* @see {@link GCSystem}
*/
export interface TextureGCSystemOptions {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
* @deprecated since 8.15.0
*/
textureGCActive: boolean;
/**
* @deprecated since 8.3.0
* @see {@link TextureGCSystemOptions.textureGCMaxIdle}
*/
textureGCAMaxIdle: number;
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
* @deprecated since 8.15.0
*/
textureGCMaxIdle: number;
/**
* Frames between two garbage collections.
* @default 600
* @deprecated since 8.15.0
*/
textureGCCheckCountMax: number;
}
/**
* System plugin to the renderer to manage texture garbage collection on the GPU,
* ensuring that it does not get clogged up with textures that are no longer being used.
* @category rendering
* @advanced
* @deprecated since 8.15.0
* @see {@link GCSystem}
*/
export declare class TextureGCSystem implements System<TextureGCSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "textureGC";
};
/**
* Default options for the TextureGCSystem
* @deprecated since 8.15.0
*/
static defaultOptions: TextureGCSystemOptions;
/**
* Frame count since started.
* @readonly
* @deprecated since 8.15.0
*/
get count(): number;
/**
* Frame count since last garbage collection.
* @readonly
* @deprecated since 8.15.0
*/
get checkCount(): number;
set checkCount(value: number);
private _checkCount;
/**
* Maximum idle frames before a texture is destroyed by garbage collection.
* @see TextureGCSystem.defaultMaxIdle
* @deprecated since 8.15.0
*/
get maxIdle(): number;
set maxIdle(value: number);
/**
* Frames between two garbage collections.
* @see TextureGCSystem.defaultCheckCountMax
* @deprecated since 8.15.0
*/
get checkCountMax(): number;
set checkCountMax(_value: number);
/**
* Current garbage collection mode.
* @see TextureGCSystem.defaultMode
* @deprecated since 8.15.0
*/
get active(): boolean;
set active(value: boolean);
private _renderer;
/** @param renderer - The renderer this System works for. */
constructor(renderer: Renderer);
init(options: TextureGCSystemOptions): void;
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
* @deprecated since 8.15.0
*/
run(): void;
destroy(): void;
}
/**
* Class controls uv mapping from Texture normal space to BaseTexture normal space.
*
* Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite.
*
* Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture.
* If you want to add support for texture region of certain feature or filter, that's what you're looking for.
*
* Takes track of Texture changes through `_lastTextureID` private field.
* Use `update()` method call to track it from outside.
* @see Texture
* @see Mesh
* @see TilingSprite
* @category rendering
* @advanced
*/
export declare class TextureMatrix {
/**
* Matrix operation that converts texture region coords to texture coords
* @readonly
*/
mapCoord: Matrix;
/**
* Changes frame clamping
* Works with TilingSprite and Mesh
* Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders
* @default 0
*/
clampOffset: number;
/**
* Changes frame clamping
* Works with TilingSprite and Mesh
* Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
* @default 0.5
*/
clampMargin: number;
/**
* Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw.
* Calculated based on clampOffset.
*/
readonly uClampFrame: Float32Array;
/** Normalized clamp offset. Calculated based on clampOffset. */
readonly uClampOffset: Float32Array;
/**
* Tracks Texture frame changes.
* @ignore
*/
_updateID: number;
/**
* Tracks Texture frame changes.
* @protected
*/
protected _textureID: number;
protected _texture: Texture;
/**
* If texture size is the same as baseTexture.
* @default false
* @readonly
*/
isSimple: boolean;
/**
* @param texture - observed texture
* @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
*/
constructor(texture: Texture, clampMargin?: number);
/** Texture property. */
get texture(): Texture;
set texture(value: Texture);
/**
* Multiplies uvs array to transform
* @param uvs - mesh uvs
* @param [out=uvs] - output
* @returns - output
*/
multiplyUvs(uvs: Float32Array, out?: Float32Array): Float32Array;
/**
* Updates matrices if texture was changed
* @returns - whether or not it was updated
*/
update(): boolean;
}
/**
* Texture pool, used by FilterSystem and plugins.
*
* Stores collection of temporary pow2 or screen-sized renderTextures
*
* If you use custom RenderTexturePool for your filters, you can use methods
* `getFilterTexture` and `returnFilterTexture` same as in default pool
* @category rendering
* @advanced
*/
export declare class TexturePoolClass {
/** The default options for texture pool */
textureOptions: TextureSourceOptions;
/** The default texture style for the pool */
textureStyle: TextureStyle;
/**
* Allow renderTextures of the same size as screen, not just pow2
*
* Automatically sets to true after `setScreenSize`
* @default false
*/
enableFullScreen: boolean;
private _texturePool;
private _poolKeyHash;
/**
* @param textureOptions - options that will be passed to BaseRenderTexture constructor
* @param {SCALE_MODE} [textureOptions.scaleMode] - See {@link SCALE_MODE} for possible values.
*/
constructor(textureOptions?: TextureSourceOptions);
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
* @param antialias
*/
createTexture(pixelWidth: number, pixelHeight: number, antialias: boolean): Texture;
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param frameWidth - The minimum width of the render texture.
* @param frameHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @param antialias
* @returns The new render texture.
*/
getOptimalTexture(frameWidth: number, frameHeight: number, resolution: number, antialias: boolean): Texture;
/**
* Gets extra texture of the same size as input renderTexture
* @param texture - The texture to check what size it is.
* @param antialias - Whether to use antialias.
* @returns A texture that is a power of two
*/
getSameSizeTexture(texture: Texture, antialias?: boolean): Texture<TextureSource<any>>;
/**
* Place a render texture back into the pool. Optionally reset the style of the texture to the default texture style.
* useful if you modified the style of the texture after getting it from the pool.
* @param renderTexture - The renderTexture to free
* @param resetStyle - Whether to reset the style of the texture to the default texture style
*/
returnTexture(renderTexture: Texture, resetStyle?: boolean): void;
/**
* Clears the pool.
* @param destroyTextures - Destroy all stored textures.
*/
clear(destroyTextures?: boolean): void;
}
/**
* The default texture pool instance.
* @category rendering
* @advanced
*/
export declare const TexturePool: TexturePoolClass;
/**
* Stores a texture's frame in UV coordinates, in
* which everything lies in the rectangle `[(0,0), (1,0),
* (1,1), (0,1)]`.
*
* | Corner | Coordinates |
* |--------------|-------------|
* | Top-Left | `(x0,y0)` |
* | Top-Right | `(x1,y1)` |
* | Bottom-Right | `(x2,y2)` |
* | Bottom-Left | `(x3,y3)` |
* @protected
* @category rendering
* @advanced
*/
export declare class TextureUvs {
/** X-component of top-left corner `(x0,y0)`. */
x0: number;
/** Y-component of top-left corner `(x0,y0)`. */
y0: number;
/** X-component of top-right corner `(x1,y1)`. */
x1: number;
/** Y-component of top-right corner `(x1,y1)`. */
y1: number;
/** X-component of bottom-right corner `(x2,y2)`. */
x2: number;
/** Y-component of bottom-right corner `(x2,y2)`. */
y2: number;
/** X-component of bottom-left corner `(x3,y3)`. */
x3: number;
/** Y-component of bottom-right corner `(x3,y3)`. */
y3: number;
uvsFloat32: Float32Array;
constructor();
/**
* Sets the texture Uvs based on the given frame information.
* @protected
* @param frame - The frame of the texture
* @param baseFrame - The base frame of the texture
* @param rotate - Rotation of frame, see {@link groupD8}
*/
set(frame: Rectangle, baseFrame: Size, rotate: number): void;
toString(): string;
}
/**
* @param canvas
* @param options
* @internal
*/
export declare function getCanvasTexture(canvas: ICanvas, options?: CanvasSourceOptions): Texture<CanvasSource>;
/**
* @param canvas
* @internal
*/
export declare function hasCachedCanvasTexture(canvas: ICanvas): boolean;
/** @internal */
export declare function getSupportedCompressedTextureFormats(): Promise<TEXTURE_FORMATS[]>;
/** @internal */
export declare const nonCompressedFormats: TEXTURE_FORMATS[];
/** @internal */
export declare function getSupportedTextureFormats(): Promise<TEXTURE_FORMATS[]>;
/**
* The type of resource or options that can be used to create a texture source.
* This includes ImageResource, TextureSourceOptions, BufferSourceOptions, and CanvasSourceOptions.
* @category rendering
* @advanced
*/
export type TextureResourceOrOptions = ImageResource | TextureSourceOptions<ImageResource> | BufferSourceOptions | CanvasSourceOptions;
/**
* @param options
* @deprecated since v8.2.0
* @see TextureSource.from
* @category rendering
* @internal
*/
export declare function autoDetectSource(options?: TextureResourceOrOptions): TextureSource;
/**
* @param options
* @param skipCache
* @internal
*/
export declare function resourceToTexture(options?: TextureResourceOrOptions, skipCache?: boolean): Texture;
/**
* Helper function that creates a returns Texture based on the source you provide.
* The source should be loaded and ready to go. If not its best to grab the asset using Assets.
* @param id - String or Source to create texture from
* @param skipCache - Skip adding the texture to the cache
* @returns The texture based on the Id provided
* @category utils
* @internal
*/
export declare function textureFrom(id: TextureSourceLike, skipCache?: boolean): Texture;
/**
* @param value
* @param groupId
* @internal
*/
export declare function createIdFromString(value: string, groupId: string): number;
/**
* @param fn
* @internal
*/
export declare function parseFunctionBody(fn: (...args: any[]) => any): string;
/** @internal */
export interface ViewObserver {
onViewUpdate: () => void;
}
/**
* A view is something that is able to be rendered by the renderer.
* @category scene
* @advanced
*/
export interface View {
/** a unique id for this view */
readonly uid: number;
/** whether or not this view should be batched */
batched: boolean;
/**
* an identifier that is used to identify the type of system that will be used to render this renderable
* eg, 'sprite' will use the sprite system (based on the systems name
*/
readonly renderPipeId: string;
/** this is an int because it is packed directly into an attribute in the shader */
_roundPixels: 0 | 1;
/** @private */
_lastUsed: number;
/**
* Whether or not to round the x/y position of the object.
* @type {boolean}
*/
get roundPixels(): boolean;
/** if true, the view will have its position rounded to the nearest whole number */
set roundPixels(value: boolean);
/** this is the AABB rectangle bounds of the view in local untransformed space. */
bounds: BoundsData;
/** Checks if the point is within the view */
containsPoint: (point: Point) => boolean;
}
/**
* Options passed to the ViewSystem
* @category rendering
* @advanced
*/
export interface ViewSystemOptions {
/**
* The width of the screen.
* @default 800
*/
width?: number;
/**
* The height of the screen.
* @default 600
*/
height?: number;
/** The canvas to use as a view, optional. */
canvas?: ICanvas;
/**
* Alias for `canvas`.
* @deprecated since 8.0.0
*/
view?: ICanvas;
/**
* Resizes renderer view in CSS pixels to allow for resolutions other than 1.
*
* This is only supported for HTMLCanvasElement
* and will be ignored if the canvas is an OffscreenCanvas.
*/
autoDensity?: boolean;
/** The resolution / device pixel ratio of the renderer. */
resolution?: number;
/** Whether to enable anti-aliasing. This may affect performance. */
antialias?: boolean;
/** Whether to ensure the main view has can make use of the depth buffer. Always true for WebGL renderer. */
depth?: boolean;
}
/**
* Options for destroying the ViewSystem.
* @category rendering
* @advanced
*/
export interface ViewSystemDestroyOptions {
/** Whether to remove the view element from the DOM. Defaults to `false`. */
removeView?: boolean;
}
/**
* The view system manages the main canvas that is attached to the DOM.
* This main role is to deal with how the holding the view reference and dealing with how it is resized.
* @category rendering
* @advanced
*/
export declare class ViewSystem implements System<ViewSystemOptions, TypeOrBool<ViewSystemDestroyOptions>> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "view";
readonly priority: 0;
};
/** The default options for the view system. */
static defaultOptions: ViewSystemOptions;
/** The canvas element that everything is drawn to. */
canvas: ICanvas;
/** The texture that is used to draw the canvas to the screen. */
texture: Texture<CanvasSource>;
/**
* Whether CSS dimensions of canvas view should be resized to screen dimensions automatically.
* This is only supported for HTMLCanvasElement and will be ignored if the canvas is an OffscreenCanvas.
* @type {boolean}
*/
get autoDensity(): boolean;
set autoDensity(value: boolean);
/** Whether to enable anti-aliasing. This may affect performance. */
antialias: boolean;
/**
* Measurements of the screen. (0, 0, screenWidth, screenHeight).
*
* Its safe to use as filterArea or hitArea for the whole stage.
*/
screen: Rectangle;
/** The render target that the view is drawn to. */
renderTarget: RenderTarget;
/** The resolution / device pixel ratio of the renderer. */
get resolution(): number;
set resolution(value: number);
/**
* initiates the view system
* @param options - the options for the view
*/
init(options: ViewSystemOptions): void;
/**
* Resizes the screen and canvas to the specified dimensions.
* @param desiredScreenWidth - The new width of the screen.
* @param desiredScreenHeight - The new height of the screen.
* @param resolution
*/
resize(desiredScreenWidth: number, desiredScreenHeight: number, resolution: number): void;
/**
* Destroys this System and optionally removes the canvas from the dom.
* @param {options | false} options - The options for destroying the view, or "false".
* @example
* viewSystem.destroy();
* viewSystem.destroy(true);
* viewSystem.destroy({ removeView: true });
*/
destroy(options?: TypeOrBool<ViewSystemDestroyOptions>): void;
}
/**
* The WebGL adaptor for the render target system. Allows the Render Target System to be used with the WebGL renderer
* @category rendering
* @ignore
*/
export declare class GlRenderTargetAdaptor implements RenderTargetAdaptor<GlRenderTarget> {
private _renderTargetSystem;
private _renderer;
private _clearColorCache;
private _viewPortCache;
/** Pre-computed draw buffers arrays for MRT, indexed by color attachment count */
private _drawBuffersCache;
init(renderer: WebGLRenderer, renderTargetSystem: RenderTargetSystem<GlRenderTarget>): void;
contextChange(): void;
copyToTexture(sourceRenderSurfaceTexture: RenderTarget, destinationTexture: Texture, originSrc: {
x: number;
y: number;
}, size: {
width: number;
height: number;
}, originDest: {
x: number;
y: number;
}): Texture<TextureSource<any>>;
startRenderPass(renderTarget: RenderTarget, clear?: CLEAR_OR_BOOL, clearColor?: RgbaArray, viewport?: Rectangle): void;
finishRenderPass(renderTarget?: RenderTarget): void;
initGpuRenderTarget(renderTarget: RenderTarget): GlRenderTarget;
destroyGpuRenderTarget(gpuRenderTarget: GlRenderTarget): void;
clear(_renderTarget: RenderTarget, clear: CLEAR_OR_BOOL, clearColor?: RgbaArray): void;
resizeGpuRenderTarget(renderTarget: RenderTarget): void;
private _initColor;
private _resizeColor;
private _initStencil;
private _resizeStencil;
prerender(renderTarget: RenderTarget): void;
postrender(renderTarget: RenderTarget): void;
private _setDrawBuffers;
}
/**
* The WebGL adaptor for the render target system. Allows the Render Target System to be used with the WebGl renderer
* @category rendering
* @advanced
*/
export declare class GlRenderTargetSystem extends RenderTargetSystem<GlRenderTarget> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem
];
readonly name: "renderTarget";
};
adaptor: GlRenderTargetAdaptor;
constructor(renderer: WebGLRenderer);
}
/**
* Type definition for the global uniforms used in the renderer.
* This includes projection matrix, world transform matrix, world color, and resolution.
* @category rendering
* @advanced
*/
export type GlobalUniformGroup = UniformGroup<{
uProjectionMatrix: {
value: Matrix;
type: "mat3x3<f32>";
};
uWorldTransformMatrix: {
value: Matrix;
type: "mat3x3<f32>";
};
uWorldColorAlpha: {
value: Float32Array;
type: "vec4<f32>";
};
uResolution: {
value: number[];
type: "vec2<f32>";
};
}>;
/**
* Options for the global uniforms system.
* This includes size, projection matrix, world transform matrix, world color, and offset.
* @category rendering
* @advanced
*/
export interface GlobalUniformOptions {
size?: number[];
projectionMatrix?: Matrix;
worldTransformMatrix?: Matrix;
worldColor?: number;
offset?: PointData;
}
/**
* Data structure for the global uniforms used in the renderer.
* This includes the projection matrix, world transform matrix, world color, resolution, and bind group.
* @category rendering
* @advanced
*/
export interface GlobalUniformData {
projectionMatrix: Matrix;
worldTransformMatrix: Matrix;
worldColor: number;
resolution: number[];
offset: PointData;
bindGroup: BindGroup;
}
/** @internal */
export interface GlobalUniformRenderer {
renderTarget: GlRenderTargetSystem | GpuRenderTargetSystem;
renderPipes: Renderer["renderPipes"];
ubo: UboSystem;
type: RendererType;
}
/**
* System plugin to the renderer to manage global uniforms for the renderer.
* @category rendering
* @advanced
*/
export declare class GlobalUniformSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "globalUniforms";
};
private readonly _renderer;
private _stackIndex;
private _globalUniformDataStack;
private readonly _uniformsPool;
private readonly _activeUniforms;
private readonly _bindGroupPool;
private readonly _activeBindGroups;
private _currentGlobalUniformData;
constructor(renderer: GlobalUniformRenderer);
reset(): void;
start(options: GlobalUniformOptions): void;
bind({ size, projectionMatrix, worldTransformMatrix, worldColor, offset, }: GlobalUniformOptions): void;
push(options: GlobalUniformOptions): void;
pop(): void;
get bindGroup(): BindGroup;
get globalUniformData(): GlobalUniformData;
get uniformGroup(): UniformGroup<any>;
private _createUniforms;
destroy(): void;
}
/**
* Shared systems for the renderer.
* @category rendering
* @internal
*/
export declare const SharedSystems: (typeof BackgroundSystem | typeof GlobalUniformSystem | typeof HelloSystem | typeof ViewSystem | typeof RenderGroupSystem | typeof GCSystem | typeof TextureGCSystem | typeof GenerateTextureSystem | typeof ExtractSystem | typeof RendererInitHook | typeof RenderableGCSystem | typeof SchedulerSystem)[];
/**
* Shared render pipes for the renderer.
* @category rendering
* @internal
*/
export declare const SharedRenderPipes: (typeof BlendModePipe | typeof BatcherPipe | typeof SpritePipe | typeof RenderGroupPipe | typeof AlphaMaskPipe | typeof StencilMaskPipe | typeof ColorMaskPipe | typeof CustomRenderPipe)[];
/**
* Options for the shared systems of a renderer.
* @category rendering
* @advanced
*/
export interface SharedRendererOptions extends ExtractRendererOptions<typeof SharedSystems>, PixiMixins.RendererOptions {
/**
* Whether to stop PixiJS from dynamically importing default extensions for the renderer.
* It is false by default, and means PixiJS will load all the default extensions, based
* on the environment e.g browser/webworker.
* If you set this to true, then you will need to manually import the systems and extensions you need.
*
* e.g.
* ```js
* import 'accessibility';
* import 'app';
* import 'events';
* import 'spritesheet';
* import 'graphics';
* import 'mesh';
* import 'text';
* import 'text-bitmap';
* import 'text-html';
* import { autoDetectRenderer } from 'pixi.js';
*
* const renderer = await autoDetectRenderer({
* width: 800,
* height: 600,
* skipExtensionImports: true,
* });
* ```
* @default false
*/
skipExtensionImports?: boolean;
/**
* @default true
* @deprecated since 8.1.6
* @see `skipExtensionImports`
*/
manageImports?: boolean;
}
declare const DefaultWebGPUSystems: (typeof BackgroundSystem | typeof GlobalUniformSystem | typeof HelloSystem | typeof ViewSystem | typeof RenderGroupSystem | typeof GCSystem | typeof TextureGCSystem | typeof GenerateTextureSystem | typeof ExtractSystem | typeof RendererInitHook | typeof RenderableGCSystem | typeof SchedulerSystem | typeof GpuUboSystem | typeof GpuEncoderSystem | typeof GpuDeviceSystem | typeof GpuLimitsSystem | typeof GpuBufferSystem | typeof GpuTextureSystem | typeof GpuRenderTargetSystem | typeof GpuShaderSystem | typeof GpuStateSystem | typeof PipelineSystem | typeof GpuColorMaskSystem | typeof GpuStencilSystem | typeof BindGroupSystem)[];
declare const DefaultWebGPUPipes: (typeof BlendModePipe | typeof BatcherPipe | typeof SpritePipe | typeof RenderGroupPipe | typeof AlphaMaskPipe | typeof StencilMaskPipe | typeof ColorMaskPipe | typeof CustomRenderPipe | typeof GpuUniformBatchPipe)[];
/**
* The default WebGPU systems. These are the systems that are added by default to the WebGPURenderer.
* @category rendering
* @standard
* @interface
*/
export type WebGPUSystems = ExtractSystemTypes<typeof DefaultWebGPUSystems> & PixiMixins.RendererSystems & PixiMixins.WebGPUSystems;
/**
* The WebGPU renderer pipes. These are used to render the scene.
* @see {@link WebGPURenderer}
* @internal
*/
export type WebGPUPipes = ExtractSystemTypes<typeof DefaultWebGPUPipes> & PixiMixins.RendererPipes & PixiMixins.WebGPUPipes;
/**
* Options for WebGPURenderer.
* @category rendering
* @standard
*/
export interface WebGPUOptions extends SharedRendererOptions, ExtractRendererOptions<typeof DefaultWebGPUSystems>, PixiMixins.WebGPUOptions {
}
export interface WebGPURenderer<T extends ICanvas = HTMLCanvasElement> extends AbstractRenderer<WebGPUPipes, WebGPUOptions, T>, WebGPUSystems {
}
/**
* The WebGPU PixiJS Renderer. This renderer allows you to use the next-generation graphics API, WebGPU.
* ```ts
* // Create a new renderer
* const renderer = new WebGPURenderer();
* await renderer.init();
*
* // Add the renderer to the stage
* document.body.appendChild(renderer.canvas);
*
* // Create a new stage
* const stage = new Container();
*
* // Render the stage
* renderer.render(stage);
* ```
*
* You can use {@link autoDetectRenderer} to create a renderer that will automatically detect the best
* renderer for the environment.
* ```ts
* import { autoDetectRenderer } from 'pixi.js';
* // Create a new renderer
* const renderer = await autoDetectRenderer();
* ```
*
* The renderer is composed of systems that manage specific tasks. The following systems are added by default
* whenever you create a WebGPU renderer:
*
* | WebGPU Core Systems | Systems that are specific to the WebGL renderer |
* | ---------------------------------------- | ----------------------------------------------------------------------------- |
* | {@link GpuUboSystem} | This manages WebGPU uniform buffer objects feature for shaders |
* | {@link GpuEncoderSystem} | This manages the WebGPU command encoder |
* | {@link GpuDeviceSystem} | This manages the WebGPU Device and its extensions |
* | {@link GpuBufferSystem} | This manages buffers and their GPU resources, keeps everything in sync |
* | {@link GpuTextureSystem} | This manages textures and their GPU resources, keeps everything in sync |
* | {@link GpuRenderTargetSystem} | This manages what we render too. For example the screen, or another texture |
* | {@link GpuShaderSystem} | This manages shaders, programs that run on the GPU to output lovely pixels |
* | {@link GpuStateSystem} | This manages the state of the WebGPU Pipelines. eg the various flags that can be set blend modes / depthTesting etc |
* | {@link PipelineSystem} | This manages the WebGPU pipelines, used for rendering |
* | {@link GpuColorMaskSystem} | This manages the color mask. Used for color masking |
* | {@link GpuStencilSystem} | This manages the stencil buffer. Used primarily for masking |
* | {@link BindGroupSystem} | This manages the WebGPU bind groups. this is how data is bound to a shader when rendering |
*
* The breadth of the API surface provided by the renderer is contained within these systems.
* @category rendering
* @standard
* @property {GpuUboSystem} ubo - UboSystem instance.
* @property {GpuEncoderSystem} encoder - EncoderSystem instance.
* @property {GpuDeviceSystem} device - DeviceSystem instance.
* @property {GpuBufferSystem} buffer - BufferSystem instance.
* @property {GpuTextureSystem} texture - TextureSystem instance.
* @property {GpuRenderTargetSystem} renderTarget - RenderTargetSystem instance.
* @property {GpuShaderSystem} shader - ShaderSystem instance.
* @property {GpuStateSystem} state - StateSystem instance.
* @property {PipelineSystem} pipeline - PipelineSystem instance.
* @property {GpuColorMaskSystem} colorMask - ColorMaskSystem instance.
* @property {GpuStencilSystem} stencil - StencilSystem instance.
* @property {BindGroupSystem} bindGroup - BindGroupSystem instance.
* @extends AbstractRenderer
*/
export declare class WebGPURenderer<T extends ICanvas = HTMLCanvasElement> extends AbstractRenderer<WebGPUPipes, WebGPUOptions, T> implements WebGPUSystems {
/** The WebGPU Device. */
gpu: GPU$1;
constructor();
}
/**
* The GPU object.
* Contains the GPU adapter and device.
* @category rendering
* @advanced
*/
interface GPU$1 {
/** The GPU adapter */
adapter: GPUAdapter;
/** The GPU device */
device: GPUDevice;
}
/**
* Options for the WebGPU context.
* @property {GpuPowerPreference} [powerPreference=default] - An optional hint indicating what configuration of GPU
* is suitable for the WebGPU context, can be `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @property {boolean} [forceFallbackAdapter=false] - Force the use of the fallback adapter
* @category rendering
* @advanced
*/
export interface GpuContextOptions {
/**
* An optional hint indicating what configuration of GPU is suitable for the WebGPU context,
* can be `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @default undefined
*/
powerPreference?: GpuPowerPreference;
/**
* Force the use of the fallback adapter
* @default false
*/
forceFallbackAdapter: boolean;
/** Using shared device and adaptor from other engine */
gpu?: GPU$1;
}
/**
* System plugin to the renderer to manage the context.
* @class
* @category rendering
* @advanced
*/
export declare class GpuDeviceSystem implements System<GpuContextOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "device";
};
/** The default options for the GpuDeviceSystem. */
static defaultOptions: GpuContextOptions;
/** The GPU device */
gpu: GPU$1;
private _renderer;
private _initPromise;
/**
* @param {WebGPURenderer} renderer - The renderer this System works for.
*/
constructor(renderer: WebGPURenderer);
init(options: GpuContextOptions): Promise<void>;
/**
* Handle the context change event
* @param gpu
*/
protected contextChange(gpu: GPU$1): void;
/**
* Helper class to create a WebGL Context
* @param {object} options - An options object that gets passed in to the canvas element containing the
* context attributes
* @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext
* @returns {WebGLRenderingContext} the WebGL context
*/
private _createDeviceAndAdaptor;
destroy(): void;
}
/**
* Stores GPU-specific data for a Texture instance in WebGL context.
* @internal
*/
export declare class GPUTextureGpuData implements GPUData {
gpuTexture: GPUTexture;
textureView: GPUTextureView;
constructor(gpuTexture: GPUTexture);
/** Destroys this GPU data instance. */
destroy(): void;
}
/**
* The system that handles textures for the GPU.
* @category rendering
* @advanced
*/
export declare class GpuTextureSystem implements System, CanvasGenerator {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUSystem
];
readonly name: "texture";
};
protected CONTEXT_UID: number;
private _gpuSamplers;
private _bindGroupHash;
private readonly _uploads;
private _gpu;
private _mipmapGenerator?;
private readonly _renderer;
private readonly _managedTextures;
/**
* @deprecated since 8.15.0
*/
get managedTextures(): Readonly<TextureSource[]>;
constructor(renderer: WebGPURenderer);
protected contextChange(gpu: GPU$1): void;
/**
* Initializes a texture source, if it has already been initialized nothing will happen.
* @param source - The texture source to initialize.
* @returns The initialized texture source.
*/
initSource(source: TextureSource): GPUTexture;
private _initSource;
protected onSourceUpdate(source: TextureSource): void;
protected onUpdateMipmaps(source: TextureSource): void;
protected onSourceUnload(source: TextureSource): void;
protected onSourceResize(source: TextureSource): void;
private _initSampler;
getGpuSampler(sampler: TextureStyle): GPUSampler;
getGpuSource(source: TextureSource): GPUTexture;
/**
* this returns s bind group for a specific texture, the bind group contains
* - the texture source
* - the texture style
* - the texture matrix
* This is cached so the bind group should only be created once per texture
* @param texture - the texture you want the bindgroup for
* @returns the bind group for the texture
*/
getTextureBindGroup(texture: Texture): BindGroup;
private _createTextureBindGroup;
getTextureView(texture: BindableTexture): GPUTextureView;
generateCanvas(texture: Texture): ICanvas;
getPixels(texture: Texture): GetPixelsOutput;
destroy(): void;
}
/**
* options for creating a new TextureSource
* @category rendering
* @advanced
*/
export interface TextureSourceOptions<T extends Record<string, any> = any> extends TextureStyleOptions {
/**
* the resource that will be uploaded to the GPU. This is where we get our pixels from
* eg an ImageBimt / Canvas / Video etc
*/
resource?: T;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
width?: number;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
height?: number;
/** the resolution of the texture. */
resolution?: number;
/** the format that the texture data has */
format?: TEXTURE_FORMATS;
/**
* Used by internal textures
* @ignore
*/
sampleCount?: number;
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
antialias?: boolean;
/** how many dimensions does this texture have? currently v8 only supports 2d */
dimensions?: TEXTURE_DIMENSIONS;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
mipLevelCount?: number;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
autoGenerateMipmaps?: boolean;
/** the alpha mode of the texture */
alphaMode?: ALPHA_MODES;
/** optional label, can be used for debugging */
label?: string;
/** If true, the Garbage Collector will unload this texture if it is not used after a period of time */
autoGarbageCollect?: boolean;
/** Used by RenderTexture.create to allow resizing. Not used by TextureSource itself. */
dynamic?: boolean;
}
/**
* A TextureSource stores the information that represents an image.
* All textures have require TextureSource, which contains information about the source.
* Therefore you can have many textures all using a single TextureSource (eg a sprite sheet)
*
* This is an class is extended depending on the source of the texture.
* Eg if you are using an an image as your resource, then an ImageSource is used.
* @category rendering
* @advanced
*/
export declare class TextureSource<T extends Record<string, any> = any> extends EventEmitter<{
change: BindResource;
update: TextureSource;
unload: TextureSource;
destroy: TextureSource;
resize: TextureSource;
styleChange: TextureSource;
updateMipmaps: TextureSource;
error: Error;
}> implements BindResource, GPUDataOwner, GCable {
protected readonly options: TextureSourceOptions<T>;
/** The default options used when creating a new TextureSource. override these to add your own defaults */
static defaultOptions: TextureSourceOptions;
/** @internal */
_gpuData: Record<number, GlTexture | GPUTextureGpuData>;
/** GC tracking data, undefined if not being tracked */
_gcData?: GCData;
/** @internal */
_gcLastUsed: number;
/** unique id for this Texture source */
readonly uid: number;
/** optional label, can be used for debugging */
label: string;
/**
* The resource type used by this TextureSource. This is used by the bind groups to determine
* how to handle this resource.
* @internal
*/
readonly _resourceType = "textureSource";
/**
* i unique resource id, used by the bind group systems.
* This can change if the texture is resized or its resource changes
* @internal
*/
_resourceId: number;
/**
* this is how the backends know how to upload this texture to the GPU
* It changes depending on the resource type. Classes that extend TextureSource
* should override this property.
* @internal
*/
uploadMethodId: string;
/** @internal */
_resolution: number;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
pixelWidth: number;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
pixelHeight: number;
/**
* the width of this texture source, accounting for resolution
* eg pixelWidth 200, resolution 2, then width will be 100
*/
width: number;
/**
* the height of this texture source, accounting for resolution
* eg pixelHeight 200, resolution 2, then height will be 100
*/
height: number;
/**
* the resource that will be uploaded to the GPU. This is where we get our pixels from
* eg an ImageBimt / Canvas / Video etc
*/
resource: T;
/**
* The number of samples of a multisample texture. This is always 1 for non-multisample textures.
* To enable multisample for a texture, set antialias to true
* @internal
*/
sampleCount: number;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
mipLevelCount: number;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
autoGenerateMipmaps: boolean;
/** the format that the texture data has */
format: TEXTURE_FORMATS;
/** how many dimensions does this texture have? currently v8 only supports 2d */
dimension: TEXTURE_DIMENSIONS;
/** the alpha mode of the texture */
alphaMode: ALPHA_MODES;
private _style;
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
antialias: boolean;
/**
* Has the source been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* Used by automatic texture Garbage Collection, stores last GC tick when it was bound
* @protected
*/
_touched: number;
/**
* Used by the batcher to build texture batches. faster to have the variable here!
* @protected
*/
_batchTick: number;
/**
* A temporary batch location for the texture batching. Here for performance reasons only!
* @protected
*/
_textureBindLocation: number;
isPowerOfTwo: boolean;
/** If true, the Garbage Collector will unload this texture if it is not used after a period of time */
autoGarbageCollect: boolean;
/**
* used internally to know where a texture came from. Usually assigned by the asset loader!
* @ignore
*/
_sourceOrigin: string;
/**
* @param options - options for creating a new TextureSource
*/
constructor(options?: TextureSourceOptions<T>);
/** returns itself */
get source(): TextureSource;
/** the style of the texture */
get style(): TextureStyle;
set style(value: TextureStyle);
/** Specifies the maximum anisotropy value clamp used by the sampler. */
set maxAnisotropy(value: number);
get maxAnisotropy(): number;
/** setting this will set wrapModeU, wrapModeV and wrapModeW all at once! */
get addressMode(): WRAP_MODE;
set addressMode(value: WRAP_MODE);
/** setting this will set wrapModeU, wrapModeV and wrapModeW all at once! */
get repeatMode(): WRAP_MODE;
set repeatMode(value: WRAP_MODE);
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
get magFilter(): SCALE_MODE;
set magFilter(value: SCALE_MODE);
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
get minFilter(): SCALE_MODE;
set minFilter(value: SCALE_MODE);
/** Specifies behavior for sampling between mipmap levels. */
get mipmapFilter(): SCALE_MODE;
set mipmapFilter(value: SCALE_MODE);
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMinClamp(): number;
set lodMinClamp(value: number);
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMaxClamp(): number;
set lodMaxClamp(value: number);
private _onStyleChange;
/** call this if you have modified the texture outside of the constructor */
update(): void;
/** Destroys this texture source */
destroy(): void;
/**
* This will unload the Texture source from the GPU. This will free up the GPU memory
* As soon as it is required fore rendering, it will be re-uploaded.
*/
unload(): void;
/** the width of the resource. This is the REAL pure number, not accounting resolution */
get resourceWidth(): number;
/** the height of the resource. This is the REAL pure number, not accounting resolution */
get resourceHeight(): number;
/**
* the resolution of the texture. Changing this number, will not change the number of pixels in the actual texture
* but will the size of the texture when rendered.
*
* changing the resolution of this texture to 2 for example will make it appear twice as small when rendered (as pixel
* density will have increased)
*/
get resolution(): number;
set resolution(resolution: number);
/**
* Resize the texture, this is handy if you want to use the texture as a render texture
* @param width - the new width of the texture
* @param height - the new height of the texture
* @param resolution - the new resolution of the texture
* @returns - if the texture was resized
*/
resize(width?: number, height?: number, resolution?: number): boolean;
/**
* Lets the renderer know that this texture has been updated and its mipmaps should be re-generated.
* This is only important for RenderTexture instances, as standard Texture instances will have their
* mipmaps generated on upload. You should call this method after you make any change to the texture
*
* The reason for this is is can be quite expensive to update mipmaps for a texture. So by default,
* We want you, the developer to specify when this action should happen.
*
* Generally you don't want to have mipmaps generated on Render targets that are changed every frame,
*/
updateMipmaps(): void;
set wrapMode(value: WRAP_MODE);
get wrapMode(): WRAP_MODE;
set scaleMode(value: SCALE_MODE);
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode(): SCALE_MODE;
/**
* Refresh check for isPowerOfTwo texture based on size
* @private
*/
protected _refreshPOT(): void;
static test(_resource: any): any;
/**
* A helper function that creates a new TextureSource based on the resource you provide.
* @param resource - The resource to create the texture source from.
*/
static from: (resource: TextureResourceOrOptions) => TextureSource;
}
/**
* Options for creating a BufferImageSource.
* @category rendering
* @advanced
*/
export interface BufferSourceOptions extends TextureSourceOptions<TypedArray | ArrayBuffer> {
width: number;
height: number;
}
/**
* A texture source that uses a TypedArray or ArrayBuffer as its resource.
* It automatically determines the format based on the type of TypedArray provided.
* @category rendering
* @advanced
*/
export declare class BufferImageSource extends TextureSource<TypedArray | ArrayBuffer> {
static extension: ExtensionMetadata;
uploadMethodId: string;
constructor(options: BufferSourceOptions);
static test(resource: any): resource is TypedArray | ArrayBuffer;
}
/**
* Stores the width of the non-scalable borders, for example when used with {@link NineSlicePlane} texture.
* @category rendering
* @advanced
*/
export interface TextureBorders {
/** left border in pixels */
left: number;
/** top border in pixels */
top: number;
/** right border in pixels */
right: number;
/** bottom border in pixels */
bottom: number;
}
/**
* The UVs data structure for a texture.
* @category rendering
* @advanced
*/
export type UVs = {
x0: number;
y0: number;
x1: number;
y1: number;
x2: number;
y2: number;
x3: number;
y3: number;
};
/**
* The options that can be passed to a new Texture
* @category rendering
* @standard
*/
export interface TextureOptions<TextureSourceType extends TextureSource = TextureSource> {
/** the underlying texture data that this texture will use */
source?: TextureSourceType;
/** optional label, for debugging */
label?: string;
/** The rectangle frame of the texture to show */
frame?: Rectangle;
/** The area of original texture */
orig?: Rectangle;
/** Trimmed rectangle of original texture */
trim?: Rectangle;
/** Default anchor point used for sprite placement / rotation */
defaultAnchor?: {
x: number;
y: number;
};
/** Default borders used for 9-slice scaling {@link NineSlicePlane}*/
defaultBorders?: TextureBorders;
/** indicates how the texture was rotated by texture packer. See {@link groupD8} */
rotate?: number;
/**
* Set to true if you plan on modifying this texture's frame, UVs, or swapping its source at runtime.
* This is false by default as it improves performance. Generally, it's recommended to create new
* textures and swap those rather than modifying an existing texture's properties unless you are
* working with a dynamic frames.
* Not setting this to true when modifying the texture can lead to visual artifacts.
*
* If this is false and you modify the texture, you can manually update the sprite's texture by calling
* `sprite.onViewUpdate()`.
*/
dynamic?: boolean;
}
/**
* A texture that can be bound to a shader as it has a texture source.
* @category rendering
* @advanced
*/
export interface BindableTexture {
source: TextureSource;
}
/**
* A texture source can be a string, an image, a video, a canvas, or a texture resource.
* @category rendering
* @advanced
* @see {@link TextureSource}
* @see {@link TextureResourceOrOptions}
* @see {@link Texture.from}
*/
export type TextureSourceLike = TextureSource | TextureResourceOrOptions | string;
/**
* A texture stores the information that represents an image or part of an image.
*
* A texture must have a loaded resource passed to it to work. It does not contain any
* loading mechanisms.
*
* The Assets class can be used to load a texture from a file. This is the recommended
* way as it will handle the loading and caching for you.
*
* ```js
*
* const texture = await Assets.load('assets/image.png');
*
* // once Assets has loaded the image it will be available via the from method
* const sameTexture = Texture.from('assets/image.png');
* // another way to access the texture once loaded
* const sameAgainTexture = Assets.get('assets/image.png');
*
* const sprite1 = new Sprite(texture);
*
* ```
*
* It cannot be added to the display list directly; instead use it as the texture for a Sprite.
* If no frame is provided for a texture, then the whole image is used.
*
* You can directly create a texture from an image and then reuse it multiple times like this :
*
* ```js
* import { Sprite, Texture } from 'pixi.js';
*
* const texture = await Assets.load('assets/image.png');
* const sprite1 = new Sprite(texture);
* const sprite2 = new Sprite(texture);
* ```
*
* If you didn't pass the texture frame to constructor, it enables `noFrame` mode:
* it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture.
* @category rendering
* @class
* @standard
*/
export declare class Texture<TextureSourceType extends TextureSource = TextureSource> extends EventEmitter<{
update: Texture;
destroy: Texture;
}> implements BindableTexture {
/**
* Helper function that creates a returns Texture based on the source you provide.
* The source should be loaded and ready to go. If not its best to grab the asset using Assets.
* @param id - String or Source to create texture from
* @param skipCache - Skip adding the texture to the cache
* @returns The texture based on the Id provided
*/
static from: (id: TextureSourceLike, skipCache?: boolean) => Texture;
/** label used for debugging */
label?: string;
/** unique id for this texture */
readonly uid: number;
/**
* Has the texture been destroyed?
* @readonly
*/
destroyed: boolean;
/** @internal */
_source: TextureSourceType;
/**
* Indicates whether the texture is rotated inside the atlas
* set to 2 to compensate for texture packer rotation
* set to 6 to compensate for spine packer rotation
* can be used to rotate or mirror sprites
* See {@link groupD8} for explanation
*/
readonly rotate: number;
/** A uvs object based on the given frame and the texture source */
readonly uvs: UVs;
/**
* Anchor point that is used as default if sprite is created with this texture.
* Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point.
* @default {0,0}
*/
readonly defaultAnchor?: {
x: number;
y: number;
};
/**
* Default width of the non-scalable border that is used if 9-slice plane is created with this texture.
* @since 7.2.0
* @see NineSliceSprite
*/
readonly defaultBorders?: TextureBorders;
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*/
readonly frame: Rectangle;
/** This is the area of original texture, before it was put in atlas. */
readonly orig: Rectangle;
/**
* This is the trimmed area of original texture, before it was put in atlas
* Please call `updateUvs()` after you change coordinates of `trim` manually.
*/
readonly trim: Rectangle;
/**
* Does this Texture have any frame data assigned to it?
*
* This mode is enabled automatically if no frame was passed inside constructor.
*
* In this mode texture is subscribed to baseTexture events, and fires `update` on any change.
*
* Beware, after loading or resize of baseTexture event can fired two times!
* If you want more control, subscribe on baseTexture itself.
* @example
* texture.on('update', () => {});
*/
noFrame: boolean;
/**
* Set to true if you plan on modifying the uvs of this texture.
* When this is the case, sprites and other objects using the texture will
* make sure to listen for changes to the uvs and update their vertices accordingly.
*/
dynamic: boolean;
private _textureMatrix;
/** is it a texture? yes! used for type checking */
readonly isTexture = true;
/**
* @param {TextureOptions} options - Options for the texture
*/
constructor({ source, label, frame, orig, trim, defaultAnchor, defaultBorders, rotate, dynamic }?: TextureOptions<TextureSourceType>);
set source(value: TextureSourceType);
/** the underlying source of the texture (equivalent of baseTexture in v7) */
get source(): TextureSourceType;
/** returns a TextureMatrix instance for this texture. By default, that object is not created because its heavy. */
get textureMatrix(): TextureMatrix;
/** The width of the Texture in pixels. */
get width(): number;
/** The height of the Texture in pixels. */
get height(): number;
/** Call this function when you have modified the frame of this texture. */
updateUvs(): void;
/**
* Destroys this texture
* @param destroySource - Destroy the source when the texture is destroyed.
*/
destroy(destroySource?: boolean): void;
/**
* Call this if you have modified the `texture outside` of the constructor.
*
* If you have modified this texture's source, you must separately call `texture.source.update()` to see those changes.
*/
update(): void;
/** @deprecated since 8.0.0 */
get baseTexture(): TextureSource;
/** an Empty Texture used internally by the engine */
static EMPTY: Texture;
/** a White texture used internally by the engine */
static WHITE: Texture<BufferImageSource>;
}
/**
* A render texture, extends `Texture`.
* @see {@link Texture}
* @category rendering
* @advanced
*/
export declare class RenderTexture extends Texture {
/**
* Creates a RenderTexture. Pass `dynamic: true` in options to allow resizing after creation.
* @param options - Options for the RenderTexture, including width, height, and dynamic.
* @returns A new RenderTexture instance.
* @example
* const rt = RenderTexture.create({ width: 100, height: 100, dynamic: true });
* rt.resize(500, 500);
*/
static create(options: TextureSourceOptions): RenderTexture;
/**
* Resizes the render texture.
* @param width - The new width of the render texture.
* @param height - The new height of the render texture.
* @param resolution - The new resolution of the render texture.
* @returns This texture.
*/
resize(width: number, height: number, resolution?: number): this;
}
/**
* Options for generating a texture source.
* @category rendering
* @advanced
* @interface
*/
export type GenerateTextureSourceOptions = Omit<TextureSourceOptions, "resource" | "width" | "height" | "resolution">;
/**
* Options for generating a texture from a container.
* Used to create reusable textures from display objects, which can improve performance
* when the same content needs to be rendered multiple times.
* @example
* ```ts
* // Basic texture generation
* const sprite = new Sprite(texture);
* const generatedTexture = renderer.generateTexture({
* target: sprite
* });
*
* // Generate with custom region and resolution
* const texture = renderer.generateTexture({
* target: container,
* frame: new Rectangle(0, 0, 100, 100),
* resolution: 2
* });
*
* // Generate with background color and anti-aliasing
* const highQualityTexture = renderer.generateTexture({
* target: graphics,
* clearColor: '#ff0000',
* antialias: true,
* textureSourceOptions: {
* scaleMode: 'linear'
* }
* });
* ```
* @category rendering
* @advanced
*/
export type GenerateTextureOptions = {
/**
* The container to generate the texture from.
* This can be any display object like Sprite, Container, or Graphics.
* @example
* ```ts
* const graphics = new Graphics()
* .circle(0, 0, 50)
* .fill('red');
*
* const texture = renderer.generateTexture({
* target: graphics
* });
* ```
*/
target: Container;
/**
* The region of the container that should be rendered.
* If not specified, defaults to the local bounds of the container.
* @example
* ```ts
* // Extract only a portion of the container
* const texture = renderer.generateTexture({
* target: container,
* frame: new Rectangle(10, 10, 100, 100)
* });
* ```
*/
frame?: Rectangle;
/**
* The resolution of the texture being generated.
* Higher values create sharper textures at the cost of memory.
* @default renderer.resolution
* @example
* ```ts
* // Generate a high-resolution texture
* const hiResTexture = renderer.generateTexture({
* target: sprite,
* resolution: 2 // 2x resolution
* });
* ```
*/
resolution?: number;
/**
* The color used to clear the texture before rendering.
* Can be a hex number, string, or array of numbers.
* @example
* ```ts
* // Clear with red background
* const texture = renderer.generateTexture({
* target: sprite,
* clearColor: '#ff0000'
* });
*
* // Clear with semi-transparent black
* const texture = renderer.generateTexture({
* target: sprite,
* clearColor: [0, 0, 0, 0.5]
* });
* ```
*/
clearColor?: ColorSource;
/**
* Whether to enable anti-aliasing. This may affect performance.
* @default false
* @example
* ```ts
* // Generate a smooth texture
* const texture = renderer.generateTexture({
* target: graphics,
* antialias: true
* });
* ```
*/
antialias?: boolean;
/**
* Advanced options for configuring the texture source.
* Controls texture properties like scale mode and filtering.
* @advanced
* @example
* ```ts
* const texture = renderer.generateTexture({
* target: sprite,
* textureSourceOptions: {
* scaleMode: 'linear',
* }
* });
* ```
*/
textureSourceOptions?: GenerateTextureSourceOptions;
};
/**
* System that manages the generation of textures from display objects in the renderer.
* This system is responsible for creating reusable textures from containers, sprites, and other display objects.
* Available through `renderer.textureGenerator`.
* @example
* ```ts
* import { Application, Sprite, Graphics } from 'pixi.js';
*
* const app = new Application();
* await app.init();
*
* // Create a complex display object
* const container = new Container();
*
* const graphics = new Graphics()
* .circle(0, 0, 50)
* .fill('red');
*
* const sprite = new Sprite(texture);
* sprite.x = 100;
*
* container.addChild(graphics, sprite);
*
* // Generate a texture from the container
* const generatedTexture = app.renderer.textureGenerator.generateTexture({
* target: container,
* resolution: 2,
* antialias: true
* });
*
* // Use the generated texture
* const newSprite = new Sprite(generatedTexture);
* app.stage.addChild(newSprite);
*
* // Clean up when done
* generatedTexture.destroy(true);
* ```
*
* Features:
* - Convert any display object to a texture
* - Support for custom regions and resolutions
* - Anti-aliasing support
* - Background color configuration
* - Texture source options customization
*
* Common Use Cases:
* - Creating texture atlases dynamically
* - Caching complex container content
* - Generating thumbnails
* - Creating reusable textures from rendered content
*
* Performance Considerations:
* - Generating textures is relatively expensive
* - Cache results when possible
* - Be mindful of resolution and size
* - Clean up unused textures
* @see {@link GenerateTextureOptions} For detailed texture generation options
* @see {@link AbstractRenderer.generateTexture} For the main renderer method
* @see {@link RenderTexture} For the resulting texture type
* @category rendering
* @standard
*/
export declare class GenerateTextureSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "textureGenerator";
};
private readonly _renderer;
constructor(renderer: Renderer);
/**
* Creates a texture from a display object that can be used for creating sprites and other textures.
* This is particularly useful for optimizing performance when a complex container needs to be reused.
* @param options - Generate texture options or a container to convert to texture
* @returns A new RenderTexture containing the rendered display object
* @example
* ```ts
* // Basic usage with a container
* const container = new Container();
* container.addChild(
* new Graphics()
* .circle(0, 0, 50)
* .fill('red')
* );
*
* const texture = renderer.textureGenerator.generateTexture(container);
*
* // Advanced usage with options
* const texture = renderer.textureGenerator.generateTexture({
* target: container,
* frame: new Rectangle(0, 0, 100, 100), // Specific region
* resolution: 2, // High DPI
* clearColor: '#ff0000', // Red background
* antialias: true // Smooth edges
* });
*
* // Create a sprite from the generated texture
* const sprite = new Sprite(texture);
*
* // Clean up when done
* texture.destroy(true);
* ```
* @see {@link GenerateTextureOptions} For detailed texture generation options
* @see {@link RenderTexture} For the type of texture created
* @category rendering
*/
generateTexture(options: GenerateTextureOptions | Container): RenderTexture;
destroy(): void;
}
/**
* The configuration for the renderer.
* This is used to define the systems and render pipes that will be used by the renderer.
* @category rendering
* @advanced
*/
export interface RendererConfig {
type: number;
name: string;
runners?: string[];
systems: {
name: string;
value: SystemConstructor;
}[];
renderPipes: {
name: string;
value: PipeConstructor;
}[];
renderPipeAdaptors: {
name: string;
value: any;
}[];
}
/**
* The options for rendering a view.
* @category rendering
* @standard
*/
export interface RenderOptions extends ClearOptions {
/** The container to render. */
container: Container;
/** the transform to apply to the container. */
transform?: Matrix;
}
/**
* The options for clearing the render target.
* @category rendering
* @advanced
*/
export interface ClearOptions {
/**
* The render target to render. if this target is a canvas and you are using the WebGL renderer,
* please ensure you have set `multiView` to `true` on renderer.
*/
target?: RenderSurface;
/** The color to clear with. */
clearColor?: ColorSource;
/** The clear mode to use. */
clear?: CLEAR_OR_BOOL;
}
/**
* Options for destroying the renderer.
* This can be a boolean or an object.
* @category rendering
* @standard
*/
export type RendererDestroyOptions = TypeOrBool<ViewSystemDestroyOptions & {
/** Whether to clean up global resource pools/caches */
releaseGlobalResources?: boolean;
}>;
declare const defaultRunners: readonly [
"init",
"destroy",
"contextChange",
"resolutionChange",
"resetState",
"renderEnd",
"renderStart",
"render",
"update",
"postrender",
"prerender"
];
type DefaultRunners = typeof defaultRunners[number];
type Runners = {
[key in DefaultRunners]: SystemRunner;
} & {
[K: ({} & string) | ({} & symbol)]: SystemRunner;
};
/**
* The base class for a PixiJS Renderer. It contains the shared logic for all renderers.
*
* You should not use this class directly, but instead use {@link WebGLRenderer}
* or {@link WebGPURenderer}.
* Alternatively, you can also use {@link autoDetectRenderer} if you want us to
* determine the best renderer for you.
*
* The renderer is composed of systems that manage specific tasks. The following systems are added by default
* whenever you create a renderer:
*
*
* | Generic Systems | Systems that manage functionality that all renderer types share |
* | ------------------------------------ | ----------------------------------------------------------------------------- |
* | {@link ViewSystem} | This manages the main view of the renderer usually a Canvas |
* | {@link BackgroundSystem} | This manages the main views background color and alpha |
* | {@link EventSystem} | This manages UI events. |
* | {@link AccessibilitySystem} | This manages accessibility features. Requires `import 'pixi.js/accessibility'`|
*
* | Core Systems | Provide an optimised, easy to use API to work with WebGL/WebGPU |
* | ------------------------------------ | ----------------------------------------------------------------------------- |
* | {@link GlobalUniformSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. |
* | {@link TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. |
*
* | PixiJS High-Level Systems | Set of specific systems designed to work with PixiJS objects |
* | ------------------------------------ | ----------------------------------------------------------------------------- |
* | {@link HelloSystem} | Says hello, buy printing out the pixi version into the console log (along with the renderer type) |
* | {@link GenerateTextureSystem} | This adds the ability to generate textures from any Container |
* | {@link FilterSystem} | This manages the filtering pipeline for post-processing effects. |
* | {@link PrepareSystem} | This manages uploading assets to the GPU. Requires `import 'pixi.js/prepare'`|
* | {@link ExtractSystem} | This extracts image data from display objects. |
*
* The breadth of the API surface provided by the renderer is contained within these systems.
* @abstract
* @category rendering
* @advanced
* @property {HelloSystem} hello - HelloSystem instance.
* @property {TextureGCSystem} textureGC - TextureGCSystem instance.
* @property {FilterSystem} filter - FilterSystem instance.
* @property {GlobalUniformSystem} globalUniforms - GlobalUniformSystem instance.
* @property {TextureSystem} texture - TextureSystem instance.
* @property {EventSystem} events - EventSystem instance.
* @property {ExtractSystem} extract - ExtractSystem instance. Requires `import 'pixi.js/extract'`.
* @property {PrepareSystem} prepare - PrepareSystem instance. Requires `import 'pixi.js/prepare'`.
* @property {AccessibilitySystem} accessibility - AccessibilitySystem instance. Requires `import 'pixi.js/accessibility'`.
*/
export declare class AbstractRenderer<PIPES, OPTIONS extends SharedRendererOptions, CANVAS extends ICanvas = HTMLCanvasElement> extends EventEmitter<{
resize: [
screenWidth: number,
screenHeight: number,
resolution: number
];
}> {
/** The default options for the renderer. */
static defaultOptions: {
/**
* Default resolution / device pixel ratio of the renderer.
* @default 1
*/
resolution: number;
/**
* Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported`
* function. If set to true, a WebGL renderer can fail to be created if the browser thinks there could be
* performance issues when using WebGL.
*
* In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many
* scenarios as possible. However, some users may have a poor experience, for example, if a user has a gpu or
* driver version blacklisted by the
* browser.
*
* If your application requires high performance rendering, you may wish to set this to false.
* We recommend one of two options if you decide to set this flag to false:
*
* 1: Use the Canvas renderer as a fallback in case high performance WebGL is
* not supported.
*
* 2: Call `isWebGLSupported` (which if found in the utils package) in your code before attempting to create a
* PixiJS renderer, and show an error message to the user if the function returns false, explaining that their
* device & browser combination does not support high performance WebGL.
* This is a much better strategy than trying to create a PixiJS renderer and finding it then fails.
* @default false
*/
failIfMajorPerformanceCaveat: boolean;
/**
* Should round pixels be forced when rendering?
* @default false
*/
roundPixels: boolean;
};
/** @internal */
readonly type: number;
/** The name of the renderer. */
readonly name: string;
/** The current tick of the renderer. */
tick: number;
/** @internal */
readonly uid: number;
/** @internal */
_roundPixels: 0 | 1;
/** @internal */
readonly runners: Runners;
/** @internal */
readonly renderPipes: PIPES;
/** The view system manages the main canvas that is attached to the DOM */
view: ViewSystem;
/** The background system manages the background color and alpha of the main view. */
background: BackgroundSystem;
/** System that manages the generation of textures from the renderer */
textureGenerator: GenerateTextureSystem;
protected _initOptions: OPTIONS;
protected config: RendererConfig;
private _systemsHash;
private _lastObjectRendered;
/**
* Set up a system with a collection of SystemClasses and runners.
* Systems are attached dynamically to this class when added.
* @param config - the config for the system manager
*/
constructor(config: RendererConfig);
/**
* Initialize the renderer.
* @param options - The options to use to create the renderer.
*/
init(options?: Partial<OPTIONS>): Promise<void>;
/**
* Renders the object to its view.
* @param options - The options to render with.
* @param options.container - The container to render.
* @param [options.target] - The target to render to.
*/
render(options: RenderOptions | Container): void;
/** @deprecated since 8.0.0 */
render(container: Container, options: {
renderTexture: any;
}): void;
/**
* Resizes the WebGL view to the specified width and height.
* @param desiredScreenWidth - The desired width of the screen.
* @param desiredScreenHeight - The desired height of the screen.
* @param resolution - The resolution / device pixel ratio of the renderer.
*/
resize(desiredScreenWidth: number, desiredScreenHeight: number, resolution?: number): void;
/**
* Clears the render target.
* @param options - The options to use when clearing the render target.
* @param options.target - The render target to clear.
* @param options.clearColor - The color to clear with.
* @param options.clear - The clear mode to use.
* @advanced
*/
clear(options?: ClearOptions): void;
/** The resolution / device pixel ratio of the renderer. */
get resolution(): number;
set resolution(value: number);
/**
* Same as view.width, actual number of pixels in the canvas by horizontal.
* @type {number}
* @readonly
* @default 800
*/
get width(): number;
/**
* Same as view.height, actual number of pixels in the canvas by vertical.
* @default 600
*/
get height(): number;
/**
* The canvas element that everything is drawn to.
* @type {environment.ICanvas}
*/
get canvas(): CANVAS;
/**
* the last object rendered by the renderer. Useful for other plugins like interaction managers
* @readonly
*/
get lastObjectRendered(): Container;
/**
* Flag if we are rendering to the screen vs renderTexture
* @readonly
* @default true
*/
get renderingToScreen(): boolean;
/**
* Measurements of the screen. (0, 0, screenWidth, screenHeight).
*
* Its safe to use as filterArea or hitArea for the whole stage.
*/
get screen(): Rectangle;
/**
* Create a bunch of runners based of a collection of ids
* @param runnerIds - the runner ids to add
*/
private _addRunners;
private _addSystems;
/**
* Add a new system to the renderer.
* @param ClassRef - Class reference
* @param name - Property name for system, if not specified
* will use a static `name` property on the class itself. This
* name will be assigned as s property on the Renderer so make
* sure it doesn't collide with properties on Renderer.
* @returns Return instance of renderer
*/
private _addSystem;
private _addPipes;
destroy(options?: RendererDestroyOptions): void;
/**
* Generate a texture from a container.
* @param options - options or container target to use when generating the texture
* @returns a texture
*/
generateTexture(options: GenerateTextureOptions | Container): Texture;
/**
* Whether the renderer will round coordinates to whole pixels when rendering.
* Can be overridden on a per scene item basis.
*/
get roundPixels(): boolean;
/**
* Overridable function by `pixi.js/unsafe-eval` to silence
* throwing an error if platform doesn't support unsafe-evals.
* @private
* @ignore
*/
_unsafeEvalCheck(): void;
/**
* Resets the rendering state of the renderer.
* This is useful when you want to use the WebGL context directly and need to ensure PixiJS's internal state
* stays synchronized. When modifying the WebGL context state externally, calling this method before the next Pixi
* render will reset all internal caches and ensure it executes correctly.
*
* This is particularly useful when combining PixiJS with other rendering engines like Three.js:
* ```js
* // Reset Three.js state
* threeRenderer.resetState();
*
* // Render a Three.js scene
* threeRenderer.render(threeScene, threeCamera);
*
* // Reset PixiJS state since Three.js modified the WebGL context
* pixiRenderer.resetState();
*
* // Now render Pixi content
* pixiRenderer.render(pixiScene);
* ```
* @advanced
*/
resetState(): void;
}
declare const DefaultWebGLSystems: (typeof BackgroundSystem | typeof GlobalUniformSystem | typeof HelloSystem | typeof ViewSystem | typeof RenderGroupSystem | typeof GCSystem | typeof TextureGCSystem | typeof GenerateTextureSystem | typeof ExtractSystem | typeof RendererInitHook | typeof RenderableGCSystem | typeof SchedulerSystem | typeof GlUboSystem | typeof GlBackBufferSystem | typeof GlContextSystem | typeof GlLimitsSystem | typeof GlBufferSystem | typeof GlTextureSystem | typeof GlRenderTargetSystem | typeof GlGeometrySystem | typeof GlUniformGroupSystem | typeof GlShaderSystem | typeof GlEncoderSystem | typeof GlStateSystem | typeof GlStencilSystem | typeof GlColorMaskSystem)[];
declare const DefaultWebGLPipes: (typeof BlendModePipe | typeof BatcherPipe | typeof SpritePipe | typeof RenderGroupPipe | typeof AlphaMaskPipe | typeof StencilMaskPipe | typeof ColorMaskPipe | typeof CustomRenderPipe)[];
/**
* The default WebGL renderer, uses WebGL2 contexts.
* @category rendering
* @standard
* @interface
*/
export type WebGLSystems = ExtractSystemTypes<typeof DefaultWebGLSystems> & PixiMixins.RendererSystems & PixiMixins.WebGLSystems;
/**
* The default WebGL renderer, uses WebGL2 contexts.
* @internal
*/
export type WebGLPipes = ExtractSystemTypes<typeof DefaultWebGLPipes> & PixiMixins.RendererPipes & PixiMixins.WebGLPipes;
/**
* Options for WebGLRenderer.
* @category rendering
* @standard
*/
export interface WebGLOptions extends SharedRendererOptions, ExtractRendererOptions<typeof DefaultWebGLSystems>, PixiMixins.WebGLOptions {
}
export interface WebGLRenderer<T extends ICanvas = HTMLCanvasElement> extends AbstractRenderer<WebGLPipes, WebGLOptions, T>, WebGLSystems {
}
/**
* The WebGL PixiJS Renderer. This renderer allows you to use the most common graphics API, WebGL (and WebGL2).
*
* ```ts
* // Create a new renderer
* const renderer = new WebGLRenderer();
* await renderer.init();
*
* // Add the renderer to the stage
* document.body.appendChild(renderer.canvas);
*
* // Create a new stage
* const stage = new Container();
*
* // Render the stage
* renderer.render(stage);
* ```
*
* You can use {@link autoDetectRenderer} to create a renderer that will automatically detect the best
* renderer for the environment.
*
*
* ```ts
* // Create a new renderer
* const renderer = await rendering.autoDetectRenderer({
* preference:'webgl',
* });
* ```
*
* The renderer is composed of systems that manage specific tasks. The following systems are added by default
* whenever you create a WebGL renderer:
*
* | WebGL Core Systems | Systems that are specific to the WebGL renderer |
* | ------------------------------------------- | ----------------------------------------------------------------------------- |
* | {@link GlUboSystem} | This manages WebGL2 uniform buffer objects feature for shaders |
* | {@link GlBackBufferSystem} | manages the back buffer, used so that we can pixi can pixels from the screen |
* | {@link GlContextSystem} | This manages the WebGL context and its extensions |
* | {@link GlBufferSystem} | This manages buffers and their GPU resources, keeps everything in sync |
* | {@link GlTextureSystem} | This manages textures and their GPU resources, keeps everything in sync |
* | {@link GlRenderTargetSystem} | This manages what we render too. For example the screen, or another texture |
* | {@link GlGeometrySystem} | This manages geometry, used for drawing meshes via the GPU |
* | {@link GlUniformGroupSystem} | This manages uniform groups. Syncing shader properties with the GPU |
* | {@link GlShaderSystem} | This manages shaders, programs that run on the GPU to output lovely pixels |
* | {@link GlEncoderSystem} | This manages encoders, a WebGPU Paradigm, use it to draw a mesh + shader |
* | {@link GlStateSystem} | This manages the state of the WebGL context. eg the various flags that can be set blend modes / depthTesting etc |
* | {@link GlStencilSystem} | This manages the stencil buffer. Used primarily for masking |
* | {@link GlColorMaskSystem} | This manages the color mask. Used for color masking |
*
* The breadth of the API surface provided by the renderer is contained within these systems.
* @category rendering
* @property {GlUboSystem} ubo - UboSystem instance.
* @property {GlBackBufferSystem} backBuffer - BackBufferSystem instance.
* @property {GlContextSystem} context - ContextSystem instance.
* @property {GlBufferSystem} buffer - BufferSystem instance.
* @property {GlTextureSystem} texture - TextureSystem instance.
* @property {GlRenderTargetSystem} renderTarget - RenderTargetSystem instance.
* @property {GlGeometrySystem} geometry - GeometrySystem instance.
* @property {GlUniformGroupSystem} uniformGroup - UniformGroupSystem instance.
* @property {GlShaderSystem} shader - ShaderSystem instance.
* @property {GlEncoderSystem} encoder - EncoderSystem instance.
* @property {GlStateSystem} state - StateSystem instance.
* @property {GlStencilSystem} stencil - StencilSystem instance.
* @property {GlColorMaskSystem} colorMask - ColorMaskSystem instance.
* @extends AbstractRenderer
* @standard
*/
export declare class WebGLRenderer<T extends ICanvas = HTMLCanvasElement> extends AbstractRenderer<WebGLPipes, WebGLOptions, T> implements WebGLSystems {
gl: GlRenderingContext;
constructor();
}
/**
* A generic renderer that can be either a WebGL or WebGPU renderer.
* @category rendering
* @extends WebGLRenderer
* @extends WebGPURenderer
* @standard
*/
export type Renderer<T extends ICanvas = HTMLCanvasElement> = WebGLRenderer<T> | WebGPURenderer<T>;
/**
* Generic pipes for the renderer.
* @category rendering
* @advanced
*/
export type RenderPipes = WebGLPipes | WebGPUPipes;
/**
* Options for the renderer.
* @extends WebGLOptions
* @extends WebGPUOptions
* @category rendering
* @standard
*/
export interface RendererOptions extends WebGLOptions, WebGPUOptions {
}
/**
* Ids for the different render types.
* The idea is that you can use bitwise operations to filter whether or not you want to do something
* in a certain render type.
* Filters for example can be compatible for both webGL or WebGPU but not compatible with canvas.
* So internally if it works with both we set filter.compatibleRenderers = RendererType.WEBGL | RendererType.WEBGPU
* if it only works with webgl we set filter.compatibleRenderers = RendererType.WEBGL
* @category rendering
* @internal
*/
export declare enum RendererType {
/** The WebGL renderer */
WEBGL = 1,
/** The WebGPU renderer */
WEBGPU = 2,
/** Either WebGL or WebGPU renderer */
BOTH = 3
}
/**
* The GPU power preference for the WebGPU context.
* This is an optional hint indicating what configuration of GPU is suitable for the WebGPU context,
*
* - `'high-performance'` will prioritize rendering performance over power consumption,
* - `'low-power'` will prioritize power saving over rendering performance.
* @category rendering
* @advanced
*/
export type GpuPowerPreference = "low-power" | "high-performance"; /** @internal */
/**
* A resource that can have GPU data associated with it.
* @category rendering
* @advanced
*/
export interface GPUDataOwner<GPU_DATA extends GPUData = any> {
_gpuData: Record<number, GPU_DATA>;
unload: () => void;
}
/**
* Data stored on a GC-managed resource.
* @category rendering
* @advanced
*/
export interface GCData {
/** Index in the managed resources array */
index?: number;
/** Type of the resource */
type: "resource" | "renderable";
}
/**
* Interface for resources that can be garbage collected.
* @category rendering
* @advanced
*/
export interface GCable extends GPUDataOwner {
/** Timestamp of last use */
_gcLastUsed: number;
/** GC tracking data, null if not being tracked */
_gcData?: GCData | null;
/** If set to true, the resource will be garbage collected automatically when it is not used. */
autoGarbageCollect?: boolean;
/** An optional callback for when an item is touched */
_onTouch?(now: number): void;
}
type GCableEventEmitter = GCable & Pick<EventEmitter, "once" | "off">;
interface GCResourceHashEntry {
context: any;
hash: string;
type: GCData["type"];
priority: number;
}
/**
* Options for the {@link GCSystem}.
* @category rendering
* @advanced
*/
export interface GCSystemOptions {
/**
* If set to true, this will enable the garbage collector.
* @default true
*/
gcActive: boolean;
/**
* The maximum time in milliseconds a resource can be unused before being garbage collected.
* @default 60000
*/
gcMaxUnusedTime: number;
/**
* How frequently to run garbage collection in milliseconds.
* @default 30000
*/
gcFrequency: number;
}
/**
* A unified garbage collection system for managing GPU resources.
* Resources register themselves with a cleanup callback and are automatically
* cleaned up when they haven't been used for a specified amount of time.
* @example
* ```ts
* // Register a resource for GC
* gc.addResource(myResource, () => {
* // cleanup logic here
* myResource.unload();
* });
*
* // Touch the resource when used (resets idle timer)
* gc.touch(myResource);
*
* // Remove from GC tracking (e.g., on manual destroy)
* gc.removeResource(myResource);
* ```
* @category rendering
* @advanced
*/
export declare class GCSystem implements System<GCSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "gc";
readonly priority: 0;
};
/** Default options for the GCSystem */
static defaultOptions: GCSystemOptions;
/** Maximum time in ms a resource can be unused before being garbage collected */
maxUnusedTime: number;
/** Reference to the renderer this system belongs to */
private _renderer;
/** Array of resources being tracked for garbage collection */
private readonly _managedResources;
private readonly _managedResourceHashes;
/** ID of the GC scheduler handler */
private _handler;
/** How frequently GC runs in ms */
private _frequency;
/** Current timestamp used for age calculations */
now: number;
private _ready;
/**
* Creates a new GCSystem instance.
* @param renderer - The renderer this garbage collection system works for
*/
constructor(renderer: Renderer);
/**
* Initializes the garbage collection system with the provided options.
* @param options - Configuration options
*/
init(options: GCSystemOptions): void;
/**
* Gets whether the garbage collection system is currently enabled.
* @returns True if GC is enabled, false otherwise
*/
get enabled(): boolean;
/**
* Enables or disables the garbage collection system.
* When enabled, schedules periodic cleanup of resources.
* When disabled, cancels all scheduled cleanups.
*/
set enabled(value: boolean);
/**
* Called before rendering. Updates the current timestamp.
* @param options - The render options
* @param options.container - The container to render
*/
protected prerender({ container }: RenderOptions): void;
/** Performs garbage collection after rendering. */
protected postrender(): void;
/**
* Updates the GC tick counter for a render group and its children.
* @param renderGroup - The render group to update
* @param gcTick - The new tick value
*/
private _updateInstructionGCTick;
/**
* Registers a resource for garbage collection tracking.
* @param resource - The resource to track
* @param type - The type of resource to track
*/
addResource(resource: GCableEventEmitter, type: GCData["type"]): void;
/**
* Removes a resource from garbage collection tracking.
* Call this when manually destroying a resource.
* @param resource - The resource to stop tracking
*/
removeResource(resource: GCable): void;
/**
* Registers a hash-based resource collection for garbage collection tracking.
* Resources in the hash will be automatically tracked and cleaned up when unused.
* @param context - The object containing the hash property
* @param hash - The property name on context that holds the resource hash
* @param type - The type of resources in the hash ('resource' or 'renderable')
* @param priority - Processing priority (lower values are processed first)
*/
addResourceHash(context: any, hash: string, type: GCData["type"], priority?: number): void;
/**
* Performs garbage collection by cleaning up unused resources.
* Removes resources that haven't been used for longer than maxUnusedTime.
*/
run(): void;
protected updateRenderableGCTick(renderable: Renderable & GCable, now: number): void;
protected runOnResource(resource: GCableEventEmitter, now: number, writeIndex: number): number;
/**
* Creates a clone of the hash, copying all non-null entries up to (but not including) the stop key.
* @param hashValue - The original hash to clone from
* @param stopKey - The key to stop at (exclusive)
* @returns A new hash object with copied entries
*/
private _createHashClone;
protected runOnHash(hashEntry: GCResourceHashEntry, now: number): void;
/** Cleans up the garbage collection system. Disables GC and removes all tracked resources. */
destroy(): void;
}
/**
* A GPU Data object
* @internal
*/
export interface GPUData {
destroy: () => void;
}
/** @internal */
export interface GPUDataContainer<GPU_DATA extends GPUData = any> {
_gpuData: Record<number, GPU_DATA>;
unload: () => void;
}
/**
* Options for the construction of a ViewContainer.
* @category scene
* @advanced
*/
export interface ViewContainerOptions extends ContainerOptions, PixiMixins.ViewContainerOptions {
/** If set to true, the resource will be garbage collected automatically when it is not used. */
autoGarbageCollect?: boolean;
}
export interface ViewContainer<GPU_DATA extends GPUData = any> extends PixiMixins.ViewContainer, Container, GPUDataOwner<GPU_DATA>, GCable {
}
/**
* A ViewContainer is a type of container that represents a view.
* This view can be a Sprite, a Graphics object, or any other object that can be rendered.
* This class is abstract and should not be used directly.
* @category scene
* @advanced
*/
export declare abstract class ViewContainer<GPU_DATA extends GPUData = any> extends Container implements View, GCable {
/** @internal */
readonly renderPipeId: string;
/** @internal */
readonly canBundle = true;
/** @internal */
allowChildren: boolean;
/** @internal */
_roundPixels: 0 | 1;
/** @internal */
_lastUsed: number;
/** @internal */
_gpuData: Record<number, GPU_DATA>;
/** @internal */
_gcData?: GCData;
/** If set to true, the resource will be garbage collected automatically when it is not used. */
autoGarbageCollect: boolean;
/** @internal */
_gcLastUsed: number;
protected _bounds: Bounds;
protected _boundsDirty: boolean;
/**
* The local bounds of the view in its own coordinate space.
* Bounds are automatically updated when the view's content changes.
* @example
* ```ts
* // Get bounds dimensions
* const bounds = view.bounds;
* console.log(`Width: ${bounds.maxX - bounds.minX}`);
* console.log(`Height: ${bounds.maxY - bounds.minY}`);
* ```
* @returns The rectangular bounds of the view
* @see {@link Bounds} For bounds operations
*/
get bounds(): Bounds;
/** @private */
protected abstract updateBounds(): void;
/**
* Whether or not to round the x/y position of the sprite.
* @example
* ```ts
* // Enable pixel rounding for crisp rendering
* view.roundPixels = true;
* ```
* @default false
*/
get roundPixels(): boolean;
set roundPixels(value: boolean);
constructor(options: ViewContainerOptions);
/**
* Checks if the object contains the given point in local coordinates.
* Uses the view's bounds for hit testing.
* @example
* ```ts
* // Basic point check
* const localPoint = { x: 50, y: 25 };
* const contains = view.containsPoint(localPoint);
* console.log('Point is inside:', contains);
* ```
* @param point - The point to check in local coordinates
* @returns True if the point is within the view's bounds
* @see {@link ViewContainer#bounds} For the bounds used in hit testing
* @see {@link Container#toLocal} For converting global coordinates to local
*/
containsPoint(point: PointData): boolean;
/** @private */
abstract batched: boolean;
/** @private */
protected onViewUpdate(): void;
/** Unloads the GPU data from the view. */
unload(): void;
destroy(options?: DestroyOptions): void;
/**
* Collects renderables for the view container.
* @param instructionSet - The instruction set to collect renderables for.
* @param renderer - The renderer to collect renderables for.
* @param currentLayer - The current render layer.
* @internal
*/
collectRenderablesSimple(instructionSet: InstructionSet, renderer: Renderer, currentLayer: RenderLayer): void;
}
/**
* Represents a renderable object in the rendering system.
* This is typically a view container that can be rendered to a target.
* @internal
*/
export type Renderable = ViewContainer;
/**
* A set of instructions that can be executed by the renderer.
* Basically wraps an array, but with some extra properties that help the renderer
* to keep things nice and optimised.
*
* Note:
* InstructionSet.instructions contains all the instructions, but does not resize (for performance).
* So for the true length of the instructions you need to use InstructionSet.instructionSize
* @category rendering
* @advanced
*/
export declare class InstructionSet {
/** a unique id for this instruction set used through the renderer */
readonly uid: number;
/** the array of instructions */
readonly instructions: Instruction[];
/** the actual size of the array (any instructions passed this should be ignored) */
instructionSize: number;
/** allows for access to the render pipes of the renderer */
renderPipes: any;
renderables: Renderable[];
/** used by the garbage collector to track when the instruction set was last used */
gcTick: number;
/** reset the instruction set so it can be reused set size back to 0 */
reset(): void;
/**
* Destroy the instruction set, clearing the instructions and renderables.
* @internal
*/
destroy(): void;
/**
* Add an instruction to the set
* @param instruction - add an instruction to the set
*/
add(instruction: Instruction): void;
/**
* Log the instructions to the console (for debugging)
* @internal
*/
log(): void;
}
/**
* Options for configuring a RenderLayer. A RenderLayer allows control over rendering order
* independent of the scene graph hierarchy.
* @example
* ```ts
* // Basic layer with automatic sorting
* const layer = new RenderLayer({
* sortableChildren: true
* });
*
* // Layer with custom sort function
* const customLayer = new RenderLayer({
* sortableChildren: true,
* sortFunction: (a, b) => {
* // Sort by y position
* return a.position.y - b.position.y;
* }
* });
*
* // Add objects to layer while maintaining scene graph parent
* const sprite = new Sprite(texture);
* container.addChild(sprite); // Add to scene graph
* layer.attach(sprite); // Add to render layer
*
* // Manual sorting when needed
* const manualLayer = new RenderLayer({
* sortableChildren: false
* });
* manualLayer.attach(sprite1, sprite2);
* manualLayer.sortRenderLayerChildren(); // Sort manually
* ```
* @category scene
* @standard
*/
export interface RenderLayerOptions {
/**
* If true, the layer's children will be sorted by zIndex before rendering.
* If false, you can manually sort the children using sortRenderLayerChildren when needed.
* @default false
* @example
* ```ts
* const layer = new RenderLayer({
* sortableChildren: true // Automatically sorts children by zIndex
* });
* ```
* @see {@link RenderLayer#sortRenderLayerChildren} For manual sorting
* @see {@link RenderLayer#sortFunction} For customizing the sort logic
* @see {@link Container#zIndex} For the default sort property
*/
sortableChildren?: boolean;
/**
* Custom sort function to sort layer children. Default sorts by zIndex.
* @param a - First container to compare
* @param b - Second container to compare
* @returns Negative if a should render before b, positive if b should render before a
* @example
* ```ts
* const layer = new RenderLayer({
* sortFunction: (a, b) => {
* // Sort by y position
* return a.position.y - b.position.y;
* }
* });
* ```
* @see {@link RenderLayer#sortableChildren} For enabling automatic sorting
* @see {@link RenderLayer#sortRenderLayerChildren} For manual sorting
* @see {@link Container#zIndex} For the default sort property
* @default (a, b) => a.zIndex - b.zIndex
*/
sortFunction?: (a: Container, b: Container) => number;
}
/**
* The RenderLayer API provides a way to control the rendering order of objects independently
* of their logical parent-child relationships in the scene graph.
* This allows developers to decouple how objects are transformed
* (via their logical parent) from how they are rendered on the screen.
*
* ### Key Concepts
*
* #### RenderLayers Control Rendering Order:
* - RenderLayers define where in the render stack objects are drawn,
* but they do not affect an object's transformations (e.g., position, scale, rotation) or logical hierarchy.
* - RenderLayers can be added anywhere in the scene graph.
*
* #### Logical Parenting Remains Unchanged:
* - Objects still have a logical parent for transformations via addChild.
* - Assigning an object to a layer does not reparent it.
*
* #### Explicit Control:
* - Developers assign objects to layers using renderLayer.add and remove them using renderLayer.remove.
* ---
* ### API Details
*
* #### 1. Creating a RenderLayer
* A RenderLayer is a lightweight object responsible for controlling render order.
* It has no children or transformations of its own
* but can be inserted anywhere in the scene graph to define its render position.
* ```js
* const layer = new RenderLayer();
* app.stage.addChild(layer); // Insert the layer into the scene graph
* ```
*
* #### 2. Adding Objects to a Layer
* Use renderLayer.add to assign an object to a layer.
* This overrides the object's default render order defined by its logical parent.
* ```js
* const rect = new Graphics();
* container.addChild(rect); // Add to logical parent
* layer.attach(rect); // Control render order via the layer
* ```
*
* #### 3. Removing Objects from a Layer
* To stop an object from being rendered in the layer, use remove.
* ```js
* layer.remove(rect); // Stop rendering rect via the layer
* ```
* When an object is removed from its logical parent (removeChild), it is automatically removed from the layer.
*
* #### 4. Re-Adding Objects to Layers
* If an object is re-added to a logical parent, it does not automatically reassign itself to the layer.
* Developers must explicitly reassign it.
* ```js
* container.addChild(rect); // Logical parent
* layer.attach(rect); // Explicitly reassign to the layer
* ```
*
* #### 5. Layer Position in Scene Graph
* A layer's position in the scene graph determines its render priority relative to other layers and objects.
* Layers can be inserted anywhere in the scene graph.
* ```js
* const backgroundLayer = new RenderLayer();
* const uiLayer = new RenderLayer();
*
* app.stage.addChild(backgroundLayer);
* app.stage.addChild(world);
* app.stage.addChild(uiLayer);
* ```
* This is a new API and therefore considered experimental at this stage.
* While the core is pretty robust, there are still a few tricky issues we need to tackle.
* However, even with the known issues below, we believe this API is incredibly useful!
*
* Known issues:
* - Interaction may not work as expected since hit testing does not account for the visual render order created by layers.
* For example, if an object is visually moved to the front via a layer, hit testing will still use its original position.
* - RenderLayers and their children must all belong to the same renderGroup to work correctly
* @category scene
* @class
* @extends null
* @standard
*/
export declare class RenderLayer extends Container {
/**
* Default options for RenderLayer instances. These options control the sorting behavior
* of objects within the render layer.
* @example
* ```ts
* // Create a custom render layer with modified default options
* RenderLayer.defaultOptions = {
* sortableChildren: true,
* sortFunction: (a, b) => a.y - b.y // Sort by vertical position
* };
*
* // All new render layers will use these defaults
* const layer1 = new RenderLayer();
* // layer1 will have sortableChildren = true
* ```
* @property {boolean} sortableChildren -
* @property {Function} sortFunction -
* @see {@link RenderLayer} For the main render layer class
* @see {@link Container#zIndex} For the default sort property
* @see {@link RenderLayer#sortRenderLayerChildren} For manual sorting
*/
static defaultOptions: RenderLayerOptions;
/** Function used to sort layer children if sortableChildren is true */
sortFunction: (a: Container, b: Container) => number;
/**
* The list of objects that this layer is responsible for rendering. Objects in this list maintain
* their original parent in the scene graph but are rendered as part of this layer.
* @example
* ```ts
* const layer = new RenderLayer();
* const sprite = new Sprite(texture);
*
* // Add sprite to scene graph for transforms
* container.addChild(sprite);
*
* // Add to layer for render order control
* layer.attach(sprite);
* console.log(layer.renderLayerChildren.length); // 1
*
* // Access objects in the layer
* layer.renderLayerChildren.forEach(child => {
* console.log('Layer child:', child);
* });
*
* // Check if object is in layer
* const isInLayer = layer.renderLayerChildren.includes(sprite);
*
* // Clear all objects from layer
* layer.detachAll();
* console.log(layer.renderLayerChildren.length); // 0
* ```
* @readonly
* @see {@link RenderLayer#attach} For adding objects to the layer
* @see {@link RenderLayer#detach} For removing objects from the layer
* @see {@link RenderLayer#detachAll} For removing all objects from the layer
*/
renderLayerChildren: Container[];
/** @internal */
parent: Container | null;
/** @internal */
didChange: boolean;
/** @internal */
_updateFlags: number;
/** @internal */
parentRenderLayer: null;
/** @internal */
destroyed: boolean;
/** @internal */
layerParentId: string;
/**
* If true, the layer's children will be sorted by zIndex before rendering.
* If false, you can manually sort the children using sortRenderLayerChildren when needed.
* @default false
* @example
* ```ts
* const layer = new RenderLayer({
* sortableChildren: true // Automatically sorts children by zIndex
* });
* ```
* @see {@link RenderLayer#sortRenderLayerChildren} For manual sorting
* @see {@link RenderLayer#sortFunction} For customizing the sort logic
* @see {@link Container#zIndex} For the default sort property
*/
sortableChildren: boolean;
/**
* Creates a new RenderLayer instance
* @param options - Configuration options for the RenderLayer
* @param {boolean} [options.sortableChildren=false] - If true, layer children will be automatically sorted each render
* @param {Function} [options.sortFunction] - Custom function to sort layer children. Default sorts by zIndex
*/
constructor(options?: RenderLayerOptions);
/**
* Adds one or more Containers to this render layer. The Containers will be rendered as part of this layer
* while maintaining their original parent in the scene graph.
*
* If the Container already belongs to a layer, it will be removed from the old layer before being added to this one.
* @example
* ```ts
* const layer = new RenderLayer();
* const container = new Container();
* const sprite1 = new Sprite(texture1);
* const sprite2 = new Sprite(texture2);
*
* // Add sprites to scene graph for transforms
* container.addChild(sprite1, sprite2);
*
* // Add sprites to layer for render order control
* layer.attach(sprite1, sprite2);
*
* // Add single sprite with type checking
* const typedSprite = layer.attach<Sprite>(new Sprite(texture3));
* typedSprite.tint = 'red';
*
* // Automatically removes from previous layer if needed
* const otherLayer = new RenderLayer();
* otherLayer.attach(sprite1); // Removes from previous layer
* ```
* @param children - The Container(s) to add to this layer. Can be any Container or array of Containers.
* @returns The first child that was added, for method chaining
* @see {@link RenderLayer#detach} For removing objects from the layer
* @see {@link RenderLayer#detachAll} For removing all objects from the layer
* @see {@link Container#addChild} For adding to scene graph hierarchy
*/
attach<U extends Container[]>(...children: U): U[0];
/**
* Removes one or more Containers from this render layer. The Containers will maintain their
* original parent in the scene graph but will no longer be rendered as part of this layer.
* @example
* ```ts
* const layer = new RenderLayer();
* const container = new Container();
* const sprite1 = new Sprite(texture1);
* const sprite2 = new Sprite(texture2);
*
* // Add sprites to scene graph and layer
* container.addChild(sprite1, sprite2);
* layer.attach(sprite1, sprite2);
*
* // Remove single sprite from layer
* layer.detach(sprite1);
* // sprite1 is still child of container but not rendered in layer
*
* // Remove multiple sprites at once
* const otherLayer = new RenderLayer();
* otherLayer.attach(sprite3, sprite4);
* otherLayer.detach(sprite3, sprite4);
*
* // Type-safe detachment
* const typedSprite = layer.detach<Sprite>(spriteInLayer);
* typedSprite.texture = newTexture; // TypeScript knows this is a Sprite
* ```
* @param children - The Container(s) to remove from this layer
* @returns The first child that was removed, for method chaining
* @see {@link RenderLayer#attach} For adding objects to the layer
* @see {@link RenderLayer#detachAll} For removing all objects from the layer
* @see {@link Container#removeChild} For removing from scene graph hierarchy
*/
detach<U extends Container[]>(...children: U): U[0];
/**
* Removes all objects from this render layer. Objects will maintain their
* original parent in the scene graph but will no longer be rendered as part of this layer.
* @example
* ```ts
* const layer = new RenderLayer();
* const container = new Container();
*
* // Add multiple sprites to scene graph and layer
* const sprites = [
* new Sprite(texture1),
* new Sprite(texture2),
* new Sprite(texture3)
* ];
*
* container.addChild(...sprites); // Add to scene graph
* layer.attach(...sprites); // Add to render layer
*
* // Later, remove all sprites from layer at once
* layer.detachAll();
* console.log(layer.renderLayerChildren.length); // 0
* console.log(container.children.length); // 3 (still in scene graph)
* ```
* @returns The RenderLayer instance for method chaining
* @see {@link RenderLayer#attach} For adding objects to the layer
* @see {@link RenderLayer#detach} For removing individual objects
* @see {@link Container#removeChildren} For removing from scene graph
*/
detachAll(): void;
/**
* Collects renderables for this layer and its children.
* This method is called by the renderer to gather all objects that should be rendered in this layer.
* @param instructionSet - The set of instructions to collect renderables into.
* @param renderer - The renderer that is collecting renderables.
* @param _currentLayer - The current render layer being processed.
* @internal
*/
collectRenderables(instructionSet: InstructionSet, renderer: Renderer, _currentLayer: RenderLayer): void;
/**
* Sort the layer's children using the defined sort function. This method allows manual sorting
* of layer children and is automatically called during rendering if sortableChildren is true.
* @example
* ```ts
* const layer = new RenderLayer();
*
* // Add multiple sprites at different depths
* const sprite1 = new Sprite(texture);
* const sprite2 = new Sprite(texture);
* const sprite3 = new Sprite(texture);
*
* sprite1.zIndex = 3;
* sprite2.zIndex = 1;
* sprite3.zIndex = 2;
*
* layer.attach(sprite1, sprite2, sprite3);
*
* // Manual sorting with default zIndex sort
* layer.sortRenderLayerChildren();
* // Order is now: sprite2 (1), sprite3 (2), sprite1 (3)
*
* // Custom sort by y position
* layer.sortFunction = (a, b) => a.y - b.y;
* layer.sortRenderLayerChildren();
*
* // Automatic sorting
* layer.sortableChildren = true; // Will sort each render
* ```
* @returns The RenderLayer instance for method chaining
* @see {@link RenderLayer#sortableChildren} For enabling automatic sorting
* @see {@link RenderLayer#sortFunction} For customizing the sort logic
*/
sortRenderLayerChildren(): void;
/**
* Recursively calculates the global bounds of this RenderLayer and its children.
* @param factorRenderLayers
* @param bounds
* @param _currentLayer
* @internal
*/
_getGlobalBoundsRecursive(factorRenderLayers: boolean, bounds: Bounds, _currentLayer: RenderLayer): void;
/**
* @inheritdoc
* @internal
*/
getFastGlobalBounds(factorRenderLayers?: boolean, bounds?: Bounds): Bounds;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error. Please use `RenderLayer.attach()` instead.
* @param {...any} _children
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
addChild<U extends Container[]>(..._children: U): never;
/**
* This method is not available in RenderLayer.
* Calling this method will throw an error. Please use `RenderLayer.detach()` instead.
* @param {...any} _children
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChild<U extends Container[]>(..._children: U): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error. Please use `RenderLayer.detach()` instead.
* @param {number} [_beginIndex]
* @param {number} [_endIndex]
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChildren(_beginIndex?: number, _endIndex?: number): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChildAt(_index: number): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
getChildAt(_index: number): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {Container} _child
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
setChildIndex(_child: Container, _index: number): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {Container} _child
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
getChildIndex(_child: Container): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {Container} _child
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
addChildAt<U extends Container>(_child: U, _index: number): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param {Container} _child
* @param {Container} _child2
* @ignore
*/
swapChildren<U extends Container>(_child: U, _child2: U): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param _child - The child to reparent
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
reparentChild(..._child: Container[]): never;
/**
* This method is not available in RenderLayer.
*
* Calling this method will throw an error.
* @param _child - The child to reparent
* @param _index - The index to reparent the child to
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
reparentChildAt(_child: Container, _index: number): never;
}
/**
* The type of child that can be added to a {@link Container}.
* This is a generic type that extends the {@link Container} class.
* @category scene
* @standard
*/
export type ContainerChild = Container;
/**
* Events that can be emitted by a Container. These events provide lifecycle hooks and notifications
* for container state changes.
* @example
* ```ts
* import { Container, Sprite } from 'pixi.js';
*
* // Setup container with event listeners
* const container = new Container();
*
* // Listen for child additions
* container.on('childAdded', (child, container, index) => {
* console.log(`Child added at index ${index}:`, child);
* });
*
* // Listen for child removals
* container.on('childRemoved', (child, container, index) => {
* console.log(`Child removed from index ${index}:`, child);
* });
*
* // Listen for when container is added to parent
* container.on('added', (parent) => {
* console.log('Added to parent:', parent);
* });
*
* // Listen for when container is removed from parent
* container.on('removed', (parent) => {
* console.log('Removed from parent:', parent);
* });
*
* // Listen for container destruction
* container.on('destroyed', (container) => {
* console.log('Container destroyed:', container);
* });
* ```
* @category scene
* @standard
*/
export interface ContainerEvents<C extends ContainerChild> extends PixiMixins.ContainerEvents {
/**
* Emitted when this container is added to a new container.
* Useful for setting up parent-specific behaviors.
* @param container - The parent container this was added to
* @example
* ```ts
* const child = new Container();
* child.on('added', (parent) => {
* console.log('Child added to parent:', parent.label);
* });
* parentContainer.addChild(child);
* ```
*/
added: [
container: Container
];
/**
* Emitted when a child is added to this container.
* Useful for tracking container composition changes.
* @param child - The child that was added
* @param container - The container the child was added to (this container)
* @param index - The index at which the child was added
* @example
* ```ts
* const parent = new Container();
* parent.on('childAdded', (child, container, index) => {
* console.log(`New child at index ${index}:`, child);
* });
* ```
*/
childAdded: [
child: C,
container: Container,
index: number
];
/**
* Emitted when this container is removed from its parent.
* Useful for cleanup and state management.
* @param container - The parent container this was removed from
* @example
* ```ts
* const child = new Container();
* child.on('removed', (oldParent) => {
* console.log('Child removed from parent:', oldParent.label);
* });
* ```
*/
removed: [
container: Container
];
/**
* Emitted when a child is removed from this container.
* Useful for cleanup and maintaining container state.
* @param child - The child that was removed
* @param container - The container the child was removed from (this container)
* @param index - The index from which the child was removed
* @example
* ```ts
* const parent = new Container();
* parent.on('childRemoved', (child, container, index) => {
* console.log(`Child removed from index ${index}:`, child);
* });
* ```
*/
childRemoved: [
child: C,
container: Container,
index: number
];
/**
* Emitted when the container is destroyed.
* Useful for final cleanup and resource management.
* @param container - The container that was destroyed
* @example
* ```ts
* const container = new Container();
* container.on('destroyed', (container) => {
* console.log('Container destroyed:', container.label);
* });
* ```
*/
destroyed: [
container: Container
];
}
type AnyEvent = {
[K: ({} & string) | ({} & symbol)]: any;
};
/** @internal */
export declare const UPDATE_COLOR = 1;
/** @internal */
export declare const UPDATE_BLEND = 2;
/** @internal */
export declare const UPDATE_VISIBLE = 4;
/** @internal */
export declare const UPDATE_TRANSFORM = 8;
/**
* Options for updating the transform of a container.
* @category scene
* @standard
*/
export interface UpdateTransformOptions {
x: number;
y: number;
scaleX: number;
scaleY: number;
rotation: number;
skewX: number;
skewY: number;
pivotX: number;
pivotY: number;
originX: number;
originY: number;
}
/**
* Constructor options used for `Container` instances.
* ```js
* const container = new Container({
* position: new Point(100, 200),
* scale: new Point(2, 2),
* rotation: Math.PI / 2,
* });
* ```
* @category scene
* @standard
* @see Container
*/
export interface ContainerOptions<C extends ContainerChild = ContainerChild> extends PixiMixins.ContainerOptions {
/** @see Container#isRenderGroup */
isRenderGroup?: boolean;
/**
* The blend mode to be applied to the sprite. Controls how pixels are blended when rendering.
*
* Setting to 'normal' will reset to default blending.
* > [!NOTE] More blend modes are available after importing the `pixi.js/advanced-blend-modes` sub-export.
* @example
* ```ts
* // Basic blend modes
* new Container({ blendMode: 'normal' }); // Default blending
* new Container({ blendMode: 'add' }); // Additive blending
* new Container({ blendMode: 'multiply' }); // Multiply colors
* new Container({ blendMode: 'screen' }); // Screen blend
* ```
* @default 'normal'
* @see {@link Container#alpha} For transparency
* @see {@link Container#tint} For color adjustments
*/
blendMode?: BLEND_MODES;
/**
* The tint applied to the sprite.
*
* This can be any valid {@link ColorSource}.
* @example
* ```ts
* new Container({ tint: 0xff0000 }); // Red tint
* new Container({ tint: 'blue' }); // Blue tint
* new Container({ tint: '#00ff00' }); // Green tint
* new Container({ tint: 'rgb(0,0,255)' }); // Blue tint
* ```
* @default 0xFFFFFF
* @see {@link Container#alpha} For transparency
* @see {@link Container#visible} For visibility control
*/
tint?: ColorSource;
/**
* The opacity of the object relative to its parent's opacity.
* Value ranges from 0 (fully transparent) to 1 (fully opaque).
* @example
* ```ts
* new Container({ alpha: 0.5 }); // 50% opacity
* new Container({ alpha: 1 }); // Fully opaque
* ```
* @default 1
* @see {@link Container#visible} For toggling visibility
* @see {@link Container#renderable} For render control
*/
alpha?: number;
/**
* The angle of the object in degrees.
*
* > [!NOTE] 'rotation' and 'angle' have the same effect on a display object;
* > rotation is in radians, angle is in degrees.
* @example
* ```ts
* new Container({ angle: 45 }); // Rotate 45 degrees
* new Container({ angle: 90 }); // Rotate 90 degrees
* ```
*/
angle?: number;
/**
* The array of children of this container. Each child must be a Container or extend from it.
*
* The array is read-only, but its contents can be modified using Container methods.
* @example
* ```ts
* new Container({
* children: [
* new Container(), // First child
* new Container(), // Second child
* ],
* });
* ```
* @readonly
* @see {@link Container#addChild} For adding children
* @see {@link Container#removeChild} For removing children
*/
children?: C[];
/**
* The display object container that contains this display object.
* This represents the parent-child relationship in the display tree.
* @readonly
* @see {@link Container#addChild} For adding to a parent
* @see {@link Container#removeChild} For removing from parent
*/
parent?: Container;
/**
* Controls whether this object can be rendered. If false the object will not be drawn,
* but the transform will still be updated. This is different from visible, which skips
* transform updates.
* @example
* ```ts
* new Container({ renderable: false }); // Will not be drawn, but transforms will update
* ```
* @default true
* @see {@link Container#visible} For skipping transform updates
* @see {@link Container#alpha} For transparency
*/
renderable?: boolean;
/**
* The rotation of the object in radians.
*
* > [!NOTE] 'rotation' and 'angle' have the same effect on a display object;
* > rotation is in radians, angle is in degrees.
* @example
* ```ts
* new Container({ rotation: Math.PI / 4 }); // Rotate 45 degrees
* new Container({ rotation: Math.PI / 2 }); // Rotate 90 degrees
* ```
*/
rotation?: number;
/**
* The scale factors of this object along the local coordinate axes.
*
* The default scale is (1, 1).
* @example
* ```ts
* new Container({ scale: new Point(2, 2) }); // Scale by 2x
* new Container({ scale: 0.5 }); // Scale by 0.5x
* new Container({ scale: { x: 1.5, y: 1.5 } }); // Scale by 1.5x
* ```
*/
scale?: PointData | number;
/**
* The center of rotation, scaling, and skewing for this display object in its local space.
* The `position` is the projection of `pivot` in the parent's local space.
*
* By default, the pivot is the origin (0, 0).
* @example
* ```ts
* new Container({ pivot: new Point(100, 200) }); // Set pivot to (100, 200)
* new Container({ pivot: 50 }); // Set pivot to (50, 50)
* new Container({ pivot: { x: 150, y: 150 } }); // Set pivot to (150, 150)
* ```
*/
pivot?: PointData | number;
/**
* The origin point around which the container rotates and scales.
* Unlike pivot, changing origin will not move the container's position.
* @example
* ```ts
* new Container({ origin: new Point(100, 100) }); // Rotate around point (100,100)
* new Container({ origin: 50 }); // Rotate around point (50, 50)
* new Container({ origin: { x: 150, y: 150 } }); // Rotate around point (150, 150)
* ```
*/
origin?: PointData | number;
/**
* The coordinate of the object relative to the local coordinates of the parent.
* @example
* ```ts
* new Container({ position: new Point(100, 200) }); // Set position to (100, 200)
* new Container({ position: { x: 150, y: 150 } }); // Set position to (150, 150)
* ```
*/
position?: PointData;
/**
* The skew factor for the object in radians. Skewing is a transformation that distorts
* the object by rotating it differently at each point, creating a non-uniform shape.
* @example
* ```ts
* new Container({ skew: new Point(0.1, 0.2) }); // Skew by 0.1 radians on x and 0.2 radians on y
* new Container({ skew: { x: 0.1, y: 0.2 } }); // Skew by 0.1 radians on x and 0.2 radians on y
* ```
* @default { x: 0, y: 0 }
*/
skew?: PointData;
/**
* The visibility of the object. If false the object will not be drawn,
* and the transform will not be updated.
* @example
* ```ts
* new Container({ visible: false }); // Will not be drawn and transforms will not update
* new Container({ visible: true }); // Will be drawn and transforms will update
* ```
* @default true
* @see {@link Container#renderable} For render-only control
* @see {@link Container#alpha} For transparency
*/
visible?: boolean;
/**
* The position of the container on the x axis relative to the local coordinates of the parent.
*
* An alias to position.x
* @example
* ```ts
* new Container({ x: 100 }); // Set x position to 100
* ```
*/
x?: number;
/**
* The position of the container on the y axis relative to the local coordinates of the parent.
*
* An alias to position.y
* @example
* ```ts
* new Container({ y: 200 }); // Set y position to 200
* ```
*/
y?: number;
/**
* An optional bounds area for this container. Setting this rectangle will stop the renderer
* from recursively measuring the bounds of each children and instead use this single boundArea.
*
* > [!IMPORTANT] This is great for optimisation! If for example you have a
* > 1000 spinning particles and you know they all sit within a specific bounds,
* > then setting it will mean the renderer will not need to measure the
* > 1000 children to find the bounds. Instead it will just use the bounds you set.
* @example
* ```ts
* const container = new Container({
* boundsArea: new Rectangle(0, 0, 500, 500) // Set a fixed bounds area
* });
* ```
*/
boundsArea?: Rectangle;
}
export interface Container<C extends ContainerChild> extends PixiMixins.Container<C>, EventEmitter<ContainerEvents<C> & AnyEvent> {
}
/**
* Container is a general-purpose display object that holds children. It also adds built-in support for advanced
* rendering features like masking and filtering.
*
* It is the base class of all display objects that act as a container for other objects, including Graphics
* and Sprite.
*
* <details id="transforms">
*
* <summary>Transforms</summary>
*
* The [transform]{@link Container#localTransform} of a display object describes the projection from its
* local coordinate space to its parent's local coordinate space. The following properties are derived
* from the transform:
*
* <table>
* <thead>
* <tr>
* <th>Property</th>
* <th>Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>[pivot]{@link Container#pivot}</td>
* <td>
* Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot
* is equal to position, regardless of the other three transformations. In other words, It is the center of
* rotation, scaling, and skewing.
* </td>
* </tr>
* <tr>
* <td>[position]{@link Container#position}</td>
* <td>
* Translation. This is the position of the [pivot]{@link Container#pivot} in the parent's local
* space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object
* is (0,0) in its local space, then the position will be its top-left corner in the parent's local space.
* </td>
* </tr>
* <tr>
* <td>[scale]{@link Container#scale}</td>
* <td>
* Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the
* local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center
* of scaling is the [pivot]{@link Container#pivot}.
* </td>
* </tr>
* <tr>
* <td>[rotation]{@link Container#rotation}</td>
* <td>
* Rotation. This will rotate the display object's projection by this angle (in radians).
* </td>
* </tr>
* <tr>
* <td>[skew]{@link Container#skew}</td>
* <td>
* <p>Skewing. This can be used to deform a rectangular display object into a parallelogram.</p>
* <p>
* In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be
* thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is
* ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be
* rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will
* be rotated by an angle between ⍺ and β.
* </p>
* <p>
* It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying
* a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ.
* </p>
* <p>
* Another quite interesting observation is that "skew.x", "skew.y", rotation are commutative operations. Indeed,
* because rotation is essentially a careful combination of the two.
* </p>
* </td>
* </tr>
* <tr>
* <td>[angle]{@link Container#angle}</td>
* <td>Rotation. This is an alias for [rotation]{@link Container#rotation}, but in degrees.</td>
* </tr>
* <tr>
* <td>[x]{@link Container#x}</td>
* <td>Translation. This is an alias for position.x!</td>
* </tr>
* <tr>
* <td>[y]{@link Container#y}</td>
* <td>Translation. This is an alias for position.y!</td>
* </tr>
* <tr>
* <td>[width]{@link Container#width}</td>
* <td>
* Implemented in [Container]{@link Container}. Scaling. The width property calculates scale.x by dividing
* the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there
* is no concept of user-defined width.
* </td>
* </tr>
* <tr>
* <td>[height]{@link Container#height}</td>
* <td>
* Implemented in [Container]{@link Container}. Scaling. The height property calculates scale.y by dividing
* the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there
* is no concept of user-defined height.
* </td>
* </tr>
* </tbody>
* </table>
* </details>
*
* <details id="alpha">
* <summary>Alpha</summary>
*
* This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display
* object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not
* applied on any ancestor further up the chain).
* </details>
*
* <details id="visible">
* <summary>Renderable vs Visible</summary>
*
* The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the
* screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display
* object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not
* be calculated.
* ```ts
* import { BlurFilter, Container, Graphics, Sprite } from 'pixi.js';
*
* const container = new Container();
* const sprite = Sprite.from('https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png');
*
* sprite.width = 512;
* sprite.height = 512;
*
* // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container
* // is rendered.
* container.addChild(sprite);
*
* // Blurs whatever is rendered by the container
* container.filters = [new BlurFilter()];
*
* // Only the contents within a circle at the center should be rendered onto the screen.
* container.mask = new Graphics()
* .beginFill(0xffffff)
* .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2)
* .endFill();
* ```
*
* </details>
*
* <details id="renderGroup">
* <summary>RenderGroup</summary>
*
* In PixiJS v8, containers can be set to operate in 'render group mode',
* transforming them into entities akin to a stage in traditional rendering paradigms.
* A render group is a root renderable entity, similar to a container,
* but it's rendered in a separate pass with its own unique set of rendering instructions.
* This approach enhances rendering efficiency and organization, particularly in complex scenes.
*
* You can enable render group mode on any container using container.enableRenderGroup()
* or by initializing a new container with the render group property set to true (new Container({isRenderGroup: true})).
* The method you choose depends on your specific use case and setup requirements.
*
* An important aspect of PixiJS’s rendering process is the automatic treatment of rendered scenes as render groups.
* This conversion streamlines the rendering process, but understanding when and how this happens is crucial
* to fully leverage its benefits.
*
* One of the key advantages of using render groups is the performance efficiency in moving them. Since transformations
* are applied at the GPU level, moving a render group, even one with complex and numerous children,
* doesn't require recalculating the rendering instructions or performing transformations on each child.
* This makes operations like panning a large game world incredibly efficient.
*
* However, it's crucial to note that render groups do not batch together.
* This means that turning every container into a render group could actually slow things down,
* as each render group is processed separately. It's best to use render groups judiciously, at a broader level,
* rather than on a per-child basis.
* This approach ensures you get the performance benefits without overburdening the rendering process.
*
* RenderGroups maintain their own set of rendering instructions,
* ensuring that changes or updates within a render group don't affect the rendering
* instructions of its parent or other render groups.
* This isolation ensures more stable and predictable rendering behavior.
*
* Additionally, renderGroups can be nested, allowing for powerful options in organizing different aspects of your scene.
* This feature is particularly beneficial for separating complex game graphics from UI elements,
* enabling intricate and efficient scene management in complex applications.
*
* This means that Containers have 3 levels of matrix to be mindful of:
*
* 1. localTransform, this is the transform of the container based on its own properties
* 2. groupTransform, this it the transform of the container relative to the renderGroup it belongs too
* 3. worldTransform, this is the transform of the container relative to the Scene being rendered
* </details>
* @category scene
* @standard
*/
export declare class Container<C extends ContainerChild = ContainerChild> extends EventEmitter<ContainerEvents<C> & AnyEvent> {
/**
* Mixes all enumerable properties and methods from a source object to Container.
* @param source - The source of properties and methods to mix in.
* @deprecated since 8.8.0
*/
static mixin(source: Dict<any>): void;
/**
* unique id for this container
* @internal
*/
readonly uid: number;
/** @private */
_updateFlags: number;
/** @private */
renderGroup: RenderGroup;
/** @private */
parentRenderGroup: RenderGroup;
/** @private */
parentRenderGroupIndex: number;
/** @private */
didChange: boolean;
/** @private */
didViewUpdate: boolean;
/** @private */
relativeRenderGroupDepth: number;
/**
* The array of children of this container. Each child must be a Container or extend from it.
*
* The array is read-only, but its contents can be modified using Container methods.
* @example
* ```ts
* // Access children
* const firstChild = container.children[0];
* const lastChild = container.children[container.children.length - 1];
* ```
* @readonly
* @see {@link Container#addChild} For adding children
* @see {@link Container#removeChild} For removing children
*/
children: C[];
/**
* The display object container that contains this display object.
* This represents the parent-child relationship in the display tree.
* @example
* ```ts
* // Basic parent access
* const parent = sprite.parent;
*
* // Walk up the tree
* let current = sprite;
* while (current.parent) {
* console.log('Level up:', current.parent.constructor.name);
* current = current.parent;
* }
* ```
* @readonly
* @see {@link Container#addChild} For adding to a parent
* @see {@link Container#removeChild} For removing from parent
*/
parent: Container | null;
/** @private */
includeInBuild: boolean;
/** @private */
measurable: boolean;
/** @private */
isSimple: boolean;
/**
* The RenderLayer this container belongs to, if any.
* If it belongs to a RenderLayer, it will be rendered from the RenderLayer's position in the scene.
* @readonly
* @advanced
*/
parentRenderLayer: RenderLayer | null;
/** @internal */
updateTick: number;
/**
* Current transform of the object based on local factors: position, scale, other stuff.
* This matrix represents the local transformation without any parent influence.
* @example
* ```ts
* // Basic transform access
* const localMatrix = sprite.localTransform;
* console.log(localMatrix.toString());
* ```
* @readonly
* @see {@link Container#worldTransform} For global transform
* @see {@link Container#groupTransform} For render group transform
*/
localTransform: Matrix;
/**
* The relative group transform is a transform relative to the render group it belongs too. It will include all parent
* transforms and up to the render group (think of it as kind of like a stage - but the stage can be nested).
* If this container is is self a render group matrix will be relative to its parent render group
* @readonly
* @advanced
*/
relativeGroupTransform: Matrix;
/**
* The group transform is a transform relative to the render group it belongs too.
* If this container is render group then this will be an identity matrix. other wise it
* will be the same as the relativeGroupTransform.
* Use this value when actually rendering things to the screen
* @readonly
* @advanced
*/
groupTransform: Matrix;
private _worldTransform;
/**
* Whether this object has been destroyed. If true, the object should no longer be used.
* After an object is destroyed, all of its functionality is disabled and references are removed.
* @example
* ```ts
* // Cleanup with destroy
* sprite.destroy();
* console.log(sprite.destroyed); // true
* ```
* @default false
* @see {@link Container#destroy} For destroying objects
*/
destroyed: boolean;
/**
* The coordinate of the object relative to the local coordinates of the parent.
* @internal
*/
_position: ObservablePoint;
/**
* The scale factor of the object.
* @internal
*/
_scale: ObservablePoint;
/**
* The pivot point of the container that it rotates around.
* @internal
*/
_pivot: ObservablePoint;
/**
* The origin point around which the container rotates and scales.
* Unlike pivot, changing origin will not move the container's position.
* @private
*/
_origin: ObservablePoint;
/**
* The skew amount, on the x and y axis.
* @internal
*/
_skew: ObservablePoint;
/**
* The X-coordinate value of the normalized local X axis,
* the first column of the local transformation matrix without a scale.
* @internal
*/
_cx: number;
/**
* The Y-coordinate value of the normalized local X axis,
* the first column of the local transformation matrix without a scale.
* @internal
*/
_sx: number;
/**
* The X-coordinate value of the normalized local Y axis,
* the second column of the local transformation matrix without a scale.
* @internal
*/
_cy: number;
/**
* The Y-coordinate value of the normalized local Y axis,
* the second column of the local transformation matrix without a scale.
* @internal
*/
_sy: number;
/**
* The rotation amount.
* @internal
*/
private _rotation;
/** @internal */
localColor: number;
/** @internal */
localAlpha: number;
/** @internal */
groupAlpha: number;
/** @internal */
groupColor: number;
/** @internal */
groupColorAlpha: number;
/** @internal */
localBlendMode: BLEND_MODES;
/** @internal */
groupBlendMode: BLEND_MODES;
/**
* This property holds three bits: culled, visible, renderable
* the third bit represents culling (0 = culled, 1 = not culled) 0b100
* the second bit represents visibility (0 = not visible, 1 = visible) 0b010
* the first bit represents renderable (0 = not renderable, 1 = renderable) 0b001
* @internal
*/
localDisplayStatus: number;
/** @internal */
globalDisplayStatus: number;
/** @internal */
readonly renderPipeId: string;
/**
* An optional bounds area for this container. Setting this rectangle will stop the renderer
* from recursively measuring the bounds of each children and instead use this single boundArea.
*
* > [!IMPORTANT] This is great for optimisation! If for example you have a
* > 1000 spinning particles and you know they all sit within a specific bounds,
* > then setting it will mean the renderer will not need to measure the
* > 1000 children to find the bounds. Instead it will just use the bounds you set.
* @example
* ```ts
* const container = new Container();
* container.boundsArea = new Rectangle(0, 0, 500, 500);
* ```
*/
boundsArea: Rectangle;
/**
* A value that increments each time the containe is modified
* eg children added, removed etc
* @ignore
*/
_didContainerChangeTick: number;
/**
* A value that increments each time the container view is modified
* eg texture swap, geometry change etc
* @ignore
*/
_didViewChangeTick: number;
/** @internal */
layerParentId: string;
/**
* We now use the _didContainerChangeTick and _didViewChangeTick to track changes
* @deprecated since 8.2.6
* @ignore
*/
set _didChangeId(value: number);
/** @ignore */
get _didChangeId(): number;
/**
* property that tracks if the container transform has changed
* @ignore
*/
private _didLocalTransformChangeId;
constructor(options?: ContainerOptions<C>);
/**
* Adds one or more children to the container.
* The children will be rendered as part of this container's display list.
* @example
* ```ts
* // Add a single child
* container.addChild(sprite);
*
* // Add multiple children
* container.addChild(background, player, foreground);
*
* // Add with type checking
* const sprite = container.addChild<Sprite>(new Sprite(texture));
* sprite.tint = 'red';
* ```
* @param children - The Container(s) to add to the container
* @returns The first child that was added
* @see {@link Container#removeChild} For removing children
* @see {@link Container#addChildAt} For adding at specific index
*/
addChild<U extends C[]>(...children: U): U[0];
/**
* Removes one or more children from the container.
* When removing multiple children, events will be triggered for each child in sequence.
* @example
* ```ts
* // Remove a single child
* const removed = container.removeChild(sprite);
*
* // Remove multiple children
* const bg = container.removeChild(background, player, userInterface);
*
* // Remove with type checking
* const sprite = container.removeChild<Sprite>(childSprite);
* sprite.texture = newTexture;
* ```
* @param children - The Container(s) to remove
* @returns The first child that was removed
* @see {@link Container#addChild} For adding children
* @see {@link Container#removeChildren} For removing multiple children
*/
removeChild<U extends C[]>(...children: U): U[0];
/** @ignore */
_onUpdate(point?: ObservablePoint): void;
set isRenderGroup(value: boolean);
/**
* Returns true if this container is a render group.
* This means that it will be rendered as a separate pass, with its own set of instructions
* @advanced
*/
get isRenderGroup(): boolean;
/**
* Calling this enables a render group for this container.
* This means it will be rendered as a separate set of instructions.
* The transform of the container will also be handled on the GPU rather than the CPU.
* @advanced
*/
enableRenderGroup(): void;
/**
* This will disable the render group for this container.
* @advanced
*/
disableRenderGroup(): void;
/** @ignore */
_updateIsSimple(): void;
/**
* Current transform of the object based on world (parent) factors.
*
* This matrix represents the absolute transformation in the scene graph.
* @example
* ```ts
* // Get world position
* const worldPos = container.worldTransform;
* console.log(`World position: (${worldPos.tx}, ${worldPos.ty})`);
* ```
* @readonly
* @see {@link Container#localTransform} For local space transform
*/
get worldTransform(): Matrix;
/**
* The position of the container on the x axis relative to the local coordinates of the parent.
*
* An alias to position.x
* @example
* ```ts
* // Basic position
* container.x = 100;
* ```
*/
get x(): number;
set x(value: number);
/**
* The position of the container on the y axis relative to the local coordinates of the parent.
*
* An alias to position.y
* @example
* ```ts
* // Basic position
* container.y = 200;
* ```
*/
get y(): number;
set y(value: number);
/**
* The coordinate of the object relative to the local coordinates of the parent.
* @example
* ```ts
* // Basic position setting
* container.position.set(100, 200);
* container.position.set(100); // Sets both x and y to 100
* // Using point data
* container.position = { x: 50, y: 75 };
* ```
* @since 4.0.0
*/
get position(): ObservablePoint;
set position(value: PointData);
/**
* The rotation of the object in radians.
*
* > [!NOTE] 'rotation' and 'angle' have the same effect on a display object;
* > rotation is in radians, angle is in degrees.
* @example
* ```ts
* // Basic rotation
* container.rotation = Math.PI / 4; // 45 degrees
*
* // Convert from degrees
* const degrees = 45;
* container.rotation = degrees * Math.PI / 180;
*
* // Rotate around center
* container.pivot.set(container.width / 2, container.height / 2);
* container.rotation = Math.PI; // 180 degrees
*
* // Rotate around center with origin
* container.origin.set(container.width / 2, container.height / 2);
* container.rotation = Math.PI; // 180 degrees
* ```
*/
get rotation(): number;
set rotation(value: number);
/**
* The angle of the object in degrees.
*
* > [!NOTE] 'rotation' and 'angle' have the same effect on a display object;
* > rotation is in radians, angle is in degrees.
* @example
* ```ts
* // Basic angle rotation
* sprite.angle = 45; // 45 degrees
*
* // Rotate around center
* sprite.pivot.set(sprite.width / 2, sprite.height / 2);
* sprite.angle = 180; // Half rotation
*
* // Rotate around center with origin
* sprite.origin.set(sprite.width / 2, sprite.height / 2);
* sprite.angle = 180; // Half rotation
*
* // Reset rotation
* sprite.angle = 0;
* ```
*/
get angle(): number;
set angle(value: number);
/**
* The center of rotation, scaling, and skewing for this display object in its local space.
* The `position` is the projection of `pivot` in the parent's local space.
*
* By default, the pivot is the origin (0, 0).
* @example
* ```ts
* // Rotate around center
* container.pivot.set(container.width / 2, container.height / 2);
* container.rotation = Math.PI; // Rotates around center
* ```
* @since 4.0.0
*/
get pivot(): ObservablePoint;
set pivot(value: PointData | number);
/**
* The skew factor for the object in radians. Skewing is a transformation that distorts
* the object by rotating it differently at each point, creating a non-uniform shape.
* @example
* ```ts
* // Basic skewing
* container.skew.set(0.5, 0); // Skew horizontally
* container.skew.set(0, 0.5); // Skew vertically
*
* // Skew with point data
* container.skew = { x: 0.3, y: 0.3 }; // Diagonal skew
*
* // Reset skew
* container.skew.set(0, 0);
*
* // Animate skew
* app.ticker.add(() => {
* // Create wave effect
* container.skew.x = Math.sin(Date.now() / 1000) * 0.3;
* });
*
* // Combine with rotation
* container.rotation = Math.PI / 4; // 45 degrees
* container.skew.set(0.2, 0.2); // Skew the rotated object
* ```
* @since 4.0.0
* @type {ObservablePoint} Point-like object with x/y properties in radians
* @default {x: 0, y: 0}
*/
get skew(): ObservablePoint;
set skew(value: PointData);
/**
* The scale factors of this object along the local coordinate axes.
*
* The default scale is (1, 1).
* @example
* ```ts
* // Basic scaling
* container.scale.set(2, 2); // Scales to double size
* container.scale.set(2); // Scales uniformly to double size
* container.scale = 2; // Scales uniformly to double size
* // Scale to a specific width and height
* container.setSize(200, 100); // Sets width to 200 and height to 100
* ```
* @since 4.0.0
*/
get scale(): ObservablePoint;
set scale(value: PointData | number | string);
/**
* @experimental
* The origin point around which the container rotates and scales without affecting its position.
* Unlike pivot, changing the origin will not move the container's position.
* @example
* ```ts
* // Rotate around center point
* container.origin.set(container.width / 2, container.height / 2);
* container.rotation = Math.PI; // Rotates around center
*
* // Reset origin
* container.origin.set(0, 0);
* ```
*/
get origin(): ObservablePoint;
set origin(value: PointData | number);
/**
* The width of the Container, setting this will actually modify the scale to achieve the value set.
* > [!NOTE] Changing the width will adjust the scale.x property of the container while maintaining its aspect ratio.
* > [!NOTE] If you want to set both width and height at the same time, use {@link Container#setSize}
* as it is more optimized by not recalculating the local bounds twice.
* @example
* ```ts
* // Basic width setting
* container.width = 100;
* // Optimized width setting
* container.setSize(100, 100);
* ```
*/
get width(): number;
set width(value: number);
/**
* The height of the Container,
* > [!NOTE] Changing the height will adjust the scale.y property of the container while maintaining its aspect ratio.
* > [!NOTE] If you want to set both width and height at the same time, use {@link Container#setSize}
* as it is more optimized by not recalculating the local bounds twice.
* @example
* ```ts
* // Basic height setting
* container.height = 200;
* // Optimized height setting
* container.setSize(100, 200);
* ```
*/
get height(): number;
set height(value: number);
/**
* Retrieves the size of the container as a [Size]{@link Size} object.
*
* This is faster than get the width and height separately.
* @example
* ```ts
* // Basic size retrieval
* const size = container.getSize();
* console.log(`Size: ${size.width}x${size.height}`);
*
* // Reuse existing size object
* const reuseSize = { width: 0, height: 0 };
* container.getSize(reuseSize);
* ```
* @param out - Optional object to store the size in.
* @returns The size of the container.
*/
getSize(out?: Size): Size;
/**
* Sets the size of the container to the specified width and height.
* This is more efficient than setting width and height separately as it only recalculates bounds once.
* @example
* ```ts
* // Basic size setting
* container.setSize(100, 200);
*
* // Set uniform size
* container.setSize(100); // Sets both width and height to 100
* ```
* @param value - This can be either a number or a [Size]{@link Size} object.
* @param height - The height to set. Defaults to the value of `width` if not provided.
*/
setSize(value: number | Optional<Size, "height">, height?: number): void;
/** Called when the skew or the rotation changes. */
private _updateSkew;
/**
* Updates the transform properties of the container.
* Allows partial updates of transform properties for optimized manipulation.
* @example
* ```ts
* // Basic transform update
* container.updateTransform({
* x: 100,
* y: 200,
* rotation: Math.PI / 4
* });
*
* // Scale and rotate around center
* sprite.updateTransform({
* pivotX: sprite.width / 2,
* pivotY: sprite.height / 2,
* scaleX: 2,
* scaleY: 2,
* rotation: Math.PI
* });
*
* // Update position only
* button.updateTransform({
* x: button.x + 10, // Move right
* y: button.y // Keep same y
* });
* ```
* @param opts - Transform options to update
* @param opts.x - The x position
* @param opts.y - The y position
* @param opts.scaleX - The x-axis scale factor
* @param opts.scaleY - The y-axis scale factor
* @param opts.rotation - The rotation in radians
* @param opts.skewX - The x-axis skew factor
* @param opts.skewY - The y-axis skew factor
* @param opts.pivotX - The x-axis pivot point
* @param opts.pivotY - The y-axis pivot point
* @returns This container, for chaining
* @see {@link Container#setFromMatrix} For matrix-based transforms
* @see {@link Container#position} For direct position access
*/
updateTransform(opts: Partial<UpdateTransformOptions>): this;
/**
* Updates the local transform properties by decomposing the given matrix.
* Extracts position, scale, rotation, and skew from a transformation matrix.
* @example
* ```ts
* // Basic matrix transform
* const matrix = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4)
* .scale(2, 2);
*
* container.setFromMatrix(matrix);
*
* // Copy transform from another container
* const source = new Container();
* source.position.set(100, 100);
* source.rotation = Math.PI / 2;
*
* target.setFromMatrix(source.localTransform);
*
* // Reset transform
* container.setFromMatrix(Matrix.IDENTITY);
* ```
* @param matrix - The matrix to use for updating the transform
* @see {@link Container#updateTransform} For property-based updates
* @see {@link Matrix#decompose} For matrix decomposition details
*/
setFromMatrix(matrix: Matrix): void;
/** Updates the local transform. */
updateLocalTransform(): void;
set alpha(value: number);
/**
* The opacity of the object relative to its parent's opacity.
* Value ranges from 0 (fully transparent) to 1 (fully opaque).
* @example
* ```ts
* // Basic transparency
* sprite.alpha = 0.5; // 50% opacity
*
* // Inherited opacity
* container.alpha = 0.5;
* const child = new Sprite(texture);
* child.alpha = 0.5;
* container.addChild(child);
* // child's effective opacity is 0.25 (0.5 * 0.5)
* ```
* @default 1
* @see {@link Container#visible} For toggling visibility
* @see {@link Container#renderable} For render control
*/
get alpha(): number;
set tint(value: ColorSource);
/**
* The tint applied to the sprite.
*
* This can be any valid {@link ColorSource}.
* @example
* ```ts
* // Basic color tinting
* container.tint = 0xff0000; // Red tint
* container.tint = 'red'; // Same as above
* container.tint = '#00ff00'; // Green
* container.tint = 'rgb(0,0,255)'; // Blue
*
* // Remove tint
* container.tint = 0xffffff; // White = no tint
* container.tint = null; // Also removes tint
* ```
* @default 0xFFFFFF
* @see {@link Container#alpha} For transparency
* @see {@link Container#visible} For visibility control
*/
get tint(): number;
set blendMode(value: BLEND_MODES);
/**
* The blend mode to be applied to the sprite. Controls how pixels are blended when rendering.
*
* Setting to 'normal' will reset to default blending.
* > [!NOTE] More blend modes are available after importing the `pixi.js/advanced-blend-modes` sub-export.
* @example
* ```ts
* // Basic blend modes
* sprite.blendMode = 'add'; // Additive blending
* sprite.blendMode = 'multiply'; // Multiply colors
* sprite.blendMode = 'screen'; // Screen blend
*
* // Reset blend mode
* sprite.blendMode = 'normal'; // Normal blending
* ```
* @default 'normal'
* @see {@link Container#alpha} For transparency
* @see {@link Container#tint} For color adjustments
*/
get blendMode(): BLEND_MODES;
/**
* The visibility of the object. If false the object will not be drawn,
* and the transform will not be updated.
* @example
* ```ts
* // Basic visibility toggle
* sprite.visible = false; // Hide sprite
* sprite.visible = true; // Show sprite
* ```
* @default true
* @see {@link Container#renderable} For render-only control
* @see {@link Container#alpha} For transparency
*/
get visible(): boolean;
set visible(value: boolean);
/** @ignore */
get culled(): boolean;
/** @ignore */
set culled(value: boolean);
/**
* Controls whether this object can be rendered. If false the object will not be drawn,
* but the transform will still be updated. This is different from visible, which skips
* transform updates.
* @example
* ```ts
* // Basic render control
* sprite.renderable = false; // Skip rendering
* sprite.renderable = true; // Enable rendering
* ```
* @default true
* @see {@link Container#visible} For skipping transform updates
* @see {@link Container#alpha} For transparency
*/
get renderable(): boolean;
set renderable(value: boolean);
/**
* Whether or not the object should be rendered.
* @advanced
*/
get isRenderable(): boolean;
/**
* Removes all internal references and listeners as well as removes children from the display list.
* Do not use a Container after calling `destroy`.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* ```ts
* container.destroy();
* container.destroy(true);
* container.destroy({ children: true });
* container.destroy({ children: true, texture: true, textureSource: true });
* ```
*/
destroy(options?: DestroyOptions): void;
}
/**
* The type of the pointer event to listen for.
* @category accessibility
* @standard
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
*/
export type PointerEvents = "auto" | "none" | "visiblePainted" | "visibleFill" | "visibleStroke" | "visible" | "painted" | "fill" | "stroke" | "all" | "inherit";
/**
* When `accessible` is enabled on any display object, these properties will affect its accessibility.
* @example
* const container = new Container();
* container.accessible = true;
* container.accessibleTitle = 'My Container';
* container.accessibleHint = 'This is a container';
* container.tabIndex = 0;
* @category accessibility
* @standard
*/
export interface AccessibleOptions {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @default false
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* ```
*/
accessible: boolean;
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]'
* @type {string}
* @default null
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessibleTitle = 'My Container';
* ```
*/
accessibleTitle: string | null;
/**
* Sets the aria-label attribute of the shadow div
* @default null
* @advanced
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessibleHint = 'This is a container';
* ```
*/
accessibleHint: string | null;
/**
* Sets the tabIndex of the shadow div. You can use this to set the order of the
* elements when using the tab key to navigate.
* @default 0
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.tabIndex = 0;
*
* const sprite = new Sprite(texture);
* sprite.accessible = true;
* sprite.tabIndex = 1;
* ```
*/
tabIndex: number;
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @default 'button'
* @type {string}
* @advanced
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessibleType = 'button'; // or 'link', 'checkbox', etc.
* ```
*/
accessibleType: keyof HTMLElementTagNameMap;
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @default 'auto'
* @type {PointerEvents}
* @advanced
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessiblePointerEvents = 'none'; // or 'auto', 'visiblePainted', etc.
* ```
*/
accessiblePointerEvents: PointerEvents;
/**
* Sets the text content of the shadow
* @default null
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessibleText = 'This is a container';
* ```
*/
accessibleText: string | null;
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @default true
* @example
* ```js
* const container = new Container();
* container.accessible = true;
* container.accessibleChildren = false; // This will prevent any children from being accessible
*
* const sprite = new Sprite(texture);
* sprite.accessible = true; // This will not work since accessibleChildren is false
* ```
*/
accessibleChildren: boolean;
}
/**
* The Accessibility object is attached to the {@link Container}.
* @private
*/
export interface AccessibleTarget extends AccessibleOptions {
/** @private */
_accessibleActive: boolean;
/** @private */
_accessibleDiv: AccessibleHTMLElement | null;
/** @private */
_renderId: number;
}
/** @internal */
export interface AccessibleHTMLElement extends HTMLElement {
type?: string;
container?: Container;
}
/**
* Default property values of accessible objects
* used by {@link AccessibilitySystem}.
* @internal
* @example
* import { accessibleTarget } from 'pixi.js';
*
* function MyObject() {}
* Object.assign(MyObject.prototype, accessibleTarget);
*/
export declare const accessibilityTarget: AccessibleTarget;
/**
* The result of the mobile device detection system.
* Provides detailed information about device type and platform.
* @example
* ```ts
* // Type usage with isMobile
* const deviceInfo: isMobileResult = isMobile;
*
* // Check device categories
* if (deviceInfo.apple.device) {
* console.log('iOS Device Details:', {
* isPhone: deviceInfo.apple.phone,
* isTablet: deviceInfo.apple.tablet,
* isUniversal: deviceInfo.apple.universal
* });
* }
*
* // Platform-specific checks
* const platformInfo = {
* isApple: deviceInfo.apple.device,
* isAndroid: deviceInfo.android.device,
* isAmazon: deviceInfo.amazon.device,
* isWindows: deviceInfo.windows.device
* };
* ```
* @category utils
* @standard
*/
export type isMobileResult = {
/**
* Apple device detection information.
* Provides detailed iOS device categorization.
* @example
* ```ts
* // iOS device checks
* if (isMobile.apple.device) {
* if (isMobile.apple.tablet) {
* // iPad-specific code
* useTabletLayout();
* } else if (isMobile.apple.phone) {
* // iPhone-specific code
* usePhoneLayout();
* }
* }
* ```
*/
apple: {
/** Whether the device is an iPhone */
phone: boolean;
/** Whether the device is an iPod Touch */
ipod: boolean;
/** Whether the device is an iPad */
tablet: boolean;
/** Whether app is running in iOS universal mode */
universal: boolean;
/** Whether device is any Apple mobile device */
device: boolean;
};
/**
* Amazon device detection information.
* Identifies Amazon Fire tablets and phones.
* @example
* ```ts
* // Amazon Fire tablet detection
* if (isMobile.amazon.tablet) {
* // Fire tablet optimizations
* optimizeForFireTablet();
* }
* ```
*/
amazon: {
/** Whether device is a Fire Phone */
phone: boolean;
/** Whether device is a Fire Tablet */
tablet: boolean;
/** Whether device is any Amazon mobile device */
device: boolean;
};
/**
* Android device detection information.
* Categorizes Android phones and tablets.
* @example
* ```ts
* // Android device handling
* if (isMobile.android.device) {
* // Check specific type
* const deviceType = isMobile.android.tablet ?
* 'tablet' : 'phone';
* console.log(`Android ${deviceType} detected`);
* }
* ```
*/
android: {
/** Whether device is an Android phone */
phone: boolean;
/** Whether device is an Android tablet */
tablet: boolean;
/** Whether device is any Android device */
device: boolean;
};
/**
* Windows device detection information.
* Identifies Windows phones and tablets.
* @example
* ```ts
* // Windows device checks
* if (isMobile.windows.tablet) {
* // Surface tablet optimizations
* enableTouchFeatures();
* }
* ```
*/
windows: {
/** Whether device is a Windows Phone */
phone: boolean;
/** Whether device is a Windows tablet */
tablet: boolean;
/** Whether device is any Windows mobile device */
device: boolean;
};
/**
* Other device detection information.
* Covers additional platforms and browsers.
* @example
* ```ts
* // Check other platforms
* if (isMobile.other.blackberry10) {
* // BlackBerry 10 specific code
* } else if (isMobile.other.chrome) {
* // Chrome mobile specific code
* }
* ```
*/
other: {
/** Whether device is a BlackBerry */
blackberry: boolean;
/** Whether device is a BlackBerry 10 */
blackberry10: boolean;
/** Whether browser is Opera Mobile */
opera: boolean;
/** Whether browser is Firefox Mobile */
firefox: boolean;
/** Whether browser is Chrome Mobile */
chrome: boolean;
/** Whether device is any other mobile device */
device: boolean;
};
/**
* Whether the device is any type of phone.
* Combines detection across all platforms.
* @example
* ```ts
* // Check if device is a phone
* if (isMobile.phone) {
* console.log('Running on a mobile phone');
* }
* ```
*/
phone: boolean;
/**
* Whether the device is any type of tablet.
* Combines detection across all platforms.
* @example
* ```ts
* // Check if device is a tablet
* if (isMobile.tablet) {
* console.log('Running on a mobile tablet');
* }
* ```
*/
tablet: boolean;
/**
* Whether the device is any type of mobile device.
* True if any mobile platform is detected.
* @example
* ```ts
* // Check if device is mobile
* if (isMobile.any) {
* console.log('Running on a mobile device');
* }
* ```
*/
any: boolean;
};
/**
* Detects whether the device is mobile and what type of mobile device it is.
* Provides a comprehensive detection system for mobile platforms and devices.
* @example
* ```ts
* import { isMobile } from 'pixi.js';
*
* // Check specific device types
* if (isMobile.apple.tablet) {
* console.log('Running on iPad');
* }
*
* // Check platform categories
* if (isMobile.android.any) {
* console.log('Running on Android');
* }
*
* // Conditional rendering
* if (isMobile.phone) {
* renderer.resolution = 2;
* view.style.width = '100vw';
* }
* ```
* @remarks
* - Detects all major mobile platforms
* - Distinguishes between phones and tablets
* - Updates when navigator changes
* - Common in responsive design
* @category utils
* @standard
* @see {@link isMobileResult} For full type definition
*/
export declare const isMobile: isMobileResult;
/**
* Initialisation options for the accessibility system when used with an Application.
* @category accessibility
* @advanced
*/
export interface AccessibilitySystemOptions {
/** Options for the accessibility system */
accessibilityOptions?: AccessibilityOptions;
}
/**
* The options for the accessibility system.
* @category accessibility
* @advanced
*/
export interface AccessibilityOptions {
/** Whether to enable accessibility features on initialization instead of waiting for tab key */
enabledByDefault?: boolean;
/** Whether to visually show the accessibility divs for debugging */
debug?: boolean;
/** Whether to allow tab key press to activate accessibility features */
activateOnTab?: boolean;
/** Whether to deactivate accessibility when mouse moves */
deactivateOnMouseMove?: boolean;
}
/**
* The Accessibility system provides screen reader and keyboard navigation support for PixiJS content.
* It creates an accessible DOM layer over the canvas that can be controlled programmatically or through user interaction.
*
* By default, the system activates when users press the tab key. This behavior can be customized through options:
* ```js
* const app = new Application({
* accessibilityOptions: {
* // Enable immediately instead of waiting for tab
* enabledByDefault: true,
* // Disable tab key activation
* activateOnTab: false,
* // Show/hide accessibility divs
* debug: false,
* // Prevent accessibility from being deactivated when mouse moves
* deactivateOnMouseMove: false,
* }
* });
* ```
*
* The system can also be controlled programmatically by accessing the `renderer.accessibility` property:
* ```js
* app.renderer.accessibility.setAccessibilityEnabled(true);
* ```
*
* To make individual containers accessible:
* ```js
* container.accessible = true;
* ```
* There are several properties that can be set on a Container to control its accessibility which can
* be found here: {@link AccessibleOptions}.
* @category accessibility
* @standard
*/
export declare class AccessibilitySystem implements System<AccessibilitySystemOptions> {
private readonly _mobileInfo;
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "accessibility";
};
/**
* The default options used by the system.
* You can set these before initializing the {@link Application} to change the default behavior.
* @example
* ```js
* import { AccessibilitySystem } from 'pixi.js';
*
* AccessibilitySystem.defaultOptions.enabledByDefault = true;
*
* const app = new Application()
* app.init()
* ```
*/
static defaultOptions: AccessibilityOptions;
/** Whether accessibility divs are visible for debugging */
debug: boolean;
/** Whether to activate on tab key press */
private _activateOnTab;
/** Whether to deactivate accessibility when mouse moves */
private _deactivateOnMouseMove;
/**
* The renderer this accessibility manager works for.
* @type {WebGLRenderer|WebGPURenderer}
*/
private _renderer;
/** Internal variable, see isActive getter. */
private _isActive;
/** Internal variable, see isMobileAccessibility getter. */
private _isMobileAccessibility;
/** Button element for handling touch hooks. */
private _hookDiv;
/** This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. */
private _div;
/** A simple pool for storing divs. */
private _pools;
/** This is a tick used to check if an object is no longer being rendered. */
private _renderId;
/** The array of currently active accessible items. */
private _children;
/** Count to throttle div updates on android devices. */
private _androidUpdateCount;
/** The frequency to update the div elements. */
private readonly _androidUpdateFrequency;
private _canvasObserver;
private _isRunningTests;
/** Bound function references for proper event listener removal */
private _boundOnKeyDown;
private _boundOnMouseMove;
/**
* @param {WebGLRenderer|WebGPURenderer} renderer - A reference to the current renderer
*/
constructor(renderer: Renderer, _mobileInfo?: isMobileResult);
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @type {boolean}
* @readonly
*/
get isActive(): boolean;
/**
* Value of `true` if accessibility is enabled for touch devices.
* @type {boolean}
* @readonly
*/
get isMobileAccessibility(): boolean;
/**
* Button element for handling touch hooks.
* @readonly
*/
get hookDiv(): HTMLElement;
/**
* The DOM element that will sit over the PixiJS element. This is where the div overlays will go.
* @readonly
*/
get div(): HTMLElement;
/**
* Creates the touch hooks.
* @private
*/
private _createTouchHook;
/**
* Destroys the touch hooks.
* @private
*/
private _destroyTouchHook;
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
private _activate;
private _initAccessibilitySetup;
/**
* Deactivates the accessibility system. Removes listeners and accessibility elements.
* @private
*/
private _deactivate;
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {Container} container - The Container to check.
*/
private _updateAccessibleObjects;
/**
* Runner init called, view is available at this point.
* @ignore
*/
init(options?: AccessibilitySystemOptions): void;
/**
* Updates the accessibility layer during rendering.
* - Removes divs for containers no longer in the scene
* - Updates the position and dimensions of the root div
* - Updates positions of active accessibility divs
* Only fires while the accessibility system is active.
* @ignore
*/
postrender(): void;
/**
* private function that will visually add the information to the
* accessibility div
* @param {HTMLElement} div -
*/
private _updateDebugHTML;
/**
* Adjust the hit area based on the bounds of a display object
* @param {Rectangle} hitArea - Bounds of the child
*/
private _capHitArea;
/**
* Creates or reuses a div element for a Container and adds it to the accessibility layer.
* Sets up ARIA attributes, event listeners, and positioning based on the container's properties.
* @private
* @param {Container} container - The child to make accessible.
*/
private _addChild;
/**
* Dispatch events with the EventSystem.
* @param e
* @param type
* @private
*/
private _dispatchEvent;
/**
* Maps the div button press to pixi's EventSystem (click)
* @private
* @param {MouseEvent} e - The click event.
*/
private _onClick;
/**
* Maps the div focus events to pixi's EventSystem (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
private _onFocus;
/**
* Maps the div focus events to pixi's EventSystem (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
private _onFocusOut;
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
private _onKeyDown;
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
private _onMouseMove;
/**
* Destroys the accessibility system. Removes all elements and listeners.
* > [!IMPORTANT] This is typically called automatically when the {@link Application} is destroyed.
* > A typically user should not need to call this method directly.
*/
destroy(): void;
/**
* Enables or disables the accessibility system.
* @param enabled - Whether to enable or disable accessibility.
* @example
* ```js
* app.renderer.accessibility.setAccessibilityEnabled(true); // Enable accessibility
* app.renderer.accessibility.setAccessibilityEnabled(false); // Disable accessibility
* ```
*/
setAccessibilityEnabled(enabled: boolean): void;
private _getPool;
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface Container extends Partial<AccessibleTarget> {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ContainerOptions extends Partial<AccessibleOptions> {
}
interface RendererSystems {
accessibility: AccessibilitySystem;
}
}
}
/**
* A callback which can be added to a ticker.
* The callback receives the Ticker instance as its parameter, providing access to timing properties.
* @example
* ```ts
* ticker.add((ticker) => {
* // Access deltaTime (dimensionless scalar ~1.0 at 60fps)
* sprite.rotation += 0.1 * ticker.deltaTime;
*
* // Access deltaMS (milliseconds elapsed)
* const progress = ticker.deltaMS / animationDuration;
* });
* ```
* @category ticker
* @standard
*/
export type TickerCallback<T> = (this: T, ticker: Ticker) => any;
/**
* A Ticker class that runs an update loop that other objects listen to.
* Used for managing animation frames and timing in a PixiJS application.
*
* It provides a way to add listeners that will be called on each frame,
* allowing for smooth animations and updates.
*
* ## Time Units
* - `deltaTime`: Dimensionless scalar (typically ~1.0 at 60 FPS) for frame-independent animations
* - `deltaMS`: Milliseconds elapsed (capped and speed-scaled) for time-based calculations
* - `elapsedMS`: Raw milliseconds elapsed (uncapped, unscaled) for measurements
* - `lastTime`: Timestamp in milliseconds since epoch (performance.now() format)
*
* Animation frames are requested
* only when necessary, e.g., when the ticker is started and the emitter has listeners.
* @example
* ```ts
* // Basic ticker usage with different time units
* const ticker = new Ticker();
* ticker.add((ticker) => {
* // Frame-independent animation using dimensionless deltaTime
* sprite.rotation += 0.1 * ticker.deltaTime;
*
* // Time-based animation using deltaMS (milliseconds)
* sprite.x += (100 / 1000) * ticker.deltaMS; // 100 pixels per second
* });
* ticker.start();
*
* // Control update priority
* ticker.add(
* (ticker) => {
* // High priority updates run first
* physics.update(ticker.deltaTime);
* },
* undefined,
* UPDATE_PRIORITY.HIGH
* );
*
* // One-time updates
* ticker.addOnce(() => {
* console.log('Runs on next frame only');
* });
* ```
* @see {@link TickerPlugin} For use with Application
* @see {@link UPDATE_PRIORITY} For priority constants
* @see {@link TickerCallback} For listener function type
* @category ticker
* @standard
*/
export declare class Ticker {
/**
* Target frame rate in frames per millisecond.
* Used for converting deltaTime to a scalar time delta.
* @example
* ```ts
* // Default is 0.06 (60 FPS)
* console.log(Ticker.targetFPMS); // 0.06
*
* // Calculate target frame duration
* const frameDuration = 1 / Ticker.targetFPMS; // ≈ 16.67ms
*
* // Use in custom timing calculations
* const deltaTime = elapsedMS * Ticker.targetFPMS;
* ```
* @remarks
* - Default is 0.06 (equivalent to 60 FPS)
* - Used in deltaTime calculations
* - Affects all ticker instances
* @default 0.06
* @see {@link Ticker#deltaTime} For time scaling
* @see {@link Ticker#FPS} For actual frame rate
*/
static targetFPMS: number;
/** The private shared ticker instance */
private static _shared;
/** The private system ticker instance */
private static _system;
/**
* Whether or not this ticker should invoke the method {@link Ticker#start|start}
* automatically when a listener is added.
* @example
* ```ts
* // Default behavior (manual start)
* const ticker = new Ticker();
* ticker.autoStart = false;
* ticker.add(() => {
* // Won't run until ticker.start() is called
* });
*
* // Auto-start behavior
* const autoTicker = new Ticker();
* autoTicker.autoStart = true;
* autoTicker.add(() => {
* // Runs immediately when added
* });
* ```
* @default false
* @see {@link Ticker#start} For manually starting the ticker
* @see {@link Ticker#stop} For manually stopping the ticker
*/
autoStart: boolean;
/**
* Scalar representing the delta time factor.
* This is a dimensionless value representing the fraction of a frame at the target framerate.
* At 60 FPS, this value is typically around 1.0.
*
* This is NOT in milliseconds - it's a scalar multiplier for frame-independent animations.
* For actual milliseconds, use {@link Ticker#deltaMS}.
* @example
* ```ts
* // Frame-independent animation using deltaTime scalar
* ticker.add((ticker) => {
* // Rotate sprite by 0.1 radians per frame, scaled by deltaTime
* sprite.rotation += 0.1 * ticker.deltaTime;
* });
* ```
*/
deltaTime: number;
/**
* Scalar time elapsed in milliseconds from last frame to this frame.
* Provides precise timing for animations and updates.
*
* This value is capped by setting {@link Ticker#minFPS|minFPS}
* and is scaled with {@link Ticker#speed|speed}.
*
* If the platform supports DOMHighResTimeStamp,
* this value will have a precision of 1 µs.
*
* Defaults to target frame time
*
* > [!NOTE] The cap may be exceeded by scaling.
* @example
* ```ts
* // Animation timing
* ticker.add((ticker) => {
* // Use millisecond timing for precise animations
* const progress = (ticker.deltaMS / animationDuration);
* sprite.alpha = Math.min(1, progress);
* });
* ```
* @default 16.66
*/
deltaMS: number;
/**
* Time elapsed in milliseconds from the last frame to this frame.
* This value is not capped or scaled and provides raw timing information.
*
* Unlike {@link Ticker#deltaMS}, this value is unmodified by speed scaling or FPS capping.
* @example
* ```ts
* ticker.add((ticker) => {
* console.log(`Raw frame time: ${ticker.elapsedMS}ms`);
* });
* ```
*/
elapsedMS: number;
/**
* The last time update was invoked, in milliseconds since epoch.
* Similar to performance.now() timestamp format.
*
* Used internally for calculating time deltas between frames.
* @example
* ```ts
* ticker.add((ticker) => {
* const currentTime = performance.now();
* const timeSinceLastFrame = currentTime - ticker.lastTime;
* console.log(`Time since last frame: ${timeSinceLastFrame}ms`);
* });
* ```
*/
lastTime: number;
/**
* Factor of current {@link Ticker#deltaTime|deltaTime}.
* Used to scale time for slow motion or fast-forward effects.
* @example
* ```ts
* // Basic speed adjustment
* ticker.speed = 0.5; // Half speed (slow motion)
* ticker.speed = 2.0; // Double speed (fast forward)
*
* // Temporary speed changes
* function slowMotion() {
* const normalSpeed = ticker.speed;
* ticker.speed = 0.2;
* setTimeout(() => {
* ticker.speed = normalSpeed;
* }, 1000);
* }
* ```
*/
speed: number;
/**
* Whether or not this ticker has been started.
*
* `true` if {@link Ticker#start|start} has been called.
* `false` if {@link Ticker#stop|Stop} has been called.
*
* While `false`, this value may change to `true` in the
* event of {@link Ticker#autoStart|autoStart} being `true`
* and a listener is added.
* @example
* ```ts
* // Check ticker state
* const ticker = new Ticker();
* console.log(ticker.started); // false
*
* // Start and verify
* ticker.start();
* console.log(ticker.started); // true
* ```
*/
started: boolean;
/** The first listener. All new listeners added are chained on this. */
private _head;
/** Internal current frame request ID */
private _requestId;
/**
* Internal value managed by minFPS property setter and getter.
* This is the maximum allowed milliseconds between updates.
*/
private _maxElapsedMS;
/**
* Internal value managed by minFPS property setter and getter.
* This is the minimum allowed milliseconds between updates.
*/
private _minElapsedMS;
/** If enabled, deleting is disabled.*/
private _protected;
/** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */
private _lastFrame;
/**
* Internal tick method bound to ticker instance.
* This is because in early 2015, Function.bind
* is still 60% slower in high performance scenarios.
* Also separating frame requests from update method
* so listeners may be called at any time and with
* any animation API, just invoke ticker.update(time).
* @param time - Time since last tick.
*/
private readonly _tick;
constructor();
/**
* Conditionally requests a new animation frame.
* If a frame has not already been requested, and if the internal
* emitter has listeners, a new frame is requested.
*/
private _requestIfNeeded;
/** Conditionally cancels a pending animation frame. */
private _cancelIfNeeded;
/**
* Conditionally requests a new animation frame.
* If the ticker has been started it checks if a frame has not already
* been requested, and if the internal emitter has listeners. If these
* conditions are met, a new frame is requested. If the ticker has not
* been started, but autoStart is `true`, then the ticker starts now,
* and continues with the previous conditions to request a new frame.
*/
private _startIfPossible;
/**
* Register a handler for tick events.
* @param fn - The listener function to add. Receives the Ticker instance as parameter
* @param context - The context for the listener
* @param priority - The priority of the listener
* @example
* ```ts
* // Access time properties through the ticker parameter
* ticker.add((ticker) => {
* // Use deltaTime (dimensionless scalar) for frame-independent animations
* sprite.rotation += 0.1 * ticker.deltaTime;
*
* // Use deltaMS (milliseconds) for time-based calculations
* const progress = ticker.deltaMS / animationDuration;
*
* // Use elapsedMS for raw timing measurements
* console.log(`Raw frame time: ${ticker.elapsedMS}ms`);
* });
* ```
*/
add<T = any>(fn: TickerCallback<T>, context?: T, priority?: number): this;
/**
* Add a handler for the tick event which is only executed once on the next frame.
* @example
* ```ts
* // Basic one-time update
* ticker.addOnce(() => {
* console.log('Runs next frame only');
* });
*
* // With specific context
* const game = {
* init(ticker) {
* this.loadResources();
* console.log('Game initialized');
* }
* };
* ticker.addOnce(game.init, game);
*
* // With priority
* ticker.addOnce(
* () => {
* // High priority one-time setup
* physics.init();
* },
* undefined,
* UPDATE_PRIORITY.HIGH
* );
* ```
* @param fn - The listener function to be added for one update
* @param context - The listener context
* @param priority - The priority for emitting (default: UPDATE_PRIORITY.NORMAL)
* @returns This instance of a ticker
* @see {@link Ticker#add} For continuous updates
* @see {@link Ticker#remove} For removing handlers
*/
addOnce<T = any>(fn: TickerCallback<T>, context?: T, priority?: number): this;
/**
* Internally adds the event handler so that it can be sorted by priority.
* Priority allows certain handler (user, AnimatedSprite, Interaction) to be run
* before the rendering.
* @private
* @param listener - Current listener being added.
* @returns This instance of a ticker
*/
private _addListener;
/**
* Removes any handlers matching the function and context parameters.
* If no handlers are left after removing, then it cancels the animation frame.
* @example
* ```ts
* // Basic removal
* const onTick = () => {
* sprite.rotation += 0.1;
* };
* ticker.add(onTick);
* ticker.remove(onTick);
*
* // Remove with context
* const game = {
* update(ticker) {
* this.physics.update(ticker.deltaTime);
* }
* };
* ticker.add(game.update, game);
* ticker.remove(game.update, game);
*
* // Remove all matching handlers
* // (if same function was added multiple times)
* ticker.add(onTick);
* ticker.add(onTick);
* ticker.remove(onTick); // Removes all instances
* ```
* @param fn - The listener function to be removed
* @param context - The listener context to be removed
* @returns This instance of a ticker
* @see {@link Ticker#add} For adding handlers
* @see {@link Ticker#addOnce} For one-time handlers
*/
remove<T = any>(fn: TickerCallback<T>, context?: T): this;
/**
* The number of listeners on this ticker, calculated by walking through linked list.
* @example
* ```ts
* // Check number of active listeners
* const ticker = new Ticker();
* console.log(ticker.count); // 0
*
* // Add some listeners
* ticker.add(() => {});
* ticker.add(() => {});
* console.log(ticker.count); // 2
*
* // Check after cleanup
* ticker.destroy();
* console.log(ticker.count); // 0
* ```
* @readonly
* @see {@link Ticker#add} For adding listeners
* @see {@link Ticker#remove} For removing listeners
*/
get count(): number;
/**
* Starts the ticker. If the ticker has listeners a new animation frame is requested at this point.
* @example
* ```ts
* // Basic manual start
* const ticker = new Ticker();
* ticker.add(() => {
* // Animation code here
* });
* ticker.start();
* ```
* @see {@link Ticker#stop} For stopping the ticker
* @see {@link Ticker#autoStart} For automatic starting
* @see {@link Ticker#started} For checking ticker state
*/
start(): void;
/**
* Stops the ticker. If the ticker has requested an animation frame it is canceled at this point.
* @example
* ```ts
* // Basic stop
* const ticker = new Ticker();
* ticker.stop();
* ```
* @see {@link Ticker#start} For starting the ticker
* @see {@link Ticker#started} For checking ticker state
* @see {@link Ticker#destroy} For cleaning up the ticker
*/
stop(): void;
/**
* Destroy the ticker and don't use after this. Calling this method removes all references to internal events.
* @example
* ```ts
* // Clean up with active listeners
* const ticker = new Ticker();
* ticker.add(() => {});
* ticker.destroy(); // Removes all listeners
* ```
* @see {@link Ticker#stop} For stopping without destroying
* @see {@link Ticker#remove} For removing specific listeners
*/
destroy(): void;
/**
* Triggers an update.
*
* An update entails setting the
* current {@link Ticker#elapsedMS|elapsedMS},
* the current {@link Ticker#deltaTime|deltaTime},
* invoking all listeners with current deltaTime,
* and then finally setting {@link Ticker#lastTime|lastTime}
* with the value of currentTime that was provided.
*
* This method will be called automatically by animation
* frame callbacks if the ticker instance has been started
* and listeners are added.
* @example
* ```ts
* // Basic manual update
* const ticker = new Ticker();
* ticker.update(performance.now());
* ```
* @param currentTime - The current time of execution (defaults to performance.now())
* @see {@link Ticker#deltaTime} For frame delta value
* @see {@link Ticker#elapsedMS} For raw elapsed time
*/
update(currentTime?: number): void;
/**
* The frames per second at which this ticker is running.
* The default is approximately 60 in most modern browsers.
* > [!NOTE] This does not factor in the value of
* > {@link Ticker#speed|speed}, which is specific
* > to scaling {@link Ticker#deltaTime|deltaTime}.
* @example
* ```ts
* // Basic FPS monitoring
* ticker.add(() => {
* console.log(`Current FPS: ${Math.round(ticker.FPS)}`);
* });
* ```
* @readonly
*/
get FPS(): number;
/**
* Manages the maximum amount of milliseconds allowed to
* elapse between invoking {@link Ticker#update|update}.
*
* This value is used to cap {@link Ticker#deltaTime|deltaTime},
* but does not effect the measured value of {@link Ticker#FPS|FPS}.
*
* When setting this property it is clamped to a value between
* `0` and `Ticker.targetFPMS * 1000`.
* @example
* ```ts
* // Set minimum acceptable frame rate
* const ticker = new Ticker();
* ticker.minFPS = 30; // Never go below 30 FPS
*
* // Use with maxFPS for frame rate clamping
* ticker.minFPS = 30;
* ticker.maxFPS = 60;
*
* // Monitor delta capping
* ticker.add(() => {
* // Delta time will be capped based on minFPS
* console.log(`Delta time: ${ticker.deltaTime}`);
* });
* ```
* @default 10
*/
get minFPS(): number;
set minFPS(fps: number);
/**
* Manages the minimum amount of milliseconds required to
* elapse between invoking {@link Ticker#update|update}.
*
* This will effect the measured value of {@link Ticker#FPS|FPS}.
*
* If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can.
* Otherwise it will be at least `minFPS`
* @example
* ```ts
* // Set minimum acceptable frame rate
* const ticker = new Ticker();
* ticker.maxFPS = 60; // Never go above 60 FPS
*
* // Use with maxFPS for frame rate clamping
* ticker.minFPS = 30;
* ticker.maxFPS = 60;
*
* // Monitor delta capping
* ticker.add(() => {
* // Delta time will be capped based on maxFPS
* console.log(`Delta time: ${ticker.deltaTime}`);
* });
* ```
* @default 0
*/
get maxFPS(): number;
set maxFPS(fps: number);
/**
* The shared ticker instance used by {@link AnimatedSprite} and by
* {@link VideoSource} to update animation frames / video textures.
*
* It may also be used by {@link Application} if created with the `sharedTicker` option property set to true.
*
* The property {@link Ticker#autoStart|autoStart} is set to `true` for this instance.
* Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker.
* @example
* import { Ticker } from 'pixi.js';
*
* const ticker = Ticker.shared;
* // Set this to prevent starting this ticker when listeners are added.
* // By default this is true only for the Ticker.shared instance.
* ticker.autoStart = false;
*
* // FYI, call this to ensure the ticker is stopped. It should be stopped
* // if you have not attempted to render anything yet.
* ticker.stop();
*
* // Call this when you are ready for a running shared ticker.
* ticker.start();
* @example
* import { autoDetectRenderer, Container } from 'pixi.js';
*
* // You may use the shared ticker to render...
* const renderer = autoDetectRenderer();
* const stage = new Container();
* document.body.appendChild(renderer.view);
* ticker.add((time) => renderer.render(stage));
*
* // Or you can just update it manually.
* ticker.autoStart = false;
* ticker.stop();
* const animate = (time) => {
* ticker.update(time);
* renderer.render(stage);
* requestAnimationFrame(animate);
* };
* animate(performance.now());
* @type {Ticker}
* @readonly
*/
static get shared(): Ticker;
/**
* The system ticker instance used by {@link PrepareBase} for core timing
* functionality that shouldn't usually need to be paused, unlike the `shared`
* ticker which drives visual animations and rendering which may want to be paused.
*
* The property {@link Ticker#autoStart|autoStart} is set to `true` for this instance.
* @type {Ticker}
* @readonly
* @advanced
*/
static get system(): Ticker;
}
type ResizeableRenderer = Pick<Renderer, "resize">;
/**
* Application options for the {@link ResizePlugin}.
* These options control how your application handles window and element resizing.
* @example
* ```ts
* // Auto-resize to window
* await app.init({ resizeTo: window });
*
* // Auto-resize to container element
* await app.init({ resizeTo: document.querySelector('#game') });
* ```
* @category app
* @standard
*/
export interface ResizePluginOptions {
/**
* Element to automatically resize the renderer to.
* @example
* ```ts
* const app = new Application();
* await app.init({
* resizeTo: window, // Resize to the entire window
* // or
* resizeTo: document.querySelector('#game-container'), // Resize to a specific element
* // or
* resizeTo: null, // Disable auto-resize
* });
* ```
* @default null
*/
resizeTo?: Window | HTMLElement;
}
/**
* Middleware for Application's resize functionality. This plugin handles automatic
* and manual resizing of your PixiJS application.
*
* Adds the following features to {@link Application}:
* - `resizeTo`: Set an element to automatically resize to
* - `resize`: Manually trigger a resize
* - `queueResize`: Queue a resize for the next animation frame
* - `cancelResize`: Cancel a queued resize
* @example
* ```ts
* import { Application, ResizePlugin } from 'pixi.js';
*
* // Create application
* const app = new Application();
*
* // Example 1: Auto-resize to window
* await app.init({ resizeTo: window });
*
* // Example 2: Auto-resize to specific element
* const container = document.querySelector('#game-container');
* await app.init({ resizeTo: container });
*
* // Example 3: Change resize target at runtime
* app.resizeTo = window; // Enable auto-resize to window
* app.resizeTo = null; // Disable auto-resize
* ```
* @category app
* @standard
*/
export declare class ResizePlugin {
/** @ignore */
static extension: ExtensionMetadata;
/** @internal */
static resizeTo: Window | HTMLElement;
/** @internal */
static resize: () => void;
/** @internal */
static renderer: ResizeableRenderer;
/** @internal */
static queueResize: () => void;
/** @internal */
static render: () => void;
/** @internal */
private static _resizeId;
/** @internal */
private static _resizeTo;
/** @internal */
private static _cancelResize;
/**
* Initialize the plugin with scope of application instance
* @private
* @param {object} [options] - See application options
*/
static init(options: ResizePluginOptions): void;
/**
* Clean up the ticker, scoped to application
* @private
*/
static destroy(): void;
}
/**
* Application options for the {@link TickerPlugin}.
* These options control the animation loop and update cycle of your PixiJS application.
* @example
* ```ts
* import { Application } from 'pixi.js';
*
* // Basic setup with default options
* const app = new Application();
* await app.init({
* autoStart: true, // Start animation loop automatically
* sharedTicker: false // Use dedicated ticker instance
* });
*
* // Advanced setup with shared ticker
* const app2 = new Application();
* await app2.init({
* autoStart: false, // Don't start automatically
* sharedTicker: true // Use global shared ticker
* });
*
* // Start animation when ready
* app2.start();
* ```
* @remarks
* The ticker is the heart of your application's animation system. It:
* - Manages the render loop
* - Provides accurate timing information
* - Handles frame-based updates
* - Supports priority-based execution order
* @see {@link Ticker} For detailed ticker functionality
* @see {@link UPDATE_PRIORITY} For update priority constants
* @category app
* @standard
*/
export interface TickerPluginOptions {
/**
* Controls whether the animation loop starts automatically after initialization.
* > [!IMPORTANT]
* > Setting this to `false` does NOT stop the shared ticker even if `sharedTicker` is `true`.
* > You must stop the shared ticker manually if needed.
* @example
* ```ts
* // Auto-start (default behavior)
* await app.init({ autoStart: true });
*
* // Manual start
* await app.init({ autoStart: false });
* app.start(); // Start when ready
* ```
* @default true
*/
autoStart?: boolean;
/**
* Controls whether to use the shared global ticker or create a new instance.
*
* The shared ticker is useful when you have multiple instances that should sync their updates.
* However, it has some limitations regarding update order control.
*
* Update Order:
* 1. System ticker (always runs first)
* 2. Shared ticker (if enabled)
* 3. App ticker (if using own ticker)
* @example
* ```ts
* // Use shared ticker (global instance)
* await app.init({ sharedTicker: true });
*
* // Use dedicated ticker (default)
* await app.init({ sharedTicker: false });
*
* // Access ticker properties
* console.log(app.ticker.FPS); // Current FPS
* console.log(app.ticker.deltaMS); // MS since last update
* ```
* @default false
*/
sharedTicker?: boolean;
}
/**
* Middleware for Application's {@link Ticker} functionality. This plugin manages the
* animation loop and update cycle of your PixiJS application.
*
* Adds the following features to {@link Application}:
* - `ticker`: Access to the application's ticker
* - `start`: Start the animation loop
* - `stop`: Stop the animation loop
* @example
* ```ts
* import { Application, TickerPlugin, extensions } from 'pixi.js';
*
* // Create application
* const app = new Application();
*
* // Example 1: Basic ticker usage (default autoStart)
* await app.init({ autoStart: true }); // Starts ticker automatically
*
* // Example 2: Manual ticker control
* await app.init({ autoStart: false }); // Don't start automatically
* app.start(); // Start manually
* app.stop(); // Stop manually
*
* // Example 3: Add custom update logic
* app.ticker.add((ticker) => {
* // Run every frame, delta is the time since last update
* sprite.rotation += 0.1 * ticker.deltaTime;
* });
*
* // Example 4: Control update priority
* import { UPDATE_PRIORITY } from 'pixi.js';
*
* app.ticker.add(
* (ticker) => {
* // Run before normal priority updates
* },
* null,
* UPDATE_PRIORITY.HIGH
* );
*
* // Example 5: One-time update
* app.ticker.addOnce(() => {
* console.log('Runs next frame only');
* });
* ```
* @see {@link Ticker} For detailed ticker functionality
* @see {@link UPDATE_PRIORITY} For priority constants
* @category app
* @standard
*/
export declare class TickerPlugin {
/** @ignore */
static extension: ExtensionMetadata;
/** @internal */
static start: () => void;
/** @internal */
static stop: () => void;
/** @internal */
private static _ticker;
/** @internal */
static ticker: Ticker;
/**
* Initialize the plugin with scope of application instance
* @private
* @param {object} [options] - See application options
*/
static init(options?: PixiMixins.ApplicationOptions): void;
/**
* Clean up the ticker, scoped to application.
* @private
*/
static destroy(): void;
}
declare global {
namespace PixiMixins {
// Extend the Application interface with resize and ticker functionalities
interface Application {
/**
* Element to automatically resize the renderer to.
* @example
* ```ts
* const app = new Application();
* await app.init({
* resizeTo: window, // Resize to the entire window
* // or
* resizeTo: document.querySelector('#game-container'), // Resize to a specific element
* // or
* resizeTo: null, // Disable auto-resize
* });
* ```
* @default null
*/
resizeTo: Window | HTMLElement;
/**
* Element to automatically resize the renderer to.
* > [!IMPORTANT]
* > You do not need to call this method manually in most cases.
* > A `resize` event will be dispatched automatically when the `resizeTo` element changes size.
* @remarks
* - Automatically resizes the renderer to match the size of the `resizeTo` element
* - If `resizeTo` is `null`, auto-resizing is disabled
* - If `resizeTo` is a `Window`, it resizes to the full window size
* - If `resizeTo` is an `HTMLElement`, it resizes to the element's bounding client rectangle
* @example
* ```ts
* const app = new Application();
* await app.init({
* resizeTo: window, // Resize to the entire window
* // or
* resizeTo: document.querySelector('#game-container'), // Resize to a specific element
* // or
* resizeTo: null, // Disable auto-resize
* });
*
* // Manually trigger a resize
* app.resize();
* ```
* @default null
*/
resize(): void;
/**
* Queue a resize operation for the next animation frame. This method is throttled
* and optimized for frequent calls.
* > [!IMPORTANT]
* > You do not need to call this method manually in most cases.
* > A `resize` event will be dispatched automatically when the `resizeTo` element changes size.
* @remarks
* - Safe to call multiple times per frame
* - Only one resize will occur on next frame
* - Cancels any previously queued resize
* @example
* ```ts
* app.queueResize(); // Queue for next frame
* ```
*/
queueResize(): void;
/**
* Cancel any pending resize operation that was queued with `queueResize()`.
* @remarks
* - Clears the resize operation queued for next frame
* @example
* ```ts
* // Queue a resize
* app.queueResize();
*
* // Cancel if needed
* app.cancelResize();
* ```
*/
cancelResize(): void;
/**
* The application's ticker instance that manages the update/render loop.
* @example
* ```ts
* // Basic animation
* app.ticker.add((ticker) => {
* sprite.rotation += 0.1 * ticker.deltaTime;
* });
*
* // Control update priority
* app.ticker.add(
* (ticker) => {
* // Physics update (runs first)
* },
* undefined,
* UPDATE_PRIORITY.HIGH
* );
*
* // One-time update
* app.ticker.addOnce(() => {
* console.log('Runs next frame only');
* });
*
* // Access timing info
* console.log(app.ticker.FPS); // Current FPS
* console.log(app.ticker.deltaTime); // Scaled time delta
* console.log(app.ticker.deltaMS); // MS since last update
* ```
* @see {@link Ticker} For detailed ticker functionality
* @see {@link UPDATE_PRIORITY} For priority constants
*/
ticker: Ticker;
/**
* Stops the render/update loop.
* @example
* ```ts
* // Stop the application
* app.stop();
* // ... custom update logic ...
* app.render(); // Manual render
* ```
*/
stop(): void;
/**
* Starts the render/update loop.
* @example
* ```ts
* // Initialize without auto-start
* await app.init({ autoStart: false });
*
* // Start when ready
* app.start();
* ```
*/
start(): void;
}
// Combine ResizePluginOptions and TickerPluginOptions into ApplicationOptions
interface ApplicationOptions extends ResizePluginOptions, TickerPluginOptions {
}
}
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface AssetsPreferences {
}
}
}
/**
* The CullingMixin interface provides properties and methods for managing culling behavior
* of a display object. Culling is the process of determining whether an object should be rendered
* based on its visibility within the current view or frame.
*
* Key Features:
* - Custom culling areas for better performance
* - Per-object culling control
* - Child culling management
* @example
* ```ts
* // Enable culling for a container
* const container = new Container();
* container.cullable = true;
*
* // Set custom cull area for better performance
* container.cullArea = new Rectangle(0, 0, 800, 600);
*
* // Disable child culling for static scenes
* container.cullableChildren = false;
* ```
* @category scene
* @standard
*/
export interface CullingMixinConstructor {
/**
* Custom shape used for culling calculations instead of object bounds.
* Defined in local space coordinates relative to the object.
* > [!NOTE]
* > Setting this to a custom Rectangle allows you to define a specific area for culling,
* > which can improve performance by avoiding expensive bounds calculations.
* @example
* ```ts
* const container = new Container();
*
* // Define custom culling boundary
* container.cullArea = new Rectangle(0, 0, 800, 600);
*
* // Reset to use object bounds
* container.cullArea = null;
* ```
* @remarks
* - Improves performance by avoiding bounds calculations
* - Useful for containers with many children
* - Set to null to use object bounds
* @default null
*/
cullArea: Rectangle;
/**
* Controls whether this object should be culled when out of view.
* When true, the object will not be rendered if its bounds are outside the visible area.
* @example
* ```ts
* const sprite = new Sprite(texture);
*
* // Enable culling
* sprite.cullable = true;
*
* // Force object to always render
* sprite.cullable = false;
* ```
* @remarks
* - Does not affect transform updates
* - Applies to this object only
* - Children follow their own cullable setting
* @default false
*/
cullable: boolean;
/**
* Controls whether children of this container can be culled.
* When false, skips recursive culling checks for better performance.
* @example
* ```ts
* const container = new Container();
*
* // Enable container culling
* container.cullable = true;
*
* // Disable child culling for performance
* container.cullableChildren = false;
*
* // Children will always render if container is visible
* container.addChild(sprite1, sprite2, sprite3);
* ```
* @remarks
* - Improves performance for static scenes
* - Useful when children are always within container bounds
* - Parent culling still applies
* @default true
*/
cullableChildren: boolean;
}
/** @internal */
export declare const cullingMixin: CullingMixinConstructor;
/**
* Application options for the {@link CullerPlugin}.
* These options control how your application handles culling of display objects.
* @example
* ```ts
* import { Application } from 'pixi.js';
*
* // Create application
* const app = new Application();
* await app.init({
* culler: {
* updateTransform: false // Skip updating transforms for culled objects
* }
* });
* ```
* @category app
* @standard
*/
export interface CullerPluginOptions {
/**
* Options for the culler behavior.
* @example
* ```ts
* // Basic culling options
* const app = new Application();
* await app.init({
* culler: {...}
* });
* ```
*/
culler?: {
/**
* Update the transform of culled objects.
*
* > [!IMPORTANT] Keeping this as `false` can improve performance by avoiding unnecessary calculations,
* > however, the transform used for culling may not be up-to-date if the object has moved since the last render.
* @default true
* @example
* ```ts
* const app = new Application();
* await app.init({
* culler: {
* updateTransform: false // Skip updating transforms for culled objects
* }
* });
* ```
*/
updateTransform?: boolean;
};
}
/**
* An {@link Application} plugin that automatically culls (hides) display objects that are outside
* the visible screen area. This improves performance by not rendering objects that aren't visible.
*
* Key Features:
* - Automatic culling based on screen boundaries
* - Configurable culling areas and behavior per container
* - Can improve rendering performance
* @example
* ```ts
* import { Application, CullerPlugin, Container, Rectangle } from 'pixi.js';
*
* // Register the plugin
* extensions.add(CullerPlugin);
*
* // Create application
* const app = new Application();
* await app.init({...});
*
* // Create a container with culling enabled
* const container = new Container();
* container.cullable = true; // Enable culling for this container
* container.cullableChildren = true; // Enable culling for children (default)
* app.stage.addChild(container);
*
* // Optional: Set custom cull area to avoid expensive bounds calculations
* container.cullArea = new Rectangle(0, 0, app.screen.width, app.screen.height);
*
* // Add many sprites to the group
* for (let j = 0; j < 100; j++) {
* const sprite = Sprite.from('texture.png');
* sprite.x = Math.random() * 2000;
* sprite.y = Math.random() * 2000;
*
* sprite.cullable = true; // Enable culling for each sprite
*
* // Set cullArea if needed
* // sprite.cullArea = new Rectangle(0, 0, 100, 100); // Optional
*
* // Add to container
* container.addChild(sprite);
* }
* ```
* @remarks
* To enable culling, you must set the following properties on your containers:
* - `cullable`: Set to `true` to enable culling for the container
* - `cullableChildren`: Set to `true` to enable culling for children (default)
* - `cullArea`: Optional custom Rectangle for culling bounds
*
* Performance Tips:
* - Group objects that are spatially related
* - Use `cullArea` for containers with many children to avoid bounds calculations
* - Set `cullableChildren = false` for containers that are always fully visible
* @category app
* @standard
* @see {@link Culler} For the underlying culling implementation
* @see {@link CullingMixinConstructor} For culling properties documentation
*/
export declare class CullerPlugin {
/** @ignore */
static extension: ExtensionMetadata;
/** @internal */
static renderer: Renderer;
/** @internal */
static stage: Container;
/** @internal */
static render: () => void;
private static _renderRef;
/**
* Initialize the plugin with scope of application instance
* @private
* @param {object} [options] - See application options
*/
static init(options?: PixiMixins.ApplicationOptions): void;
/** @internal */
static destroy(): void;
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface Container extends Partial<CullingMixinConstructor> {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ContainerOptions extends Partial<CullingMixinConstructor> {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ApplicationOptions extends Partial<CullerPluginOptions> {
}
}
}
/**
* Options for configuring a {@link DOMContainer}.
* Controls how DOM elements are integrated into the PixiJS scene graph.
* @example
* ```ts
* // Create with a custom element
* const domContainer = new DOMContainer({
* element: document.createElement('input'),
* anchor: { x: 0.5, y: 0.5 } // or anchor: 0.5 to center both x and y
* });
* ```
* @category scene
* @standard
* @noInheritDoc
*/
export interface DOMContainerOptions extends ViewContainerOptions {
/**
* The DOM element to use for the container.
* Can be any HTML element like div, input, textarea, etc.
*
* If not provided, creates a new div element.
* @default document.createElement('div')
*/
element?: HTMLElement;
/**
* The anchor point of the container.
* - Can be a single number to set both x and y
* - Can be a point-like object with x,y coordinates
* - (0,0) is top-left
* - (1,1) is bottom-right
* - (0.5,0.5) is center
* @default 0
*/
anchor?: PointData | number;
}
/**
* The DOMContainer object is used to render DOM elements within the PixiJS scene graph.
* It allows you to integrate HTML elements into your PixiJS application while maintaining
* proper transform hierarchy and visibility.
*
* DOMContainer is especially useful for rendering standard DOM elements
* that handle user input, such as `<input>` or `<textarea>`.
* This is often simpler and more flexible than trying to implement text input
* directly in PixiJS. For instance, if you need text fields or text areas,
* you can embed them through this container for native browser text handling.
*
* --------- EXPERIMENTAL ---------
*
* This is a new API, things may change and it may not work as expected.
* We want to hear your feedback as we go!
*
* --------------------------------
* @example
* @example
* ```ts
* // Basic text display
* const textContainer = new DOMContainer();
* textContainer.element.innerHTML = 'Hello World!';
* app.stage.addChild(textContainer);
*
* // Input field with centered anchor
* const inputContainer = new DOMContainer({
* element: document.createElement('input'),
* anchor: 0.5
* });
* inputContainer.position.set(400, 300);
* app.stage.addChild(inputContainer);
*
* // Rich text area
* const textArea = new DOMContainer({
* element: document.createElement('textarea'),
* anchor: { x: 0, y: 0 }
* });
* textArea.scale.set(2);
* app.stage.addChild(textArea);
* ```
* @category scene
* @standard
*/
export declare class DOMContainer extends ViewContainer<never> {
/** @internal */
readonly renderPipeId: string;
/** @internal */
batched: boolean;
/**
* The anchor point of the container.
* @internal
*/
readonly _anchor: Point;
/** The DOM element that this container is using. */
private _element;
/**
* @param options - The options for creating the DOM container.
*/
constructor(options?: DOMContainerOptions);
/**
* The anchor sets the origin point of the container.
* Controls the relative positioning of the DOM element.
*
* The default is `(0,0)`, this means the container's origin is the top left.
* Setting the anchor to `(0.5,0.5)` means the container's origin is centered.
* Setting the anchor to `(1,1)` would mean the container's origin point will be the bottom right corner.
* @example
* ```ts
* const container = new DOMContainer();
*
* // Set anchor to center (shorthand)
* container.anchor = 0.5;
*
* // Set anchor to bottom-right
* container.anchor = { x: 1, y: 1 };
*
* // Set anchor to custom position
* container.anchor = new Point(0.3, 0.7);
* ```
*/
get anchor(): Point;
/**
* Sets the anchor point of the container.
* @param value - New anchor value:
* - number: Sets both x and y to same value
* - PointData: Sets x and y separately
*/
set anchor(value: PointData | number);
/**
* Sets the DOM element for this container.
* This will replace the current element and update the view.
* @param value - The new DOM element to use
* @example
* ```ts
* const domContainer = new DOMContainer();
* domContainer.element = document.createElement('input');
* ```
*/
set element(value: HTMLElement);
/**
* The DOM element associated with this container.
* @example
* ```ts
* const domContainer = new DOMContainer();
* domContainer.element.innerHTML = 'Hello World!';
* document.body.appendChild(domContainer.element);
* ```
*/
get element(): HTMLElement;
/** @private */
protected updateBounds(): void;
/**
* Destroys this DOM container.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that
* @example
* domContainer.destroy();
* domContainer.destroy(true);
*/
destroy(options?: boolean): void;
}
/**
* The DOMPipe class is responsible for managing and rendering DOM elements within a PixiJS scene.
* It maps dom elements to the canvas and ensures they are correctly positioned and visible.
* @internal
*/
export declare class DOMPipe implements RenderPipe<DOMContainer> {
/**
* Static property defining the extension type and name for the DOMPipe.
* This is used to register the DOMPipe with different rendering pipelines.
*/
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "dom";
};
private _renderer;
/** Array to keep track of attached DOM elements */
private readonly _attachedDomElements;
/** The main DOM element that acts as a container for other DOM elements */
private readonly _domElement;
/** The CanvasTransformSync instance that keeps the DOM element in sync with the canvas */
private _canvasObserver;
/**
* Constructor for the DOMPipe class.
* @param renderer - The renderer instance that this DOMPipe will be associated with.
*/
constructor(renderer: Renderer);
/** Initializes the DOMPipe, setting up the main DOM element and adding it to the document body. */
init(): void;
/**
* Adds a renderable DOM container to the list of attached elements.
* @param domContainer - The DOM container to be added.
* @param _instructionSet - The instruction set (unused).
*/
addRenderable(domContainer: DOMContainer, _instructionSet: InstructionSet): void;
/**
* Updates a renderable DOM container.
* @param _domContainer - The DOM container to be updated (unused).
*/
updateRenderable(_domContainer: DOMContainer): void;
/**
* Validates a renderable DOM container.
* @param _domContainer - The DOM container to be validated (unused).
* @returns Always returns true as validation is not required.
*/
validateRenderable(_domContainer: DOMContainer): boolean;
/** Handles the post-rendering process, ensuring DOM elements are correctly positioned and visible. */
postrender(): void;
/** Destroys the DOMPipe, removing all attached DOM elements and cleaning up resources. */
destroy(): void;
}
declare global {
namespace PixiMixins {
interface RendererPipes {
dom: DOMPipe;
}
}
}
/**
* A specialized event class for wheel/scroll interactions in PixiJS applications.
* Extends {@link FederatedMouseEvent} to provide wheel-specific properties while
* maintaining compatibility with the DOM WheelEvent interface.
*
* Key features:
* - Provides scroll delta information
* - Supports different scroll modes (pixel, line, page)
* - Inherits mouse event properties
* - Normalizes cross-browser wheel events
* @example
* ```ts
* // Basic wheel event handling
* sprite.on('wheel', (event: FederatedWheelEvent) => {
* // Get scroll amount
* console.log('Vertical scroll:', event.deltaY);
* console.log('Horizontal scroll:', event.deltaX);
*
* // Check scroll mode
* if (event.deltaMode === FederatedWheelEvent.DOM_DELTA_LINE) {
* console.log('Scrolling by lines');
* } else if (event.deltaMode === FederatedWheelEvent.DOM_DELTA_PAGE) {
* console.log('Scrolling by pages');
* } else {
* console.log('Scrolling by pixels');
* }
*
* // Get scroll position
* console.log('Scroll at:', event.global.x, event.global.y);
* });
*
* // Common use case: Zoom control
* container.on('wheel', (event: FederatedWheelEvent) => {
* // Prevent page scrolling
* event.preventDefault();
*
* // Zoom in/out based on scroll direction
* const zoomFactor = 1 + (event.deltaY / 1000);
* container.scale.set(container.scale.x * zoomFactor);
* });
* ```
* @see {@link FederatedMouseEvent} For base mouse event functionality
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent} DOM WheelEvent Interface
* @see {@link EventSystem} For the event management system
* @category events
* @standard
*/
export declare class FederatedWheelEvent extends FederatedMouseEvent implements WheelEvent {
/**
* The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
* `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
*/
deltaMode: number;
/** Horizontal scroll amount */
deltaX: number;
/** Vertical scroll amount */
deltaY: number;
/** z-axis scroll amount. */
deltaZ: number;
/**
* Units specified in pixels.
* @ignore
*/
static readonly DOM_DELTA_PIXEL = 0;
/**
* Units specified in pixels.
* @ignore
*/
readonly DOM_DELTA_PIXEL = 0;
/**
* Units specified in lines.
* @ignore
*/
static readonly DOM_DELTA_LINE = 1;
/**
* Units specified in lines.
* @ignore
*/
readonly DOM_DELTA_LINE = 1;
/**
* Units specified in pages.
* @ignore
*/
static readonly DOM_DELTA_PAGE = 2;
/**
* Units specified in pages.
* @ignore
*/
readonly DOM_DELTA_PAGE = 2;
}
/**
* The tracking data for each pointer held in the state of an {@link EventBoundary}.
*
* ```ts
* pressTargetsByButton: {
* [id: number]: Container[];
* };
* clicksByButton: {
* [id: number]: {
* clickCount: number;
* target: Container;
* timeStamp: number;
* };
* };
* overTargets: Container[];
* ```
* @typedef {object} TrackingData
* @property {Record.<number, Container>} pressTargetsByButton - The pressed containers'
* propagation paths by each button of the pointer.
* @property {Record.<number, object>} clicksByButton - Holds clicking data for each button of the pointer.
* @property {Container[]} overTargets - The Container propagation path over which the pointer is hovering.
* @category events
* @internal
*/
export type TrackingData = {
pressTargetsByButton: {
[id: number]: Container[];
};
clicksByButton: {
[id: number]: {
clickCount: number;
target: Container;
timeStamp: number;
};
};
overTargets: Container[];
};
type EmitterListener = {
fn(...args: any[]): any;
context: any;
once: boolean;
};
/**
* Internal storage of event listeners in EventEmitter.
* @ignore
*/
export type EmitterListeners = Record<string, EmitterListener | EmitterListener[]>;
/**
* The type of cursor to use when the mouse pointer is hovering over an interactive element.
* Accepts any valid CSS cursor value.
* @example
* ```ts
* // Basic cursor types
* sprite.cursor = 'pointer'; // Hand cursor for clickable elements
* sprite.cursor = 'grab'; // Grab cursor for draggable elements
* sprite.cursor = 'crosshair'; // Precise cursor for selection
*
* // Direction cursors
* sprite.cursor = 'n-resize'; // North resize
* sprite.cursor = 'ew-resize'; // East-west resize
* sprite.cursor = 'nesw-resize';// Northeast-southwest resize
*
* // Custom cursor with fallback
* sprite.cursor = 'url("custom.png"), auto';
* ```
*
* Common cursor values:
* - Basic: `auto`, `default`, `none`, `pointer`, `wait`
* - Text: `text`, `vertical-text`
* - Links: `alias`, `copy`, `move`
* - Selection: `cell`, `crosshair`
* - Drag: `grab`, `grabbing`
* - Disabled: `not-allowed`, `no-drop`
* - Resize: `n-resize`, `e-resize`, `s-resize`, `w-resize`
* - Bidirectional: `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`
* - Other: `help`, `progress`
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} MDN Cursor Documentation
* @category events
* @standard
*/
export type Cursor = "auto" | "default" | "none" | "context-menu" | "help" | "pointer" | "progress" | "wait" | "cell" | "crosshair" | "text" | "vertical-text" | "alias" | "copy" | "move" | "no-drop" | "not-allowed" | "e-resize" | "n-resize" | "ne-resize" | "nw-resize" | "s-resize" | "se-resize" | "sw-resize" | "w-resize" | "ns-resize" | "ew-resize" | "nesw-resize" | "col-resize" | "nwse-resize" | "row-resize" | "all-scroll" | "zoom-in" | "zoom-out" | "grab" | "grabbing";
/**
* Interface defining a hit area for pointer interaction. The hit area specifies
* the region in which pointer events should be captured by a display object.
* @example
* ```ts
* // Create a rectangular hit area
* sprite.hitArea = new Rectangle(0, 0, 100, 100);
*
* // Create a circular hit area
* sprite.hitArea = new Circle(50, 50, 50);
*
* // Custom hit area implementation
* sprite.hitArea = {
* contains(x: number, y: number) {
* // Custom hit testing logic
* return x >= 0 && x <= 100 && y >= 0 && y <= 100;
* }
* };
* ```
* @remarks
* - Hit areas override the default bounds-based hit testing
* - Can improve performance by simplifying hit tests
* - Useful for irregular shapes or precise interaction areas
* - Common implementations include Rectangle, Circle, Polygon
* @see {@link Container.eventMode} For enabling interactivity
* @see {@link Container.interactive} For backwards compatibility
* @category events
* @standard
*/
export interface IHitArea {
/**
* Checks if the given coordinates are inside this hit area.
* @param {number} x - The x coordinate to check
* @param {number} y - The y coordinate to check
* @returns True if the coordinates are inside the hit area
*/
contains(x: number, y: number): boolean;
}
/**
* Function type for handlers, e.g., onclick
* @category events
* @advanced
*/
export type FederatedEventHandler<T = FederatedPointerEvent> = (event: T) => void;
/**
* The type of interaction behavior for a Container. This is set via the {@link Container#eventMode} property.
* @example
* ```ts
* // Basic event mode setup
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static'; // Enable standard interaction
* sprite.on('pointerdown', () => { console.log('clicked!'); });
*
* // Different event modes
* sprite.eventMode = 'none'; // Disable all interaction
* sprite.eventMode = 'passive'; // Only allow interaction on children
* sprite.eventMode = 'auto'; // Like DOM pointer-events: auto
* sprite.eventMode = 'dynamic'; // For moving/animated objects
* ```
*
* Available modes:
* - `'none'`: Ignores all interaction events, even on its children
* - `'passive'`: **(default)** Does not emit events and ignores hit testing on itself and non-interactive children.
* Interactive children will still emit events.
* - `'auto'`: Does not emit events but is hit tested if parent is interactive. Same as `interactive = false` in v7
* - `'static'`: Emit events and is hit tested. Same as `interactive = true` in v7
* - `'dynamic'`: Emits events and is hit tested but will also receive mock interaction events fired from
* a ticker to allow for interaction when the mouse isn't moving
*
* Performance tips:
* - Use `'none'` for pure visual elements
* - Use `'passive'` for containers with some interactive children
* - Use `'static'` for standard buttons/controls
* - Use `'dynamic'` only for moving/animated interactive elements
* @since 7.2.0
* @category events
* @standard
*/
export type EventMode = "none" | "passive" | "auto" | "static" | "dynamic";
/**
* The properties available for any interactive object. This interface defines the core interaction
* properties and event handlers that can be set on any Container in PixiJS.
* @example
* ```ts
* // Basic interactive setup
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
* sprite.cursor = 'pointer';
*
* // Using event handlers
* sprite.on('click', (event) => console.log('Sprite clicked!', event));
* sprite.on('pointerdown', (event) => console.log('Pointer down!', event));
*
* // Using property-based event handlers
* sprite.onclick = (event) => console.log('Clicked!');
* sprite.onpointerenter = () => sprite.alpha = 0.7;
* sprite.onpointerleave = () => sprite.alpha = 1.0;
*
* // Custom hit area
* sprite.hitArea = new Rectangle(0, 0, 100, 100);
* ```
*
* Core Properties:
* - `eventMode`: Controls how the object handles interaction events
* - `cursor`: Sets the mouse cursor when hovering
* - `hitArea`: Defines custom hit testing area
* - `interactive`: Alias for `eventMode` to enable interaction with "static" or "passive" modes
* - `interactiveChildren`: Controls hit testing on children
*
* Event Handlers:
* - Mouse: click, mousedown, mouseup, mousemove, mouseenter, mouseleave
* - Touch: touchstart, touchend, touchmove, tap
* - Pointer: pointerdown, pointerup, pointermove, pointerover
* - Global: globalpointermove, globalmousemove, globaltouchmove
* > [!IMPORTANT] Global events are fired when the pointer moves even if it is outside the bounds of the Container.
* @see {@link EventMode} For interaction mode details
* @see {@link Cursor} For cursor style options
* @see {@link IHitArea} For hit area implementation
* @category events
* @standard
*/
export interface FederatedOptions {
/**
* The cursor style to display when the mouse pointer is hovering over the object.
* Accepts any valid CSS cursor value or custom cursor URL.
* @example
* ```ts
* // Common cursor types
* sprite.cursor = 'pointer'; // Hand cursor for clickable elements
* sprite.cursor = 'grab'; // Grab cursor for draggable elements
* sprite.cursor = 'crosshair'; // Precise cursor for selection
* sprite.cursor = 'not-allowed'; // Indicate disabled state
*
* // Direction cursors
* sprite.cursor = 'n-resize'; // North resize
* sprite.cursor = 'ew-resize'; // East-west resize
* sprite.cursor = 'nesw-resize'; // Northeast-southwest resize
*
* // Custom cursor with fallback
* sprite.cursor = 'url("custom.png"), auto';
* sprite.cursor = 'url("cursor.cur") 2 2, pointer'; // With hotspot offset
* ```
* @type {Cursor | string}
* @default undefined
* @see {@link EventSystem.cursorStyles} For setting global cursor styles
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} MDN Cursor Documentation
*/
cursor?: Cursor | (string & {});
/**
* Enable interaction events for the Container. Touch, pointer and mouse events are supported.
* @example
* ```ts
* const sprite = new Sprite(texture);
*
* // Enable standard interaction (like buttons)
* sprite.eventMode = 'static';
* sprite.on('pointerdown', () => console.log('clicked!'));
*
* // Enable for moving objects
* sprite.eventMode = 'dynamic';
* sprite.on('pointermove', () => updatePosition());
*
* // Disable all interaction
* sprite.eventMode = 'none';
*
* // Only allow child interactions
* sprite.eventMode = 'passive';
* ```
*
* Available modes:
*
* - `'none'`: Ignores all interaction events, even on its children. Best for pure visuals.
* - `'passive'`: **(default)** Does not emit events and ignores hit testing on itself and non-interactive
* children. Interactive children will still emit events.
* - `'auto'`: Does not emit events but is hit tested if parent is interactive. Same as `interactive = false` in v7.
* - `'static'`: Emit events and is hit tested. Same as `interactive = true` in v7. Best for buttons/UI.
* - `'dynamic'`: Like static but also receives synthetic events when pointer is idle. Best for moving objects.
*
* Performance tips:
* - Use `'none'` for pure visual elements
* - Use `'passive'` for containers with some interactive children
* - Use `'static'` for standard UI elements
* - Use `'dynamic'` only when needed for moving/animated elements
* @since 7.2.0
*/
eventMode?: EventMode;
/**
* Whether this object should fire UI events. This is an alias for `eventMode` set to `'static'` or `'passive'`.
* Setting this to true will enable interaction events like `pointerdown`, `click`, etc.
* Setting it to false will disable all interaction events on this object.
* @see {@link Container.eventMode}
* @example
* ```ts
* // Enable interaction events
* sprite.interactive = true; // Sets eventMode = 'static'
* sprite.interactive = false; // Sets eventMode = 'passive'
* ```
*/
interactive?: boolean;
/**
* Controls whether children of this container can receive pointer events.
*
* Setting this to false allows PixiJS to skip hit testing on all children,
* improving performance for containers with many non-interactive children.
* @default true
* @example
* ```ts
* // Container with many visual-only children
* const container = new Container();
* container.interactiveChildren = false; // Skip hit testing children
*
* // Menu with interactive buttons
* const menu = new Container();
* menu.interactiveChildren = true; // Test all children
* menu.addChild(button1, button2, button3);
*
* // Performance optimization
* background.interactiveChildren = false;
* foreground.interactiveChildren = true;
* ```
*/
interactiveChildren?: boolean;
/**
* Defines a custom hit area for pointer interaction testing. When set, this shape will be used
* for hit testing instead of the container's standard bounds.
* @example
* ```ts
* import { Rectangle, Circle, Sprite } from 'pixi.js';
*
* // Rectangular hit area
* const button = new Sprite(texture);
* button.eventMode = 'static';
* button.hitArea = new Rectangle(0, 0, 100, 50);
*
* // Circular hit area
* const icon = new Sprite(texture);
* icon.eventMode = 'static';
* icon.hitArea = new Circle(32, 32, 32);
*
* // Custom hit area with polygon
* const custom = new Sprite(texture);
* custom.eventMode = 'static';
* custom.hitArea = new Polygon([0,0, 100,0, 100,100, 0,100]);
*
* // Custom hit testing logic
* sprite.hitArea = {
* contains(x: number, y: number) {
* // Custom collision detection
* return x >= 0 && x <= width && y >= 0 && y <= height;
* }
* };
* ```
* @remarks
* - Takes precedence over the container's bounds for hit testing
* - Can improve performance by simplifying collision checks
* - Useful for irregular shapes or precise click areas
*/
hitArea?: IHitArea | null;
/**
* Property-based event handler for the `click` event.
* Fired when a pointer device (mouse, touch, etc.) completes a click action.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('click', (event) => {
* console.log('Sprite clicked at:', event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onclick = (event) => {
* console.log('Clicked at:', event.global.x, event.global.y);
* };
* ```
* @default null
*/
onclick?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mousedown` event.
* Fired when a mouse button is pressed while the pointer is over the object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mousedown', (event) => {
* sprite.alpha = 0.5; // Visual feedback
* console.log('Mouse button:', event.button);
* });
* // Using property-based handler
* sprite.onmousedown = (event) => {
* sprite.alpha = 0.5; // Visual feedback
* console.log('Mouse button:', event.button);
* };
* ```
* @default null
*/
onmousedown?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseenter` event.
* Fired when the mouse pointer enters the bounds of the object. Does not bubble.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseenter', (event) => {
* sprite.scale.set(1.1);
* });
* // Using property-based handler
* sprite.onmouseenter = (event) => {
* sprite.scale.set(1.1);
* };
* ```
* @default null
*/
onmouseenter?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseleave` event.
* Fired when the pointer leaves the bounds of the display object. Does not bubble.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseleave', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onmouseleave = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onmouseleave?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mousemove` event.
* Fired when the pointer moves while over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mousemove', (event) => {
* // Get coordinates relative to the sprite
* console.log('Local:', event.getLocalPosition(sprite));
* });
* // Using property-based handler
* sprite.onmousemove = (event) => {
* // Get coordinates relative to the sprite
* console.log('Local:', event.getLocalPosition(sprite));
* };
* ```
* @default null
*/
onmousemove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `globalmousemove` event.
*
* Fired when the mouse moves anywhere, regardless of whether the pointer is over this object.
* The object must have `eventMode` set to 'static' or 'dynamic' to receive this event.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('globalmousemove', (event) => {
* // Move sprite to mouse position
* sprite.position.copyFrom(event.global);
* });
* // Using property-based handler
* sprite.onglobalmousemove = (event) => {
* // Move sprite to mouse position
* sprite.position.copyFrom(event.global);
* };
* ```
* @default null
* @remarks
* - Fires even when the mouse is outside the object's bounds
* - Useful for drag operations or global mouse tracking
* - Must have `eventMode` set appropriately to receive events
* - Part of the global move events family along with `globalpointermove` and `globaltouchmove`
*/
onglobalmousemove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseout` event.
* Fired when the pointer moves out of the bounds of the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseout', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onmouseout = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onmouseout?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseover` event.
* Fired when the pointer moves onto the bounds of the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseover', (event) => {
* sprite.scale.set(1.1);
* });
* // Using property-based handler
* sprite.onmouseover = (event) => {
* sprite.scale.set(1.1);
* };
* ```
* @default null
*/
onmouseover?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseup` event.
* Fired when a mouse button is released over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseup', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onmouseup = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onmouseup?: FederatedEventHandler | null;
/**
* Property-based event handler for the `mouseupoutside` event.
* Fired when a mouse button is released outside the display object that initially
* registered a mousedown.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('mouseupoutside', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onmouseupoutside = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onmouseupoutside?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointercancel` event.
* Fired when a pointer device interaction is canceled or lost.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointercancel', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onpointercancel = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onpointercancel?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerdown` event.
* Fired when a pointer device button (mouse, touch, pen, etc.) is pressed.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerdown', (event) => {
* sprite.position.set(event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onpointerdown = (event) => {
* sprite.position.set(event.global.x, event.global.y);
* };
* ```
* @default null
*/
onpointerdown?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerenter` event.
* Fired when a pointer device enters the bounds of the display object. Does not bubble.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerenter', (event) => {
* sprite.scale.set(1.2);
* });
* // Using property-based handler
* sprite.onpointerenter = (event) => {
* sprite.scale.set(1.2);
* };
* ```
* @default null
*/
onpointerenter?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerleave` event.
* Fired when a pointer device leaves the bounds of the display object. Does not bubble.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
* // Using emitter handler
* sprite.on('pointerleave', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onpointerleave = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onpointerleave?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointermove` event.
* Fired when a pointer device moves while over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointermove', (event) => {
* sprite.position.set(event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onpointermove = (event) => {
* sprite.position.set(event.global.x, event.global.y);
* };
* ```
* @default null
*/
onpointermove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `globalpointermove` event.
*
* Fired when the pointer moves anywhere, regardless of whether the pointer is over this object.
* The object must have `eventMode` set to 'static' or 'dynamic' to receive this event.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('globalpointermove', (event) => {
* sprite.position.set(event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onglobalpointermove = (event) => {
* sprite.position.set(event.global.x, event.global.y);
* };
* ```
* @default null
* @remarks
* - Fires even when the mouse is outside the object's bounds
* - Useful for drag operations or global mouse tracking
* - Must have `eventMode` set appropriately to receive events
* - Part of the global move events family along with `globalpointermove` and `globaltouchmove`
*/
onglobalpointermove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerout` event.
* Fired when the pointer moves out of the bounds of the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerout', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onpointerout = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onpointerout?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerover` event.
* Fired when the pointer moves over the bounds of the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerover', (event) => {
* sprite.scale.set(1.2);
* });
* // Using property-based handler
* sprite.onpointerover = (event) => {
* sprite.scale.set(1.2);
* };
* ```
* @default null
*/
onpointerover?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointertap` event.
* Fired when a pointer device completes a tap action (e.g., touch or mouse click).
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointertap', (event) => {
* console.log('Sprite tapped at:', event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onpointertap = (event) => {
* console.log('Sprite tapped at:', event.global.x, event.global.y);
* };
* ```
* @default null
*/
onpointertap?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerup` event.
* Fired when a pointer device button (mouse, touch, pen, etc.) is released.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerup', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onpointerup = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onpointerup?: FederatedEventHandler | null;
/**
* Property-based event handler for the `pointerupoutside` event.
* Fired when a pointer device button is released outside the bounds of the display object
* that initially registered a pointerdown.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('pointerupoutside', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onpointerupoutside = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onpointerupoutside?: FederatedEventHandler | null;
/**
* Property-based event handler for the `rightclick` event.
* Fired when a right-click (context menu) action is performed on the object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('rightclick', (event) => {
* console.log('Right-clicked at:', event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onrightclick = (event) => {
* console.log('Right-clicked at:', event.global.x, event.global.y);
* };
* ```
* @default null
*/
onrightclick?: FederatedEventHandler | null;
/**
* Property-based event handler for the `rightdown` event.
* Fired when a right mouse button is pressed down over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('rightdown', (event) => {
* sprite.scale.set(0.9);
* });
* // Using property-based handler
* sprite.onrightdown = (event) => {
* sprite.scale.set(0.9);
* };
* ```
* @default null
*/
onrightdown?: FederatedEventHandler | null;
/**
* Property-based event handler for the `rightup` event.
* Fired when a right mouse button is released over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('rightup', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onrightup = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onrightup?: FederatedEventHandler | null;
/**
* Property-based event handler for the `rightupoutside` event.
* Fired when a right mouse button is released outside the bounds of the display object
* that initially registered a rightdown.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('rightupoutside', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.onrightupoutside = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
onrightupoutside?: FederatedEventHandler | null;
/**
* Property-based event handler for the `tap` event.
* Fired when a tap action (touch) is completed on the object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('tap', (event) => {
* console.log('Sprite tapped at:', event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.ontap = (event) => {
* console.log('Sprite tapped at:', event.global.x, event.global.y);
* };
* ```
* @default null
*/
ontap?: FederatedEventHandler | null;
/**
* Property-based event handler for the `touchcancel` event.
* Fired when a touch interaction is canceled, such as when the touch is interrupted.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('touchcancel', (event) => {
* console.log('Touch canceled at:', event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.ontouchcancel = (event) => {
* console.log('Touch canceled at:', event.global.x, event.global.y);
* };
* ```
* @default null
*/
ontouchcancel?: FederatedEventHandler | null;
/**
* Property-based event handler for the `touchend` event.
* Fired when a touch interaction ends, such as when the finger is lifted from the screen.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('touchend', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.ontouchend = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
ontouchend?: FederatedEventHandler | null;
/**
* Property-based event handler for the `touchendoutside` event.
* Fired when a touch interaction ends outside the bounds of the display object
* that initially registered a touchstart.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('touchendoutside', (event) => {
* sprite.scale.set(1.0);
* });
* // Using property-based handler
* sprite.ontouchendoutside = (event) => {
* sprite.scale.set(1.0);
* };
* ```
* @default null
*/
ontouchendoutside?: FederatedEventHandler | null;
/**
* Property-based event handler for the `touchmove` event.
* Fired when a touch interaction moves while over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('touchmove', (event) => {
* sprite.position.set(event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.ontouchmove = (event) => {
* sprite.position.set(event.global.x, event.global.y);
* };
* ```
* @default null
*/
ontouchmove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `globaltouchmove` event.
*
* Fired when a touch interaction moves anywhere, regardless of whether the pointer is over this object.
* The object must have `eventMode` set to 'static' or 'dynamic' to receive this event.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('globaltouchmove', (event) => {
* sprite.position.set(event.global.x, event.global.y);
* });
* // Using property-based handler
* sprite.onglobaltouchmove = (event) => {
* sprite.position.set(event.global.x, event.global.y);
* };
* ```
* @default null
* @remarks
* - Fires even when the touch is outside the object's bounds
* - Useful for drag operations or global touch tracking
* - Must have `eventMode` set appropriately to receive events
* - Part of the global move events family along with `globalpointermove` and `globalmousemove`
*/
onglobaltouchmove?: FederatedEventHandler | null;
/**
* Property-based event handler for the `touchstart` event.
* Fired when a touch interaction starts, such as when a finger touches the screen.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('touchstart', (event) => {
* sprite.scale.set(0.9);
* });
* // Using property-based handler
* sprite.ontouchstart = (event) => {
* sprite.scale.set(0.9);
* };
* ```
* @default null
*/
ontouchstart?: FederatedEventHandler | null;
/**
* Property-based event handler for the `wheel` event.
* Fired when the mouse wheel is scrolled while over the display object.
* @example
* ```ts
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
*
* // Using emitter handler
* sprite.on('wheel', (event) => {
* sprite.scale.x += event.deltaY * 0.01; // Zoom in/out
* sprite.scale.y += event.deltaY * 0.01; // Zoom in/out
* });
* // Using property-based handler
* sprite.onwheel = (event) => {
* sprite.scale.x += event.deltaY * 0.01; // Zoom in/out
* sprite.scale.y += event.deltaY * 0.01; // Zoom in/out
* };
* ```
* @default null
*/
onwheel?: FederatedEventHandler<FederatedWheelEvent> | null;
}
/**
* The options for the `addEventListener` method.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener}
* @category events
* @advanced
*/
export type AddListenerOptions = boolean | AddEventListenerOptions;
/**
* The options for the `removeEventListener` method.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener}
* @category events
* @advanced
*/
export type RemoveListenerOptions = boolean | EventListenerOptions;
/**
* Additional properties for a Container that is used for interaction events.
* @category events
* @advanced
*/
export interface IFederatedContainer extends FederatedOptions {
/** The parent of this event target. */
readonly parent?: Container | null;
/** The children of this event target. */
readonly children?: ReadonlyArray<Container>;
/** @private */
_internalEventMode: EventMode;
/**
* Determines if the container is interactive or not
* @returns {boolean} Whether the container is interactive or not
* @since 7.2.0
* @example
* import { Sprite } from 'pixi.js';
*
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static';
* sprite.isInteractive(); // true
*
* sprite.eventMode = 'dynamic';
* sprite.isInteractive(); // true
*
* sprite.eventMode = 'none';
* sprite.isInteractive(); // false
*
* sprite.eventMode = 'passive';
* sprite.isInteractive(); // false
*
* sprite.eventMode = 'auto';
* sprite.isInteractive(); // false
*/
isInteractive: () => boolean;
/**
* Unlike `on` or `addListener` which are methods from EventEmitter, `addEventListener`
* seeks to be compatible with the DOM's `addEventListener` with support for options.
* @param {any} type - The type of event to listen to.
* @param {any} listener - The listener callback or object.
* @param {any} options - Listener options, used for capture phase.
* @example
* // Tell the user whether they did a single, double, triple, or nth click.
* button.addEventListener('click', {
* handleEvent(e): {
* let prefix;
*
* switch (e.detail) {
* case 1: prefix = 'single'; break;
* case 2: prefix = 'double'; break;
* case 3: prefix = 'triple'; break;
* default: prefix = e.detail + 'th'; break;
* }
*
* console.log('That was a ' + prefix + 'click');
* }
* });
*
* // But skip the first click!
* button.parent.addEventListener('click', function blockClickOnce(e) {
* e.stopImmediatePropagation();
* button.parent.removeEventListener('click', blockClickOnce, true);
* }, {
* capture: true,
* });
*/
addEventListener<K extends keyof AllFederatedEventMap>(type: K, listener: (e: AllFederatedEventMap[K]) => any, options?: AddListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: AddListenerOptions): void;
/**
* Unlike `off` or `removeListener` which are methods from EventEmitter, `removeEventListener`
* seeks to be compatible with the DOM's `removeEventListener` with support for options.
* @param {K} type - The type of event the listener is bound to.
* @param {any} listener - The listener callback or object.
* @param {RemoveListenerOptions} options - The original listener options.
* This is required to deregister a capture phase listener.
*/
removeEventListener<K extends keyof AllFederatedEventMap>(type: K, listener: (e: AllFederatedEventMap[K]) => any, options?: RemoveListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: RemoveListenerOptions): void;
/**
* Dispatch the event on this {@link Container} using the event's {@link EventBoundary}.
*
* The target of the event is set to `this` and the `defaultPrevented` flag is cleared before dispatch.
* @param {FederatedEvent} e - The event to dispatch.
* @returns Whether the {@link FederatedEvent.preventDefault preventDefault}() method was not invoked.
* @example
* // Reuse a click event!
* button.dispatchEvent(clickEvent);
*/
dispatchEvent(e: FederatedEvent): boolean;
}
/** @internal */
export declare const FederatedContainer: IFederatedContainer;
/**
* Event boundaries are "barriers" where events coming from an upstream scene are modified before downstream propagation.
*
* ## Root event boundary
*
* The {@link EventSystem#rootBoundary rootBoundary} handles events coming from the <canvas />.
* {@link EventSystem} handles the normalization from native {@link https://dom.spec.whatwg.org/#event Events}
* into {@link FederatedEvent FederatedEvents}. The rootBoundary then does the hit-testing and event dispatch
* for the upstream normalized event.
*
* ## Additional event boundaries
*
* An additional event boundary may be desired within an application's scene graph. For example, if a portion of the scene is
* is flat with many children at one level - a spatial hash maybe needed to accelerate hit testing. In this scenario, the
* container can be detached from the scene and glued using a custom event boundary.
*
* ```ts
* import { Container } from 'pixi.js';
* import { EventBoundary } from 'pixi.js';
* import { SpatialHash } from 'pixi-spatial-hash';
*
* class HashedHitTestingEventBoundary
* {
* private spatialHash: SpatialHash;
*
* constructor(scene: Container, spatialHash: SpatialHash)
* {
* super(scene);
* this.spatialHash = spatialHash;
* }
*
* hitTestRecursive(...)
* {
* // TODO: If target === this.rootTarget, then use spatial hash to get a
* // list of possible children that match the given (x,y) coordinates.
* }
* }
*
* class VastScene extends Container
* {
* protected eventBoundary: EventBoundary;
* protected scene: Container;
* protected spatialHash: SpatialHash;
*
* constructor()
* {
* this.scene = new Container();
* this.spatialHash = new SpatialHash();
* this.eventBoundary = new HashedHitTestingEventBoundary(this.scene, this.spatialHash);
*
* // Populate this.scene with a ton of children, while updating this.spatialHash
* }
* }
* ```
* @category events
* @advanced
*/
export declare class EventBoundary {
/**
* The root event-target residing below the event boundary.
* All events are dispatched trickling down and bubbling up to this `rootTarget`.
*/
rootTarget: Container;
/**
* Emits events after they were dispatched into the scene graph.
*
* This can be used for global events listening, regardless of the scene graph being used. It should
* not be used by interactive libraries for normal use.
*
* Special events that do not bubble all the way to the root target are not emitted from here,
* e.g. pointerenter, pointerleave, click.
*/
dispatch: EventEmitter;
/** The cursor preferred by the event targets underneath this boundary. */
cursor: Cursor | (string & {});
/**
* This flag would emit `pointermove`, `touchmove`, and `mousemove` events on all Containers.
*
* The `moveOnAll` semantics mirror those of earlier versions of PixiJS. This was disabled in favor of
* the Pointer Event API's approach.
*/
moveOnAll: boolean;
/** Enables the global move events. `globalpointermove`, `globaltouchmove`, and `globalmousemove` */
enableGlobalMoveEvents: boolean;
/**
* Maps event types to forwarding handles for them.
*
* {@link EventBoundary EventBoundary} provides mapping for "pointerdown", "pointermove",
* "pointerout", "pointerleave", "pointerover", "pointerup", and "pointerupoutside" by default.
* @see EventBoundary#addEventMapping
*/
protected mappingTable: Record<string, Array<{
fn: (e: FederatedEvent) => void;
priority: number;
}>>;
/**
* State object for mapping methods.
* @see EventBoundary#trackingData
*/
protected mappingState: Record<string, any>;
/**
* The event pool maps event constructors to an free pool of instances of those specific events.
* @see EventBoundary#allocateEvent
* @see EventBoundary#freeEvent
*/
protected eventPool: Map<typeof FederatedEvent, FederatedEvent[]>;
/** Every interactive element gathered from the scene. Only used in `pointermove` */
private readonly _allInteractiveElements;
/** Every element that passed the hit test. Only used in `pointermove` */
private _hitElements;
/** Whether or not to collect all the interactive elements from the scene. Enabled in `pointermove` */
private _isPointerMoveEvent;
/**
* @param rootTarget - The holder of the event boundary.
*/
constructor(rootTarget?: Container);
/**
* Adds an event mapping for the event `type` handled by `fn`.
*
* Event mappings can be used to implement additional or custom events. They take an event
* coming from the upstream scene (or directly from the {@link EventSystem}) and dispatch new downstream events
* generally trickling down and bubbling up to {@link EventBoundary.rootTarget this.rootTarget}.
*
* To modify the semantics of existing events, the built-in mapping methods of EventBoundary should be overridden
* instead.
* @param type - The type of upstream event to map.
* @param fn - The mapping method. The context of this function must be bound manually, if desired.
*/
addEventMapping(type: string, fn: (e: FederatedEvent) => void): void;
/**
* Dispatches the given event
* @param e - The event to dispatch.
* @param type - The type of event to dispatch. Defaults to `e.type`.
*/
dispatchEvent(e: FederatedEvent, type?: string): void;
/**
* Maps the given upstream event through the event boundary and propagates it downstream.
* @param e - The event to map.
*/
mapEvent(e: FederatedEvent): void;
/**
* Finds the Container that is the target of a event at the given coordinates.
*
* The passed (x,y) coordinates are in the world space above this event boundary.
* @param x - The x coordinate of the event.
* @param y - The y coordinate of the event.
*/
hitTest(x: number, y: number): Container;
/**
* Propagate the passed event from from {@link EventBoundary.rootTarget this.rootTarget} to its
* target `e.target`.
* @param e - The event to propagate.
* @param type - The type of event to propagate. Defaults to `e.type`.
*/
propagate(e: FederatedEvent, type?: string): void;
/**
* Emits the event `e` to all interactive containers. The event is propagated in the bubbling phase always.
*
* This is used in the `globalpointermove` event.
* @param e - The emitted event.
* @param type - The listeners to notify.
* @param targets - The targets to notify.
*/
all(e: FederatedEvent, type?: string | string[], targets?: Container<ContainerChild>[]): void;
/**
* Finds the propagation path from {@link EventBoundary.rootTarget rootTarget} to the passed
* `target`. The last element in the path is `target`.
* @param target - The target to find the propagation path to.
*/
propagationPath(target: Container): Container[];
protected hitTestMoveRecursive(currentTarget: Container, eventMode: EventMode, location: Point, testFn: (object: Container, pt: Point) => boolean, pruneFn: (object: Container, pt: Point) => boolean, ignore?: boolean): Container[];
/**
* Recursive implementation for {@link EventBoundary.hitTest hitTest}.
* @param currentTarget - The Container that is to be hit tested.
* @param eventMode - The event mode for the `currentTarget` or one of its parents.
* @param location - The location that is being tested for overlap.
* @param testFn - Callback that determines whether the target passes hit testing. This callback
* can assume that `pruneFn` failed to prune the container.
* @param pruneFn - Callback that determiness whether the target and all of its children
* cannot pass the hit test. It is used as a preliminary optimization to prune entire subtrees
* of the scene graph.
* @returns An array holding the hit testing target and all its ancestors in order. The first element
* is the target itself and the last is {@link EventBoundary.rootTarget rootTarget}. This is the opposite
* order w.r.t. the propagation path. If no hit testing target is found, null is returned.
*/
protected hitTestRecursive(currentTarget: Container, eventMode: EventMode, location: Point, testFn: (object: Container, pt: Point) => boolean, pruneFn: (object: Container, pt: Point) => boolean): Container[];
private _isInteractive;
private _interactivePrune;
/**
* Checks whether the container or any of its children cannot pass the hit test at all.
*
* {@link EventBoundary}'s implementation uses the {@link Container.hitArea hitArea}
* and {@link Container._maskEffect} for pruning.
* @param container - The container to prune.
* @param location - The location to test for overlap.
*/
protected hitPruneFn(container: Container, location: Point): boolean;
/**
* Checks whether the container passes hit testing for the given location.
* @param container - The container to test.
* @param location - The location to test for overlap.
* @returns - Whether `container` passes hit testing for `location`.
*/
protected hitTestFn(container: Container, location: Point): boolean;
/**
* Notify all the listeners to the event's `currentTarget`.
*
* If the `currentTarget` contains the property `on<type>`, then it is called here,
* simulating the behavior from version 6.x and prior.
* @param e - The event passed to the target.
* @param type - The type of event to notify. Defaults to `e.type`.
*/
protected notifyTarget(e: FederatedEvent, type?: string): void;
/**
* Maps the upstream `pointerdown` events to a downstream `pointerdown` event.
*
* `touchstart`, `rightdown`, `mousedown` events are also dispatched for specific pointer types.
* @param from - The upstream `pointerdown` event.
*/
protected mapPointerDown(from: FederatedEvent): void;
/**
* Maps the upstream `pointermove` to downstream `pointerout`, `pointerover`, and `pointermove` events, in that order.
*
* The tracking data for the specific pointer has an updated `overTarget`. `mouseout`, `mouseover`,
* `mousemove`, and `touchmove` events are fired as well for specific pointer types.
* @param from - The upstream `pointermove` event.
*/
protected mapPointerMove(from: FederatedEvent): void;
/**
* Maps the upstream `pointerover` to downstream `pointerover` and `pointerenter` events, in that order.
*
* The tracking data for the specific pointer gets a new `overTarget`.
* @param from - The upstream `pointerover` event.
*/
protected mapPointerOver(from: FederatedEvent): void;
/**
* Maps the upstream `pointerout` to downstream `pointerout`, `pointerleave` events, in that order.
*
* The tracking data for the specific pointer is cleared of a `overTarget`.
* @param from - The upstream `pointerout` event.
*/
protected mapPointerOut(from: FederatedEvent): void;
/**
* Maps the upstream `pointerup` event to downstream `pointerup`, `pointerupoutside`,
* and `click`/`rightclick`/`pointertap` events, in that order.
*
* The `pointerupoutside` event bubbles from the original `pointerdown` target to the most specific
* ancestor of the `pointerdown` and `pointerup` targets, which is also the `click` event's target. `touchend`,
* `rightup`, `mouseup`, `touchendoutside`, `rightupoutside`, `mouseupoutside`, and `tap` are fired as well for
* specific pointer types.
* @param from - The upstream `pointerup` event.
*/
protected mapPointerUp(from: FederatedEvent): void;
/**
* Maps the upstream `pointerupoutside` event to a downstream `pointerupoutside` event, bubbling from the original
* `pointerdown` target to `rootTarget`.
*
* (The most specific ancestor of the `pointerdown` event and the `pointerup` event must the
* `{@link EventBoundary}'s root because the `pointerup` event occurred outside of the boundary.)
*
* `touchendoutside`, `mouseupoutside`, and `rightupoutside` events are fired as well for specific pointer
* types. The tracking data for the specific pointer is cleared of a `pressTarget`.
* @param from - The upstream `pointerupoutside` event.
*/
protected mapPointerUpOutside(from: FederatedEvent): void;
/**
* Maps the upstream `wheel` event to a downstream `wheel` event.
* @param from - The upstream `wheel` event.
*/
protected mapWheel(from: FederatedEvent): void;
/**
* Finds the most specific event-target in the given propagation path that is still mounted in the scene graph.
*
* This is used to find the correct `pointerup` and `pointerout` target in the case that the original `pointerdown`
* or `pointerover` target was unmounted from the scene graph.
* @param propagationPath - The propagation path was valid in the past.
* @returns - The most specific event-target still mounted at the same location in the scene graph.
*/
protected findMountedTarget(propagationPath: Container[]): Container;
/**
* Creates an event whose `originalEvent` is `from`, with an optional `type` and `target` override.
*
* The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
* @param from - The `originalEvent` for the returned event.
* @param [type=from.type] - The type of the returned event.
* @param target - The target of the returned event.
*/
protected createPointerEvent(from: FederatedPointerEvent, type?: string, target?: Container): FederatedPointerEvent;
/**
* Creates a wheel event whose `originalEvent` is `from`.
*
* The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
* @param from - The upstream wheel event.
*/
protected createWheelEvent(from: FederatedWheelEvent): FederatedWheelEvent;
/**
* Clones the event `from`, with an optional `type` override.
*
* The event is allocated using {@link EventBoundary#allocateEvent this.allocateEvent}.
* @param from - The event to clone.
* @param [type=from.type] - The type of the returned event.
*/
protected clonePointerEvent(from: FederatedPointerEvent, type?: string): FederatedPointerEvent;
/**
* Copies wheel {@link FederatedWheelEvent} data from `from` into `to`.
*
* The following properties are copied:
* + deltaMode
* + deltaX
* + deltaY
* + deltaZ
* @param from - The event to copy data from.
* @param to - The event to copy data into.
*/
protected copyWheelData(from: FederatedWheelEvent, to: FederatedWheelEvent): void;
/**
* Copies pointer {@link FederatedPointerEvent} data from `from` into `to`.
*
* The following properties are copied:
* + pointerId
* + width
* + height
* + isPrimary
* + pointerType
* + pressure
* + tangentialPressure
* + tiltX
* + tiltY
* @param from - The event to copy data from.
* @param to - The event to copy data into.
*/
protected copyPointerData(from: FederatedEvent, to: FederatedEvent): void;
/**
* Copies mouse {@link FederatedMouseEvent} data from `from` to `to`.
*
* The following properties are copied:
* + altKey
* + button
* + buttons
* + clientX
* + clientY
* + metaKey
* + movementX
* + movementY
* + pageX
* + pageY
* + x
* + y
* + screen
* + shiftKey
* + global
* @param from - The event to copy data from.
* @param to - The event to copy data into.
*/
protected copyMouseData(from: FederatedEvent, to: FederatedEvent): void;
/**
* Copies base {@link FederatedEvent} data from `from` into `to`.
*
* The following properties are copied:
* + isTrusted
* + srcElement
* + timeStamp
* + type
* @param from - The event to copy data from.
* @param to - The event to copy data into.
*/
protected copyData(from: FederatedEvent, to: FederatedEvent): void;
/**
* @param id - The pointer ID.
* @returns The tracking data stored for the given pointer. If no data exists, a blank
* state will be created.
*/
protected trackingData(id: number): TrackingData;
/**
* Allocate a specific type of event from {@link EventBoundary#eventPool this.eventPool}.
*
* This allocation is constructor-agnostic, as long as it only takes one argument - this event
* boundary.
* @param constructor - The event's constructor.
* @returns An event of the given type.
*/
protected allocateEvent<T extends FederatedEvent>(constructor: {
new (boundary: EventBoundary): T;
}): T;
/**
* Frees the event and puts it back into the event pool.
*
* It is illegal to reuse the event until it is allocated again, using `this.allocateEvent`.
*
* It is also advised that events not allocated from {@link EventBoundary#allocateEvent this.allocateEvent}
* not be freed. This is because of the possibility that the same event is freed twice, which can cause
* it to be allocated twice & result in overwriting.
* @param event - The event to be freed.
* @throws Error if the event is managed by another event boundary.
*/
protected freeEvent<T extends FederatedEvent>(event: T): void;
/**
* Similar to {@link EventEmitter.emit}, except it stops if the `propagationImmediatelyStopped` flag
* is set on the event.
* @param e - The event to call each listener with.
* @param type - The event key.
*/
private _notifyListeners;
}
/**
* A PixiJS compatible touch event interface that extends the standard DOM Touch interface.
* Provides additional properties to normalize touch input with mouse/pointer events.
* @example
* ```ts
* // Access touch information
* sprite.on('touchstart', (event) => {
* // Standard touch properties
* console.log('Touch position:', event.clientX, event.clientY);
* console.log('Touch ID:', event.pointerId);
*
* // Additional PixiJS properties
* console.log('Pressure:', event.pressure);
* console.log('Size:', event.width, event.height);
* console.log('Tilt:', event.tiltX, event.tiltY);
* });
* ```
* @category events
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Touch} DOM Touch Interface
* @standard
*/
export interface PixiTouch extends Touch {
/** The button being pressed (0: left, 1: middle, 2: right) */
button: number;
/** Bitmap of currently pressed buttons */
buttons: number;
/** Whether this is the primary touch point */
isPrimary: boolean;
/** The width of the touch contact area */
width: number;
/** The height of the touch contact area */
height: number;
/** The angle of tilt along the x-axis (in degrees) */
tiltX: number;
/** The angle of tilt along the y-axis (in degrees) */
tiltY: number;
/** The type of pointer that triggered this event */
pointerType: string;
/** Unique identifier for this touch point */
pointerId: number;
/** The normalized pressure of the pointer (0 to 1) */
pressure: number;
/** The rotation angle of the pointer (e.g., pen) */
twist: number;
/** The normalized tangential pressure of the pointer */
tangentialPressure: number;
/** The x coordinate relative to the current layer */
layerX: number;
/** The y coordinate relative to the current layer */
layerY: number;
/** The x coordinate relative to the target's offset parent */
offsetX: number;
/** The y coordinate relative to the target's offset parent */
offsetY: number;
/** Whether the event was normalized by PixiJS */
isNormalized: boolean;
/** The type of touch event */
type: string;
}
/**
* A DOM-compatible synthetic event implementation for PixiJS's event system.
* This class implements the standard DOM Event interface while providing additional
* functionality specific to PixiJS events.
* > [!NOTE] You wont receive an instance of this class directly, but rather a subclass
* > of this class, such as {@link FederatedPointerEvent}, {@link FederatedMouseEvent}, or
* > {@link FederatedWheelEvent}. This class is the base for all federated events.
* @example
* ```ts
* // Basic event handling
* sprite.on('pointerdown', (event: FederatedEvent) => {
* // Access standard DOM event properties
* console.log('Target:', event.target);
* console.log('Phase:', event.eventPhase);
* console.log('Type:', event.type);
*
* // Control propagation
* event.stopPropagation();
* });
* ```
* @typeParam N - The type of native event held. Can be either a UIEvent or PixiTouch.
* @remarks
* - Implements the standard DOM UIEvent interface
* - Provides event bubbling and capturing phases
* - Supports propagation control
* - Manages event paths through display tree
* - Normalizes native browser events
* @see {@link https://dom.spec.whatwg.org/#event} DOM Event Specification
* @see {@link FederatedPointerEvent} For pointer-specific events
* @see {@link FederatedMouseEvent} For mouse-specific events
* @see {@link FederatedWheelEvent} For wheel-specific events
* @category events
* @standard
*/
export declare class FederatedEvent<N extends UIEvent | PixiTouch = UIEvent | PixiTouch> implements UIEvent {
/** Flags whether this event bubbles. This will take effect only if it is set before propagation. */
bubbles: boolean;
/** @deprecated since 7.0.0 */
cancelBubble: boolean;
/**
* Flags whether this event can be canceled using {@link FederatedEvent.preventDefault}. This is always
* false (for now).
*/
readonly cancelable = false;
/**
* Flag added for compatibility with DOM `Event`. It is not used in the Federated Events
* API.
* @see https://dom.spec.whatwg.org/#dom-event-composed
* @ignore
*/
readonly composed = false;
/** The listeners of the event target that are being notified. */
currentTarget: Container;
/** Flags whether the default response of the user agent was prevent through this event. */
defaultPrevented: boolean;
/**
* The propagation phase.
* @default {@link FederatedEvent.NONE}
*/
eventPhase: number;
/** Flags whether this is a user-trusted event */
isTrusted: boolean;
/** @deprecated since 7.0.0 */
returnValue: boolean;
/** @deprecated since 7.0.0 */
srcElement: EventTarget;
/** The event target that this will be dispatched to. */
target: Container;
/** The timestamp of when the event was created. */
timeStamp: number;
/** The type of event, e.g. `"mouseup"`. */
type: string;
/** The native event that caused the foremost original event. */
nativeEvent: N;
/** The original event that caused this event, if any. */
originalEvent: FederatedEvent<N>;
/** Flags whether propagation was stopped. */
propagationStopped: boolean;
/** Flags whether propagation was immediately stopped. */
propagationImmediatelyStopped: boolean;
/** The composed path of the event's propagation. The `target` is at the end. */
path: Container[];
/** The {@link EventBoundary} that manages this event. Null for root events. */
readonly manager: EventBoundary;
/** Event-specific detail */
detail: number;
/** The global Window object. */
view: WindowProxy;
/**
* Not supported.
* @deprecated since 7.0.0
* @ignore
*/
which: number;
/** The coordinates of the event relative to the nearest DOM layer. This is a non-standard property. */
layer: Point;
/** @readonly */
get layerX(): number;
/** @readonly */
get layerY(): number;
/** The coordinates of the event relative to the DOM document. This is a non-standard property. */
page: Point;
/** @readonly */
get pageX(): number;
/** @readonly */
get pageY(): number;
/**
* @param manager - The event boundary which manages this event. Propagation can only occur
* within the boundary's jurisdiction.
*/
constructor(manager: EventBoundary);
/**
* Fallback for the deprecated `InteractionEvent.data`.
* @deprecated since 7.0.0
*/
get data(): this;
/**
* The propagation path for this event. Alias for {@link EventBoundary.propagationPath}.
* @advanced
*/
composedPath(): Container[];
/**
* Unimplemented method included for implementing the DOM interface `Event`. It will throw an `Error`.
* @deprecated
* @ignore
* @param _type
* @param _bubbles
* @param _cancelable
*/
initEvent(_type: string, _bubbles?: boolean, _cancelable?: boolean): void;
/**
* Unimplemented method included for implementing the DOM interface `UIEvent`. It will throw an `Error`.
* @ignore
* @deprecated
* @param _typeArg
* @param _bubblesArg
* @param _cancelableArg
* @param _viewArg
* @param _detailArg
*/
initUIEvent(_typeArg: string, _bubblesArg?: boolean, _cancelableArg?: boolean, _viewArg?: Window | null, _detailArg?: number): void;
/**
* Prevent default behavior of both PixiJS and the user agent.
* @example
* ```ts
* sprite.on('click', (event) => {
* // Prevent both browser's default click behavior
* // and PixiJS's default handling
* event.preventDefault();
*
* // Custom handling
* customClickHandler();
* });
* ```
* @remarks
* - Only works if the native event is cancelable
* - Does not stop event propagation
*/
preventDefault(): void;
/**
* Stop this event from propagating to any additional listeners, including those
* on the current target and any following targets in the propagation path.
* @example
* ```ts
* container.on('pointerdown', (event) => {
* // Stop all further event handling
* event.stopImmediatePropagation();
*
* // These handlers won't be called:
* // - Other pointerdown listeners on this container
* // - Any pointerdown listeners on parent containers
* });
* ```
* @remarks
* - Immediately stops all event propagation
* - Prevents other listeners on same target from being called
* - More aggressive than stopPropagation()
*/
stopImmediatePropagation(): void;
/**
* Stop this event from propagating to the next target in the propagation path.
* The rest of the listeners on the current target will still be notified.
* @example
* ```ts
* child.on('pointermove', (event) => {
* // Handle event on child
* updateChild();
*
* // Prevent parent handlers from being called
* event.stopPropagation();
* });
*
* // This won't be called if child handles the event
* parent.on('pointermove', (event) => {
* updateParent();
* });
* ```
* @remarks
* - Stops event bubbling to parent containers
* - Does not prevent other listeners on same target
* - Less aggressive than stopImmediatePropagation()
*/
stopPropagation(): void;
/**
* The event propagation phase NONE that indicates that the event is not in any phase.
* @default 0
* @advanced
*/
readonly NONE = 0;
/**
* The event propagation phase CAPTURING_PHASE that indicates that the event is in the capturing phase.
* @default 1
* @advanced
*/
readonly CAPTURING_PHASE = 1;
/**
* The event propagation phase AT_TARGET that indicates that the event is at the target.
* @default 2
* @advanced
*/
readonly AT_TARGET = 2;
/**
* The event propagation phase BUBBLING_PHASE that indicates that the event is in the bubbling phase.
* @default 3
* @advanced
*/
readonly BUBBLING_PHASE = 3;
}
/**
* A specialized event class for mouse interactions in PixiJS applications.
* Extends {@link FederatedEvent} to provide mouse-specific properties and methods
* while maintaining compatibility with the DOM MouseEvent interface.
*
* Key features:
* - Tracks mouse button states
* - Provides modifier key states
* - Supports coordinate systems (client, screen, global)
* - Enables precise position tracking
* @example
* ```ts
* // Basic mouse event handling
* sprite.on('mousemove', (event: FederatedMouseEvent) => {
* // Get coordinates in different spaces
* console.log('Global position:', event.global.x, event.global.y);
* console.log('Client position:', event.client.x, event.client.y);
* console.log('Screen position:', event.screen.x, event.screen.y);
*
* // Check button and modifier states
* if (event.buttons === 1 && event.ctrlKey) {
* console.log('Left click + Control key');
* }
*
* // Get local coordinates relative to any container
* const localPos = event.getLocalPosition(container);
* console.log('Local position:', localPos.x, localPos.y);
* });
*
* // Handle mouse button states
* sprite.on('mousedown', (event: FederatedMouseEvent) => {
* console.log('Mouse button:', event.button); // 0=left, 1=middle, 2=right
* console.log('Active buttons:', event.buttons);
* });
* ```
* @category events
* @see {@link FederatedEvent} For base event functionality
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent} DOM MouseEvent Interface
* @standard
*/
export declare class FederatedMouseEvent extends FederatedEvent<MouseEvent | PointerEvent | PixiTouch> implements MouseEvent {
/** Whether the "alt" key was pressed when this mouse event occurred. */
altKey: boolean;
/** The specific button that was pressed in this mouse event. */
button: number;
/** The button depressed when this event occurred. */
buttons: number;
/** Whether the "control" key was pressed when this mouse event occurred. */
ctrlKey: boolean;
/** Whether the "meta" key was pressed when this mouse event occurred. */
metaKey: boolean;
/** This is currently not implemented in the Federated Events API. */
relatedTarget: EventTarget;
/** Whether the "shift" key was pressed when this mouse event occurred. */
shiftKey: boolean;
/** The coordinates of the mouse event relative to the canvas. */
client: Point;
/** @readonly */
get clientX(): number;
/** @readonly */
get clientY(): number;
/**
* Alias for {@link FederatedMouseEvent.clientX this.clientX}.
* @readonly
*/
get x(): number;
/**
* Alias for {@link FederatedMouseEvent.clientY this.clientY}.
* @readonly
*/
get y(): number;
/** This is the number of clicks that occurs in 200ms/click of each other. */
detail: number;
/** The movement in this pointer relative to the last `mousemove` event. */
movement: Point;
/** @readonly */
get movementX(): number;
/** @readonly */
get movementY(): number;
/** The offset of the pointer coordinates w.r.t. target Container in world space. This is not supported at the moment. */
offset: Point;
/** @readonly */
get offsetX(): number;
/** @readonly */
get offsetY(): number;
/** The pointer coordinates in world space. */
global: Point;
/** @readonly */
get globalX(): number;
/** @readonly */
get globalY(): number;
/**
* The pointer coordinates in the renderer's {@link AbstractRenderer.screen screen}. This has slightly
* different semantics than native PointerEvent screenX/screenY.
*/
screen: Point;
/**
* The pointer coordinates in the renderer's screen. Alias for `screen.x`.
* @readonly
*/
get screenX(): number;
/**
* The pointer coordinates in the renderer's screen. Alias for `screen.y`.
* @readonly
*/
get screenY(): number;
/**
* Converts global coordinates into container-local coordinates.
*
* This method transforms coordinates from world space to a container's local space,
* useful for precise positioning and hit testing.
* @param container - The Container to get local coordinates for
* @param point - Optional Point object to store the result. If not provided, a new Point will be created
* @param globalPos - Optional custom global coordinates. If not provided, the event's global position is used
* @returns The local coordinates as a Point object
* @example
* ```ts
* // Basic usage - get local coordinates relative to a container
* sprite.on('pointermove', (event: FederatedMouseEvent) => {
* // Get position relative to the sprite
* const localPos = event.getLocalPosition(sprite);
* console.log('Local position:', localPos.x, localPos.y);
* });
* // Using custom global coordinates
* const customGlobal = new Point(100, 100);
* sprite.on('pointermove', (event: FederatedMouseEvent) => {
* // Transform custom coordinates
* const localPos = event.getLocalPosition(sprite, undefined, customGlobal);
* console.log('Custom local position:', localPos.x, localPos.y);
* });
* ```
* @see {@link Container.worldTransform} For the transformation matrix
* @see {@link Point} For the point class used to store coordinates
*/
getLocalPosition<P extends PointData = Point>(container: Container, point?: P, globalPos?: PointData): P;
/**
* Whether the modifier key was pressed when this event natively occurred.
* @param key - The modifier key.
*/
getModifierState(key: string): boolean;
/**
* Not supported.
* @param _typeArg
* @param _canBubbleArg
* @param _cancelableArg
* @param _viewArg
* @param _detailArg
* @param _screenXArg
* @param _screenYArg
* @param _clientXArg
* @param _clientYArg
* @param _ctrlKeyArg
* @param _altKeyArg
* @param _shiftKeyArg
* @param _metaKeyArg
* @param _buttonArg
* @param _relatedTargetArg
* @deprecated since 7.0.0
* @ignore
*/
initMouseEvent(_typeArg: string, _canBubbleArg: boolean, _cancelableArg: boolean, _viewArg: Window, _detailArg: number, _screenXArg: number, _screenYArg: number, _clientXArg: number, _clientYArg: number, _ctrlKeyArg: boolean, _altKeyArg: boolean, _shiftKeyArg: boolean, _metaKeyArg: boolean, _buttonArg: number, _relatedTargetArg: EventTarget): void;
}
/**
* A specialized event class for pointer interactions in PixiJS applications.
* Extends {@link FederatedMouseEvent} to provide advanced pointer-specific features
* while maintaining compatibility with the DOM PointerEvent interface.
*
* Key features:
* - Supports multi-touch interactions
* - Provides pressure sensitivity
* - Handles stylus input
* - Tracks pointer dimensions
* - Supports tilt detection
* @example
* ```ts
* // Basic pointer event handling
* sprite.on('pointerdown', (event: FederatedPointerEvent) => {
* // Access pointer information
* console.log('Pointer ID:', event.pointerId);
* console.log('Pointer Type:', event.pointerType);
* console.log('Is Primary:', event.isPrimary);
*
* // Get pressure and tilt data
* console.log('Pressure:', event.pressure);
* console.log('Tilt:', event.tiltX, event.tiltY);
*
* // Access contact geometry
* console.log('Size:', event.width, event.height);
* });
*
* // Handle stylus-specific features
* sprite.on('pointermove', (event: FederatedPointerEvent) => {
* if (event.pointerType === 'pen') {
* // Handle stylus tilt
* const tiltAngle = Math.atan2(event.tiltY, event.tiltX);
* console.log('Tilt angle:', tiltAngle);
*
* // Use barrel button pressure
* console.log('Tangential pressure:', event.tangentialPressure);
* }
* });
* ```
* @see {@link FederatedMouseEvent} For base mouse event functionality
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent} DOM PointerEvent Interface
* @see {@link EventSystem} For the event management system
* @category events
* @standard
*/
export declare class FederatedPointerEvent extends FederatedMouseEvent implements PointerEvent {
/**
* The unique identifier of the pointer.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId}
*/
pointerId: number;
/**
* The width of the pointer's contact along the x-axis, measured in CSS pixels.
* radiusX of TouchEvents will be represented by this value.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
*/
width: number;
/**
* The angle in radians of a pointer or stylus measuring the vertical angle between
* the device's surface to the pointer or stylus.
* A stylus at 0 degrees would be directly parallel whereas at π/2 degrees it would be perpendicular.
* @see https://developer.mozilla.org/docs/Web/API/PointerEvent/altitudeAngle)
*/
altitudeAngle: number;
/**
* The angle in radians of a pointer or stylus measuring an arc from the X axis of the device to
* the pointer or stylus projected onto the screen's plane.
* A stylus at 0 degrees would be pointing to the "0 o'clock" whereas at π/2 degrees it would be pointing at "6 o'clock".
* @see https://developer.mozilla.org/docs/Web/API/PointerEvent/azimuthAngle)
*/
azimuthAngle: number;
/**
* The height of the pointer's contact along the y-axis, measured in CSS pixels.
* radiusY of TouchEvents will be represented by this value.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
*/
height: number;
/**
* Indicates whether or not the pointer device that created the event is the primary pointer.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
*/
isPrimary: boolean;
/**
* The type of pointer that triggered the event.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
*/
pointerType: string;
/**
* Pressure applied by the pointing device during the event.
*s
* A Touch's force property will be represented by this value.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
*/
pressure: number;
/**
* Barrel pressure on a stylus pointer.
* @see https://w3c.github.io/pointerevents/#pointerevent-interface
*/
tangentialPressure: number;
/**
* The angle, in degrees, between the pointer device and the screen.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
*/
tiltX: number;
/**
* The angle, in degrees, between the pointer device and the screen.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
*/
tiltY: number;
/**
* Twist of a stylus pointer.
* @see https://w3c.github.io/pointerevents/#pointerevent-interface
*/
twist: number;
/** This is the number of clicks that occurs in 200ms/click of each other. */
detail: number;
/**
* Only included for completeness for now
* @ignore
*/
getCoalescedEvents(): PointerEvent[];
/**
* Only included for completeness for now
* @ignore
*/
getPredictedEvents(): PointerEvent[];
}
/**
* The types for the events that can be emitted by a Container
* @category events
* @advanced
*/
export type FederatedEventMap = {
click: FederatedPointerEvent;
mousedown: FederatedPointerEvent;
mouseenter: FederatedPointerEvent;
mouseleave: FederatedPointerEvent;
mousemove: FederatedPointerEvent;
mouseout: FederatedPointerEvent;
mouseover: FederatedPointerEvent;
mouseup: FederatedPointerEvent;
mouseupoutside: FederatedPointerEvent;
pointercancel: FederatedPointerEvent;
pointerdown: FederatedPointerEvent;
pointerenter: FederatedPointerEvent;
pointerleave: FederatedPointerEvent;
pointermove: FederatedPointerEvent;
pointerout: FederatedPointerEvent;
pointerover: FederatedPointerEvent;
pointertap: FederatedPointerEvent;
pointerup: FederatedPointerEvent;
pointerupoutside: FederatedPointerEvent;
rightclick: FederatedPointerEvent;
rightdown: FederatedPointerEvent;
rightup: FederatedPointerEvent;
rightupoutside: FederatedPointerEvent;
tap: FederatedPointerEvent;
touchcancel: FederatedPointerEvent;
touchend: FederatedPointerEvent;
touchendoutside: FederatedPointerEvent;
touchmove: FederatedPointerEvent;
touchstart: FederatedPointerEvent;
wheel: FederatedWheelEvent;
};
/**
* The types for the global events that can be emitted by a Container
* @category events
* @advanced
*/
export type GlobalFederatedEventMap = {
globalmousemove: FederatedPointerEvent;
globalpointermove: FederatedPointerEvent;
globaltouchmove: FederatedPointerEvent;
};
/**
* The types for the events that can be emitted by a Container
* @category events
* @advanced
*/
export type AllFederatedEventMap = FederatedEventMap & GlobalFederatedEventMap;
/**
* The types for the events that can be emitted by a Container
* @category events
* @advanced
* @interface
*/
export type FederatedEventEmitterTypes = {
[K in keyof FederatedEventMap as K | `${K}capture`]: [
event: FederatedEventMap[K]
];
} & {
[K in keyof GlobalFederatedEventMap]: [
event: GlobalFederatedEventMap[K]
];
};
/**
* Options for configuring the PixiJS event system. These options control how the event system
* handles different types of interactions and event propagation.
* @example
* ```ts
* // Basic event system configuration
* const app = new Application();
* await app.init({
* // Configure default interaction mode
* eventMode: 'static',
*
* // Configure event features
* eventFeatures: {
* move: true, // Enable pointer movement events
* globalMove: false, // Disable global move events
* click: true, // Enable click events
* wheel: true // Enable wheel/scroll events
* }
* });
*
* // Access event system after initialization
* const eventSystem = app.renderer.events;
* console.log(eventSystem.features); // Check enabled features
* ```
* @see {@link EventSystem} For the main event system implementation
* @see {@link EventMode} For interaction mode details
* @see {@link EventSystemFeatures} For all available feature options
* @advanced
* @category events
*/
export interface EventSystemOptions {
/**
* The default event mode for all display objects.
* Controls how objects respond to interaction events.
*
* Possible values:
* - `'none'`: No interaction events
* - `'passive'`: Only container's children receive events (default)
* - `'auto'`: Receives events when parent is interactive
* - `'static'`: Standard interaction events
* - `'dynamic'`: Like static but with additional synthetic events
* @default 'passive'
*/
eventMode?: EventMode;
/**
* Configuration for enabling/disabling specific event features.
* Use this to optimize performance by turning off unused functionality.
* @example
* ```ts
* const app = new Application();
* await app.init({
* eventFeatures: {
* // Core interaction events
* move: true, // Pointer/mouse/touch movement
* click: true, // Click/tap events
* wheel: true, // Mouse wheel/scroll events
* // Global tracking
* globalMove: false // Global pointer movement
* }
* });
* ```
*/
eventFeatures?: Partial<EventSystemFeatures>;
}
/**
* The event features that are enabled by the EventSystem. These features control
* different types of interaction events in your PixiJS application.
* @example
* ```ts
* // Configure features during application initialization
* const app = new Application();
* await app.init({
* eventFeatures: {
* // Basic interaction events
* move: true, // Enable pointer movement tracking
* click: true, // Enable click/tap events
* wheel: true, // Enable mouse wheel/scroll events
* // Advanced features
* globalMove: false // Disable global move tracking for performance
* }
* });
*
* // Or configure after initialization
* app.renderer.events.features.move = false; // Disable movement events
* app.renderer.events.features.globalMove = true; // Enable global tracking
* ```
* @since 7.2.0
* @category events
* @advanced
*/
export interface EventSystemFeatures {
/**
* Enables pointer events associated with pointer movement.
*
* When enabled, these events will fire:
* - `pointermove` / `mousemove` / `touchmove`
* - `pointerout` / `mouseout`
* - `pointerover` / `mouseover`
* @example
* ```ts
* // Enable movement events
* app.renderer.events.features.move = true;
*
* // Listen for movement
* sprite.on('pointermove', (event) => {
* console.log('Pointer position:', event.global.x, event.global.y);
* });
* ```
* @default true
*/
move: boolean;
/**
* Enables global pointer move events that fire regardless of target.
*
* When enabled, these events will fire:
* - `globalpointermove`
* - `globalmousemove`
* - `globaltouchmove`
* @example
* ```ts
* // Enable global tracking
* app.renderer.events.features.globalMove = true;
*
* // Track pointer globally
* sprite.on('globalpointermove', (event) => {
* // Fires even when pointer is not over sprite
* console.log('Global position:', event.global.x, event.global.y);
* });
* ```
* @default true
*/
globalMove: boolean;
/**
* Enables pointer events associated with clicking/tapping.
*
* When enabled, these events will fire:
* - `pointerdown` / `mousedown` / `touchstart` / `rightdown`
* - `pointerup` / `mouseup` / `touchend` / `rightup`
* - `pointerupoutside` / `mouseupoutside` / `touchendoutside` / `rightupoutside`
* - `click` / `tap`
* @example
* ```ts
* // Enable click events
* app.renderer.events.features.click = true;
*
* // Handle clicks
* sprite.on('click', (event) => {
* console.log('Clicked at:', event.global.x, event.global.y);
* });
* ```
* @default true
*/
click: boolean;
/**
* Enables mouse wheel/scroll events.
* @example
* ```ts
* // Enable wheel events
* app.renderer.events.features.wheel = true;
*
* // Handle scrolling
* sprite.on('wheel', (event) => {
* // Zoom based on scroll direction
* const scale = 1 + (event.deltaY / 1000);
* sprite.scale.set(sprite.scale.x * scale);
* });
* ```
* @default true
*/
wheel: boolean;
}
/**
* The system for handling UI events in PixiJS applications. This class manages mouse, touch, and pointer events,
* normalizing them into a consistent event model.
* @example
* ```ts
* // Access event system through renderer
* const eventSystem = app.renderer.events;
*
* // Configure event features
* eventSystem.features.globalMove = false; // Disable global move events
* eventSystem.features.click = true; // Enable click events
*
* // Set custom cursor styles
* eventSystem.cursorStyles.default = 'pointer';
* eventSystem.cursorStyles.grab = 'grab';
*
* // Get current pointer position
* const pointer = eventSystem.pointer;
* console.log(pointer.global.x, pointer.global.y);
* ```
*
* Features:
* - Normalizes browser events into consistent format
* - Supports mouse, touch, and pointer events
* - Handles event delegation and bubbling
* - Provides cursor management
* - Configurable event features
* @see {@link EventBoundary} For event propagation and handling
* @see {@link FederatedEvent} For the base event class
* @see {@link EventMode} For interaction modes
* @category events
* @standard
*/
export declare class EventSystem implements System<EventSystemOptions> {
/** @ignore */
static extension: ExtensionMetadata;
/**
* The event features that are enabled by the EventSystem
* @since 7.2.0
* @example
* ```ts
* import { EventSystem, EventSystemFeatures } from 'pixi.js';
* // Access the default event features
* EventSystem.defaultEventFeatures = {
* // Enable pointer movement events
* move: true,
* // Enable global pointer move events
* globalMove: true,
* // Enable click events
* click: true,
* // Enable wheel events
* wheel: true,
* };
* ```
*/
static defaultEventFeatures: EventSystemFeatures;
private static _defaultEventMode;
/**
* The default interaction mode for all display objects.
* @see Container.eventMode
* @type {EventMode}
* @readonly
* @since 7.2.0
*/
static get defaultEventMode(): EventMode;
/**
* The {@link EventBoundary} for the stage.
*
* The {@link EventBoundary#rootTarget rootTarget} of this root boundary is automatically set to
* the last rendered object before any event processing is initiated. This means the main scene
* needs to be rendered atleast once before UI events will start propagating.
*
* The root boundary should only be changed during initialization. Otherwise, any state held by the
* event boundary may be lost (like hovered & pressed Containers).
* @advanced
*/
readonly rootBoundary: EventBoundary;
/**
* Indicates whether the current device supports touch events according to the W3C Touch Events spec.
* This is used to determine the appropriate event handling strategy.
* @see {@link https://www.w3.org/TR/touch-events/} W3C Touch Events Specification
* @readonly
* @default 'ontouchstart' in globalThis
*/
readonly supportsTouchEvents: boolean;
/**
* Indicates whether the current device supports pointer events according to the W3C Pointer Events spec.
* Used to optimize event handling and provide more consistent cross-device interaction.
* @see {@link https://www.w3.org/TR/pointerevents/} W3C Pointer Events Specification
* @readonly
* @default !!globalThis.PointerEvent
*/
readonly supportsPointerEvents: boolean;
/**
* Controls whether default browser actions are automatically prevented on pointer events.
* When true, prevents default browser actions from occurring on pointer events.
* @remarks
* - Does not apply to pointer events for backwards compatibility
* - preventDefault on pointer events stops mouse events from firing
* - For every pointer event, there will always be either a mouse or touch event alongside it
* - Setting this to false allows default browser actions (text selection, dragging images, etc.)
* @example
* ```ts
* // Allow default browser actions
* app.renderer.events.autoPreventDefault = false;
*
* // Block default actions (default)
* app.renderer.events.autoPreventDefault = true;
*
* // Example with text selection
* const text = new Text('Selectable text');
* text.eventMode = 'static';
* app.renderer.events.autoPreventDefault = false; // Allow text selection
* ```
* @default true
*/
autoPreventDefault: boolean;
/**
* Dictionary of custom cursor styles that can be used across the application.
* Used to define how different cursor modes are handled when interacting with display objects.
* @example
* ```ts
* // Access event system through renderer
* const eventSystem = app.renderer.events;
*
* // Set string-based cursor styles
* eventSystem.cursorStyles.default = 'pointer';
* eventSystem.cursorStyles.hover = 'grab';
* eventSystem.cursorStyles.drag = 'grabbing';
*
* // Use CSS object for complex styling
* eventSystem.cursorStyles.custom = {
* cursor: 'url("custom.png") 2 2, auto',
* userSelect: 'none'
* };
*
* // Use a url for custom cursors
* const defaultIcon = 'url(\'https://pixijs.com/assets/bunny.png\'),auto';
* eventSystem.cursorStyles.icon = defaultIcon;
*
* // Use callback function for dynamic cursors
* eventSystem.cursorStyles.dynamic = (mode) => {
* // Update cursor based on mode
* document.body.style.cursor = mode === 'hover'
* ? 'pointer'
* : 'default';
* };
*
* // Apply cursor style to a sprite
* sprite.cursor = 'hover'; // Will use the hover style defined above
* sprite.cursor = 'icon'; // Will apply the icon cursor
* sprite.cursor = 'custom'; // Will apply the custom CSS styles
* sprite.cursor = 'drag'; // Will apply the grabbing cursor
* sprite.cursor = 'default'; // Will apply the default pointer cursor
* sprite.cursor = 'dynamic'; // Will call the dynamic function
* ```
* @remarks
* - Strings are treated as CSS cursor values
* - Objects are applied as CSS styles to the DOM element
* - Functions are called directly for custom cursor handling
* - Default styles for 'default' and 'pointer' are provided
* @default
* ```ts
* {
* default: 'inherit',
* pointer: 'pointer' // Default cursor styles
* }
* ```
*/
cursorStyles: Record<string, string | ((mode: string) => void) | CSSStyleDeclaration>;
/**
* The DOM element to which the root event listeners are bound. This is automatically set to
* the renderer's {@link Renderer#view view}.
*/
domElement: HTMLElement;
/** The resolution used to convert between the DOM client space into world space. */
resolution: number;
/** The renderer managing this {@link EventSystem}. */
renderer: Renderer;
/**
* The event features that are enabled by the EventSystem
* @since 7.2.0
* @example
* const app = new Application()
* app.renderer.events.features.globalMove = false
*
* // to override all features use Object.assign
* Object.assign(app.renderer.events.features, {
* move: false,
* globalMove: false,
* click: false,
* wheel: false,
* })
*/
readonly features: EventSystemFeatures;
private _currentCursor;
private readonly _rootPointerEvent;
private readonly _rootWheelEvent;
private _eventsAdded;
/**
* @param {Renderer} renderer
*/
constructor(renderer: Renderer);
/**
* Runner init called, view is available at this point.
* @ignore
*/
init(options: EventSystemOptions): void;
/**
* Handle changing resolution.
* @ignore
*/
resolutionChange(resolution: number): void;
/** Destroys all event listeners and detaches the renderer. */
destroy(): void;
/**
* Sets the current cursor mode, handling any callbacks or CSS style changes.
* The cursor can be a CSS cursor string, a custom callback function, or a key from the cursorStyles dictionary.
* @param mode - Cursor mode to set. Can be:
* - A CSS cursor string (e.g., 'pointer', 'grab')
* - A key from the cursorStyles dictionary
* - null/undefined to reset to default
* @example
* ```ts
* // Using predefined cursor styles
* app.renderer.events.setCursor('pointer'); // Set standard pointer cursor
* app.renderer.events.setCursor('grab'); // Set grab cursor
* app.renderer.events.setCursor(null); // Reset to default
*
* // Using custom cursor styles
* app.renderer.events.cursorStyles.custom = 'url("cursor.png"), auto';
* app.renderer.events.setCursor('custom'); // Apply custom cursor
*
* // Using callback-based cursor
* app.renderer.events.cursorStyles.dynamic = (mode) => {
* document.body.style.cursor = mode === 'hover' ? 'pointer' : 'default';
* };
* app.renderer.events.setCursor('dynamic'); // Trigger cursor callback
* ```
* @remarks
* - Has no effect on OffscreenCanvas except for callback-based cursors
* - Caches current cursor to avoid unnecessary DOM updates
* - Supports CSS cursor values, style objects, and callback functions
* @see {@link EventSystem.cursorStyles} For defining custom cursor styles
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} MDN Cursor Reference
*/
setCursor(mode: string): void;
/**
* The global pointer event instance containing the most recent pointer state.
* This is useful for accessing pointer information without listening to events.
* @example
* ```ts
* // Access current pointer position at any time
* const eventSystem = app.renderer.events;
* const pointer = eventSystem.pointer;
*
* // Get global coordinates
* console.log('Position:', pointer.global.x, pointer.global.y);
*
* // Check button state
* console.log('Buttons pressed:', pointer.buttons);
*
* // Get pointer type and pressure
* console.log('Type:', pointer.pointerType);
* console.log('Pressure:', pointer.pressure);
* ```
* @readonly
* @since 7.2.0
* @see {@link FederatedPointerEvent} For all available pointer properties
*/
get pointer(): Readonly<FederatedPointerEvent>;
/**
* Event handler for pointer down events on {@link EventSystem#domElement this.domElement}.
* @param nativeEvent - The native mouse/pointer/touch event.
*/
private _onPointerDown;
/**
* Event handler for pointer move events on on {@link EventSystem#domElement this.domElement}.
* @param nativeEvent - The native mouse/pointer/touch events.
*/
private _onPointerMove;
/**
* Event handler for pointer up events on {@link EventSystem#domElement this.domElement}.
* @param nativeEvent - The native mouse/pointer/touch event.
*/
private _onPointerUp;
/**
* Event handler for pointer over & out events on {@link EventSystem#domElement this.domElement}.
* @param nativeEvent - The native mouse/pointer/touch event.
*/
private _onPointerOverOut;
/**
* Passive handler for `wheel` events on {@link EventSystem.domElement this.domElement}.
* @param nativeEvent - The native wheel event.
*/
protected onWheel(nativeEvent: WheelEvent): void;
/**
* Sets the {@link EventSystem#domElement domElement} and binds event listeners.
* This method manages the DOM event bindings for the event system, allowing you to
* change or remove the target element that receives input events.
* > [!IMPORTANT] This will default to the canvas element of the renderer, so you
* > should not need to call this unless you are using a custom element.
* @param element - The new DOM element to bind events to, or null to remove all event bindings
* @example
* ```ts
* // Set a new canvas element as the target
* const canvas = document.createElement('canvas');
* app.renderer.events.setTargetElement(canvas);
*
* // Remove all event bindings
* app.renderer.events.setTargetElement(null);
*
* // Switch to a different canvas
* const newCanvas = document.querySelector('#game-canvas');
* app.renderer.events.setTargetElement(newCanvas);
* ```
* @remarks
* - Automatically removes event listeners from previous element
* - Required for the event system to function
* - Safe to call multiple times
* @see {@link EventSystem#domElement} The current DOM element
* @see {@link EventsTicker} For the ticker system that tracks pointer movement
*/
setTargetElement(element: HTMLElement): void;
/** Register event listeners on {@link Renderer#domElement this.domElement}. */
private _addEvents;
/** Unregister event listeners on {@link EventSystem#domElement this.domElement}. */
private _removeEvents;
/**
* Maps coordinates from DOM/screen space into PixiJS normalized coordinates.
* This takes into account the current scale, position, and resolution of the DOM element.
* @param point - The point to store the mapped coordinates in
* @param x - The x coordinate in DOM/client space
* @param y - The y coordinate in DOM/client space
* @example
* ```ts
* // Map mouse coordinates to PixiJS space
* const point = new Point();
* app.renderer.events.mapPositionToPoint(
* point,
* event.clientX,
* event.clientY
* );
* console.log('Mapped position:', point.x, point.y);
*
* // Using with pointer events
* sprite.on('pointermove', (event) => {
* // event.global already contains mapped coordinates
* console.log('Global:', event.global.x, event.global.y);
*
* // Map to local coordinates
* const local = event.getLocalPosition(sprite);
* console.log('Local:', local.x, local.y);
* });
* ```
* @remarks
* - Accounts for element scaling and positioning
* - Adjusts for device pixel ratio/resolution
*/
mapPositionToPoint(point: PointData, x: number, y: number): void;
/**
* Ensures that the original event object contains all data that a regular pointer event would have
* @param event - The original event data from a touch or mouse event
* @returns An array containing a single normalized pointer event, in the case of a pointer
* or mouse event, or a multiple normalized pointer events if there are multiple changed touches
*/
private _normalizeToPointerData;
/**
* Normalizes the native {@link https://w3c.github.io/uievents/#interface-wheelevent WheelEvent}.
*
* The returned {@link FederatedWheelEvent} is a shared instance. It will not persist across
* multiple native wheel events.
* @param nativeEvent - The native wheel event that occurred on the canvas.
* @returns A federated wheel event.
*/
protected normalizeWheelEvent(nativeEvent: WheelEvent): FederatedWheelEvent;
/**
* Normalizes the `nativeEvent` into a federateed {@link FederatedPointerEvent}.
* @param event
* @param nativeEvent
*/
private _bootstrapEvent;
/**
* Transfers base & mouse event data from the `nativeEvent` to the federated event.
* @param event
* @param nativeEvent
*/
private _transferMouseData;
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface Container extends IFederatedContainer {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ContainerOptions extends FederatedOptions {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ContainerEvents extends FederatedEventEmitterTypes {
}
interface RendererOptions {
/**
* The type of interaction behavior for a Container. This is set via the {@link Container#eventMode} property.
* @example
* ```ts
* // Basic event mode setup
* const sprite = new Sprite(texture);
* sprite.eventMode = 'static'; // Enable standard interaction
* sprite.on('pointerdown', () => { console.log('clicked!'); });
*
* // Different event modes
* sprite.eventMode = 'none'; // Disable all interaction
* sprite.eventMode = 'passive'; // Only allow interaction on children
* sprite.eventMode = 'auto'; // Like DOM pointer-events: auto
* sprite.eventMode = 'dynamic'; // For moving/animated objects
* ```
*
* Available modes:
* - `'none'`: Ignores all interaction events, even on its children
* - `'passive'`: **(default)** Does not emit events and ignores hit testing on itself and
* non-interactive children. Interactive children will still emit events.
* - `'auto'`: Does not emit events but is hit tested if parent is interactive.
* Same as `interactive = false` in v7
* - `'static'`: Emit events and is hit tested. Same as `interactive = true` in v7
* - `'dynamic'`: Emits events and is hit tested but will also receive mock interaction events fired from
* a ticker to allow for interaction when the mouse isn't moving
*
* Performance tips:
* - Use `'none'` for pure visual elements
* - Use `'passive'` for containers with some interactive children
* - Use `'static'` for standard buttons/controls
* - Use `'dynamic'` only for moving/animated interactive elements
* @since 7.2.0
*/
eventMode?: EventMode;
/**
* Configuration for enabling/disabling specific event features.
* Use this to optimize performance by turning off unused functionality.
* @example
* ```ts
* const app = new Application();
* await app.init({
* eventFeatures: {
* // Core interaction events
* move: true, // Pointer/mouse/touch movement
* click: true, // Click/tap events
* wheel: true, // Mouse wheel/scroll events
* // Global tracking
* globalMove: false // Global pointer movement
* }
* });
* ```
* @since 7.2.0
*/
eventFeatures?: EventSystemOptions["eventFeatures"];
}
interface RendererSystems {
events: EventSystem;
}
}
}
/** @internal */
export declare class FilterPipe implements InstructionPipe<FilterInstruction> {
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "filter";
};
private _renderer;
constructor(renderer: Renderer);
push(filterEffect: Effect, container: Container, instructionSet: InstructionSet): void;
pop(_filterEffect: Effect, _container: Container, instructionSet: InstructionSet): void;
execute(instruction: FilterInstruction): void;
destroy(): void;
}
declare global {
namespace PixiMixins {
interface RendererSystems {
filter: FilterSystem;
}
interface RendererPipes {
filter: FilterPipe;
}
}
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface Point extends Vector2Math {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ObservablePoint extends Vector2Math {
}
interface Rectangle {
/**
* Accepts `other` Rectangle and returns true if the given Rectangle is equal to `this` Rectangle.
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic equality check
* const rect1 = new Rectangle(0, 0, 100, 100);
* const rect2 = new Rectangle(0, 0, 100, 100);
* console.log(rect1.equals(rect2)); // true
*
* // Check after modifications
* rect2.width = 200;
* console.log(rect1.equals(rect2)); // false
*
* // Compare with offset rectangle
* const offset = new Rectangle(10, 10, 100, 100);
* console.log(rect1.equals(offset)); // false
* ```
* @param {Rectangle} other - The Rectangle to compare with `this`
* @returns {boolean} Returns true if all `x`, `y`, `width`, and `height` are equal.
*/
equals(other: Rectangle): boolean;
/**
* If the area of the intersection between the Rectangles `other` and `this` is not zero,
* returns the area of intersection as a Rectangle object. Otherwise, return an empty Rectangle
* with its properties set to zero.
*
* Rectangles without area (width or height equal to zero) can't intersect or be intersected
* and will always return an empty rectangle with its properties set to zero.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic intersection check
* const rect1 = new Rectangle(0, 0, 100, 100);
* const rect2 = new Rectangle(50, 50, 100, 100);
*
* const overlap = rect1.intersection(rect2);
* console.log(overlap); // Rectangle(50, 50, 50, 50)
*
* // Using output rectangle
* const out = new Rectangle();
* rect1.intersection(rect2, out);
*
* // Zero-area rectangles
* const empty = new Rectangle(0, 0, 0, 100);
* const result = rect1.intersection(empty);
* console.log(result); // Rectangle(0, 0, 0, 0)
* ```
* @param {Rectangle} other - The Rectangle to intersect with `this`.
* @param {Rectangle} [outRect] - A Rectangle object in which to store the value,
* optional (otherwise will create a new Rectangle).
* @returns {Rectangle} The intersection of `this` and `other`.
* @see {@link Rectangle.intersects} For boolean intersection test
* @see {@link Rectangle.union} For combining rectangles
*/
intersection<T extends Rectangle = Rectangle>(other: Rectangle, outRect?: T): T;
/**
* Adds `this` and `other` Rectangles together to create a new Rectangle object filling
* the horizontal and vertical space between the two rectangles.
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic union
* const rect1 = new Rectangle(0, 0, 100, 100);
* const rect2 = new Rectangle(50, 50, 100, 100);
* const combined = rect1.union(rect2);
* console.log(combined); // Rectangle(0, 0, 150, 150)
*
* // Using output rectangle
* const out = new Rectangle();
* rect1.union(rect2, out);
*
* // Chain multiple unions
* const rect3 = new Rectangle(200, 200, 50, 50);
* const result = rect1.union(rect2).union(rect3);
* ```
* @param {Rectangle} other - The Rectangle to unite with `this`
* @param {Rectangle} [outRect] - Optional Rectangle to store the result
* @returns The union of `this` and `other`
* @see {@link Rectangle.intersection} For overlap area
* @see {@link Rectangle.containsRect} For containment testing
*/
union<T extends Rectangle = Rectangle>(other: Rectangle, outRect?: T): T;
}
}
interface Vector2Math {
/**
* Adds `other` to `this` point and outputs into `outPoint` or a new Point.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic point addition
* const point = new Point(10, 20);
* const other = new Point(5, 10);
* const result = point.add(other);
* console.log(result); // Point(15, 30)
*
* // Using output point for efficiency
* const output = new Point();
* point.add(other, output);
* console.log(output); // Point(15, 30)
*
* // Chain multiple additions
* const final = point.add(other).add(new Point(2, 3));
* ```
* @param {PointData} other - The point to add to `this`
* @param {PointData} [outPoint] - Optional Point-like object to store result
* @returns The outPoint or a new Point with addition result
* @see {@link Point.subtract} For point subtraction
* @see {@link Point.multiply} For point multiplication
*/
add<T extends PointData = Point>(other: PointData, outPoint?: T): T;
/**
* Subtracts `other` from `this` point and outputs into `outPoint` or a new Point.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic point subtraction
* const point = new Point(10, 20);
* const other = new Point(5, 10);
* const result = point.subtract(other);
* console.log(result); // Point(5, 10)
*
* // Using output point for efficiency
* const output = new Point();
* point.subtract(other, output);
* console.log(output); // Point(5, 10)
*
* // Chain multiple subtractions
* const final = point.subtract(other).subtract(new Point(2, 3));
* ```
* @param {PointData} other - The point to subtract from `this`
* @param {PointData} [outPoint] - Optional Point-like object to store result
* @returns The outPoint or a new Point with subtraction result
* @see {@link Point.add} For point addition
* @see {@link Point.multiply} For point multiplication
*/
subtract<T extends PointData = Point>(other: PointData, outPoint?: T): T;
/**
* Multiplies component-wise `other` and `this` points and outputs into `outPoint` or a new Point.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic point multiplication
* const point = new Point(10, 20);
* const other = new Point(2, 3);
* const result = point.multiply(other);
* console.log(result); // Point(20, 60)
*
* // Using output point for efficiency
* const output = new Point();
* point.multiply(other, output);
* console.log(output); // Point(20, 60)
*
* // Chain multiple operations
* const final = point.multiply(other).add(new Point(5, 5));
* ```
* @param {PointData} other - The point to multiply with `this`
* @param {PointData} [outPoint] - Optional Point-like object to store result
* @returns The outPoint or a new Point with multiplication result
* @see {@link Point.add} For point addition
* @see {@link Point.multiplyScalar} For scalar multiplication
*/
multiply<T extends PointData = Point>(other: PointData, outPoint?: T): T;
/**
* Multiplies each component of `this` point with the number `scalar` and outputs into `outPoint` or a new Point.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic scalar multiplication
* const point = new Point(10, 20);
* const result = point.multiplyScalar(2);
* console.log(result); // Point(20, 40)
*
* // Using output point for efficiency
* const output = new Point();
* point.multiplyScalar(0.5, output);
* console.log(output); // Point(5, 10)
*
* // Chain with other operations
* const final = point.multiplyScalar(2).add(new Point(5, 5));
* ```
* @param {number} scalar - The number to multiply both components with
* @param {PointData} [outPoint] - Optional Point-like object to store result
* @returns The outPoint or a new Point with multiplication result
* @see {@link Point.multiply} For point multiplication
* @see {@link Point.normalize} For unit vector conversion
*/
multiplyScalar<T extends PointData = Point>(scalar: number, outPoint?: T): T;
/**
* Computes the dot product of `other` with `this` point.
* The dot product is the sum of the products of the corresponding components of two vectors.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic dot product
* const v1 = new Point(2, 3);
* const v2 = new Point(4, 5);
* const result = v1.dot(v2); // 2*4 + 3*5 = 23
*
* // Check if vectors are perpendicular
* const isOrthogonal = v1.dot(v2) === 0;
*
* // Get angle between vectors
* const cosTheta = v1.dot(v2) / (v1.magnitude() * v2.magnitude());
* ```
* @param {PointData} other - The other point to calculate the dot product with
* @returns The scalar result of the dot product
* @see {@link Point.cross} For cross product calculation
* @see {@link Point.magnitude} For vector length
*/
dot(other: PointData): number;
/**
* Computes the cross product of `other` with `this` point.
* Returns the z-component of the 3D cross product, assuming z=0 for both vectors.
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic cross product
* const v1 = new Point(2, 3);
* const v2 = new Point(4, 5);
* const result = v1.cross(v2); // 2*5 - 3*4 = -2
*
* // Check if vectors are parallel
* const isParallel = v1.cross(v2) === 0;
*
* // Get signed area of parallelogram
* const area = Math.abs(v1.cross(v2));
* ```
* @remarks
* - Returns z-component only (x,y assumed in 2D plane)
* - Positive result means counter-clockwise angle from this to other
* - Magnitude equals area of parallelogram formed by vectors
* @param {PointData} other - The other point to calculate the cross product with
* @returns The z-component of the cross product
* @see {@link Point.dot} For dot product calculation
* @see {@link Point.normalize} For unit vector conversion
*/
cross(other: PointData): number;
/**
* Computes a normalized version of `this` point.
*
* A normalized vector is a vector of magnitude (length) 1
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic normalization
* const vector = new Point(3, 4);
* const normalized = vector.normalize();
* console.log(normalized.magnitude()); // 1
*
* // Using output point
* const out = new Point();
* vector.normalize(out);
*
* // Chain with other operations
* const scaled = vector.normalize().multiplyScalar(5);
* ```
* @param {PointData} outPoint - Optional Point-like object to store result
* @returns The normalized point
* @see {@link Point.magnitude} For vector length
* @see {@link Point.multiplyScalar} For scaling
*/
normalize<T extends PointData = Point>(outPoint?: T): T;
/**
* Computes the magnitude (length) of this point as Euclidean distance from origin.
*
* Defined as the square root of the sum of the squares of each component.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic length calculation
* const vector = new Point(3, 4);
* console.log(vector.magnitude()); // 5
*
* // Check if unit vector
* const isUnit = Math.abs(vector.magnitude() - 1) < 0.0001;
*
* // Compare vector lengths
* const longer = v1.magnitude() > v2.magnitude();
* ```
* @returns The magnitude (length) of the vector
* @see {@link Point.magnitudeSquared} For efficient length comparison
* @see {@link Point.normalize} For unit vector conversion
*/
magnitude(): number;
/**
* Computes the squared magnitude of this point.
* More efficient than magnitude() for length comparisons.
*
* Defined as the sum of the squares of each component.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Efficient length comparison
* const v1 = new Point(3, 4);
* const v2 = new Point(1, 2);
*
* // Better than: v1.magnitude() > v2.magnitude()
* const longer = v1.magnitudeSquared() > v2.magnitudeSquared();
*
* // Check if vector is longer than 5 units
* const isLong = v1.magnitudeSquared() > 25; // 5 * 5
* ```
* @returns The squared magnitude of the vector
* @see {@link Point.magnitude} For actual vector length
* @see {@link Point.dot} For dot product calculation
*/
magnitudeSquared(): number;
/**
* Computes vector projection of `this` on `onto`.
* Projects one vector onto another, creating a parallel vector with the length of the projection.
*
* Imagine a light source, parallel to `onto`, above `this`.
* The light would cast rays perpendicular to `onto`.
* `this.project(onto)` is the shadow cast by `this` on the line defined by `onto` .
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @remarks
* - Results in zero vector if projecting onto zero vector
* - Length depends on angle between vectors
* - Result is parallel to `onto` vector
* - Useful for physics and collision responses
* @param {PointData} onto - Vector to project onto (should be non-zero)
* @param {PointData} [outPoint] - Optional Point-like object to store result
* @returns The projection of `this` onto `onto`
* @see {@link Point.dot} For angle calculations
* @see {@link Point.normalize} For unit vector conversion
*/
project<T extends PointData = Point>(onto: PointData, outPoint?: T): T;
/**
* Reflects `this` vector off of a plane orthogonal to `normal`.
*
* Like a light ray bouncing off a mirror surface.
* `this` vector is the light and `normal` is a vector perpendicular to the mirror.
* `this.reflect(normal)` is the reflection of `this` on that mirror.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic reflection
* const ray = new Point(1, 1);
* const surfaceNormal = new Point(0, 1).normalize();
* const reflection = ray.reflect(surfaceNormal);
*
* // Using output point
* const out = new Point();
* ray.reflect(surfaceNormal, out);
*
* // Reflect off angled surface
* const slope = new Point(1, 1).normalize();
* const bounced = ray.reflect(slope);
* ```
* @remarks
* - Normal vector should be normalized for accurate results
* - Preserves vector magnitude
* - Useful for physics simulations
* - Common in light/particle effects
* @param {PointData} normal - The normal vector of the reflecting plane
* @param {PointData} outPoint - Optional Point-like object to store result
* @returns The reflection of `this` off the plane
* @see {@link Point.normalize} For normalizing vectors
* @see {@link Point.dot} For angle calculations
*/
reflect<T extends PointData = Point>(normal: PointData, outPoint?: T): T;
/**
* Rotates `this` vector.
*
* Like a light ray bouncing off a mirror surface.
* `this` vector is the light and `normal` is a vector perpendicular to the mirror.
* `this.reflect(normal)` is the reflection of `this` on that mirror.
*
* > [!IMPORTANT] Only available with **pixi.js/math-extras**.
* @example
* ```ts
* // Basic point rotation
* const point = new Point(10, 20);
* const degrees = 45
* const radians = degrees * (Math.PI / 180)
* const result = point.rotate(radians);
* console.log(result); // {x: -7.071067811865474, y: 21.213203435596427}
*
* // Using output point for efficiency
* const output = new Point(10, 20);
* point.rotate(90 * (Math.PI / 180), output);
* console.log(result); // {x: -7.071067811865474, y: 21.213203435596427}
*
* // Chain multiple additions
* const final = point.rotate(radians).rotate(radians2);
* ```
* @remarks
* convert degrees to radians with const radians = degrees * (Math.PI / 180)
* @param {PointData} radians - The rotation angle in radians
* @param {PointData} outPoint - Optional Point-like object to store result
* @returns The outPoint or a new Point with rotated result
*/
rotate<T extends PointData = Point>(radians: number, outPoint?: T): T;
}
}
/** @internal */
export interface GraphicsAdaptor {
shader: Shader;
contextChange(renderer: Renderer): void;
execute(graphicsPipe: GraphicsPipe, renderable: Graphics): void;
destroy(): void;
}
/** @internal */
export declare class GraphicsGpuData implements GPUData {
batches: BatchableGraphics[];
batched: boolean;
destroy(): void;
}
/** @internal */
export declare class GraphicsPipe implements RenderPipe<Graphics> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "graphics";
};
renderer: Renderer;
state: State;
private _adaptor;
private readonly _managedGraphics;
constructor(renderer: Renderer, adaptor: GraphicsAdaptor);
contextChange(): void;
validateRenderable(graphics: Graphics): boolean;
addRenderable(graphics: Graphics, instructionSet: InstructionSet): void;
updateRenderable(graphics: Graphics): void;
execute(graphics: Graphics): void;
private _rebuild;
private _addToBatcher;
private _getGpuDataForRenderable;
private _initGpuDataForRenderable;
private _updateBatchesForRenderable;
destroy(): void;
}
/**
* The line cap styles for strokes.
*
* It can be:
* - `butt`: The ends of the stroke are squared off at the endpoints.
* - `round`: The ends of the stroke are rounded.
* @category scene
* @standard
*/
export type LineCap = "butt" | "round" | "square";
/**
* The line join styles for strokes.
*
* It can be:
* - `round`: The corners of the stroke are rounded.
* - `bevel`: The corners of the stroke are squared off.
* - `miter`: The corners of the stroke are extended to meet at a point.
* @category scene
* @standard
*/
export type LineJoin = "round" | "bevel" | "miter";
/** @internal */
export declare const closePointEps = 0.0001;
/** @internal */
export declare const curveEps = 0.0001;
/**
* Defines the type of gradient to create.
*
* It can be:
* - 'linear': A linear gradient that transitions colors along a straight line.
* - 'radial': A radial gradient that transitions colors in a circular pattern from an inner circle to an outer circle.
* @category scene
* @standard
*/
export type GradientType = "linear" | "radial";
/**
* Represents the style options for a linear gradient fill.
* @category scene
* @standard
*/
export interface BaseGradientOptions {
/** The type of gradient */
type?: GradientType;
/** Array of colors stops to use in the gradient */
colorStops?: {
offset: number;
color: ColorSource;
}[];
/** Whether coordinates are 'global' or 'local' */
textureSpace?: TextureSpace;
/**
* The size of the texture to use for the gradient - this is for advanced usage.
* The texture size does not need to match the size of the object being drawn.
* Due to GPU interpolation, gradient textures can be relatively small!
* Consider using a larger texture size if your gradient has a lot of very tight color steps
*/
textureSize?: number;
/**
* The wrap mode of the gradient.
* This can be 'clamp-to-edge' or 'repeat'.
* @default 'clamp-to-edge'
*/
wrapMode?: WRAP_MODE;
}
/**
* Options specific to linear gradients.
* A linear gradient creates a smooth transition between colors along a straight line defined by start and end points.
* @category scene
* @standard
*/
export interface LinearGradientOptions extends BaseGradientOptions {
/** The type of gradient. Must be 'linear' for linear gradients. */
type?: "linear";
/**
* The start point of the gradient.
* This point defines where the gradient begins.
* It is represented as a PointData object containing x and y coordinates.
* The coordinates are in local space by default (0-1), but can be in global space if specified.
*/
start?: PointData;
/**
* The end point of the gradient.
* This point defines where the gradient ends.
* It is represented as a PointData object containing x and y coordinates.
* The coordinates are in local space by default (0-1), but can be in global space if specified.
*/
end?: PointData;
}
/**
* Options specific to radial gradients.
* A radial gradient creates a smooth transition between colors that radiates outward in a circular pattern.
* The gradient is defined by inner and outer circles, each with their own radius.
* @category scene
* @standard
*/
export interface RadialGradientOptions extends BaseGradientOptions {
/** The type of gradient. Must be 'radial' for radial gradients. */
type?: "radial";
/** The center point of the inner circle where the gradient begins. In local coordinates by default (0-1). */
center?: PointData;
/** The radius of the inner circle where the gradient begins. */
innerRadius?: number;
/** The center point of the outer circle where the gradient ends. In local coordinates by default (0-1). */
outerCenter?: PointData;
/** The radius of the outer circle where the gradient ends. */
outerRadius?: number;
/**
* The y scale of the gradient, use this to make the gradient elliptical.
* NOTE: Only applied to radial gradients used with Graphics.
*/
scale?: number;
/**
* The rotation of the gradient in radians, useful for making the gradient elliptical.
* NOTE: Only applied to radial gradients used with Graphics.
*/
rotation?: number;
}
/**
* Options for creating a gradient fill.
* @category scene
* @standard
*/
export type GradientOptions = LinearGradientOptions | RadialGradientOptions;
/**
* Class representing a gradient fill that can be used to fill shapes and text.
* Supports both linear and radial gradients with multiple color stops.
*
* For linear gradients, color stops define colors and positions (0 to 1) along a line from start point (x0,y0)
* to end point (x1,y1).
*
* For radial gradients, color stops define colors between two circles - an inner circle centered at (x0,y0) with radius r0,
* and an outer circle centered at (x1,y1) with radius r1.
* @example
* ```ts
* // Create a vertical linear gradient from red to blue
* const linearGradient = new FillGradient({
* type: 'linear',
* start: { x: 0, y: 0 }, // Start at top
* end: { x: 0, y: 1 }, // End at bottom
* colorStops: [
* { offset: 0, color: 'red' }, // Red at start
* { offset: 1, color: 'blue' } // Blue at end
* ],
* // Use normalized coordinate system where (0,0) is the top-left and (1,1) is the bottom-right of the shape
* textureSpace: 'local'
* });
*
* // Create a radial gradient from yellow center to green edge
* const radialGradient = new FillGradient({
* type: 'radial',
* center: { x: 0.5, y: 0.5 },
* innerRadius: 0,
* outerCenter: { x: 0.5, y: 0.5 },
* outerRadius: 0.5,
* colorStops: [
* { offset: 0, color: 'yellow' }, // Center color
* { offset: 1, color: 'green' } // Edge color
* ],
* // Use normalized coordinate system where (0,0) is the top-left and (1,1) is the bottom-right of the shape
* textureSpace: 'local'
* });
*
* // Create a rainbow linear gradient in global coordinates
* const globalGradient = new FillGradient({
* type: 'linear',
* start: { x: 0, y: 0 },
* end: { x: 100, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 }, // Red
* { offset: 0.33, color: 0x00ff00 }, // Green
* { offset: 0.66, color: 0x0000ff }, // Blue
* { offset: 1, color: 0xff00ff } // Purple
* ],
* textureSpace: 'global' // Use world coordinates
* });
*
* // Create an offset radial gradient
* const offsetRadial = new FillGradient({
* type: 'radial',
* center: { x: 0.3, y: 0.3 },
* innerRadius: 0.1,
* outerCenter: { x: 0.5, y: 0.5 },
* outerRadius: 0.5,
* colorStops: [
* { offset: 0, color: 'white' },
* { offset: 1, color: 'black' }
* ],
* // Use normalized coordinate system where (0,0) is the top-left and (1,1) is the bottom-right of the shape
* textureSpace: 'local'
* });
* ```
*
* Internally this creates a texture of the gradient then applies a
* transform to it to give it the correct size and angle.
*
* This means that it's important to destroy a gradient when it is no longer needed
* to avoid memory leaks.
*
* If you want to animate a gradient then it's best to modify and update an existing one
* rather than creating a whole new one each time. That or use a custom shader.
* @category scene
* @standard
*/
export declare class FillGradient implements CanvasGradient {
/** Default options for creating a gradient fill */
static readonly defaultLinearOptions: LinearGradientOptions;
/** Default options for creating a radial gradient fill */
static readonly defaultRadialOptions: RadialGradientOptions;
/**
* Unique identifier for this gradient instance
* @internal
*/
readonly uid: number;
/**
* Internal tick counter to track changes in the gradient.
* This is used to invalidate the gradient when the texture changes.
* @internal
*/
_tick: number;
/** Type of gradient - currently only supports 'linear' */
readonly type: GradientType;
/** Internal texture used to render the gradient */
texture: Texture;
/** Transform matrix for positioning the gradient */
transform: Matrix;
/** Array of color stops defining the gradient */
colorStops: Array<{
offset: number;
color: string;
}>;
/** Whether gradient coordinates are in local or global space */
textureSpace: TextureSpace;
private readonly _textureSize;
/** The start point of the linear gradient */
start: PointData;
/** The end point of the linear gradient */
end: PointData;
/** The wrap mode of the gradient texture */
private readonly _wrapMode;
/** The center point of the inner circle of the radial gradient */
center: PointData;
/** The center point of the outer circle of the radial gradient */
outerCenter: PointData;
/** The radius of the inner circle of the radial gradient */
innerRadius: number;
/** The radius of the outer circle of the radial gradient */
outerRadius: number;
/** The scale of the radial gradient */
scale: number;
/** The rotation of the radial gradient */
rotation: number;
/**
* Creates a new gradient fill. The constructor behavior changes based on the gradient type.
* @param {GradientOptions} options - The options for the gradient
* @see {@link LinearGradientOptions}
* @see {@link RadialGradientOptions}
*/
constructor(options: GradientOptions);
/**
* Deprecated: Use the options object instead.
* @deprecated since 8.5.2
* @ignore
*/
constructor(x0?: number, y0?: number, x1?: number, y1?: number, textureSpace?: TextureSpace, textureSize?: number);
/**
* Adds a color stop to the gradient
* @param offset - Position of the stop (0-1)
* @param color - Color of the stop
* @returns This gradient instance for chaining
*/
addColorStop(offset: number, color: ColorSource): this;
/**
* Builds the internal texture and transform for the gradient.
* Called automatically when the gradient is first used.
* @internal
*/
buildLinearGradient(): void;
/**
* Builds the internal texture and transform for the gradient.
* Called automatically when the gradient is first used.
* @internal
*/
buildGradient(): void;
/**
* Builds the internal texture and transform for the radial gradient.
* Called automatically when the gradient is first used.
* @internal
*/
buildRadialGradient(): void;
/** Destroys the gradient, releasing resources. This will also destroy the internal texture. */
destroy(): void;
/**
* Returns a unique key for this gradient instance.
* This key is used for caching and texture management.
* @returns {string} Unique key for the gradient
*/
get styleKey(): string;
}
/**
* Defines the repetition modes for fill patterns.
*
* - `repeat`: The pattern repeats in both directions.
* - `repeat-x`: The pattern repeats horizontally only.
* - `repeat-y`: The pattern repeats vertically only.
* - `no-repeat`: The pattern does not repeat.
* @category scene
* @standard
*/
export type PatternRepetition = "repeat" | "repeat-x" | "repeat-y" | "no-repeat";
/**
* A class that represents a fill pattern for use in Text and Graphics fills.
* It allows for textures to be used as patterns, with optional repetition modes.
* @category scene
* @standard
* @example
* const txt = await Assets.load('https://pixijs.com/assets/bg_scene_rotate.jpg');
* const pat = new FillPattern(txt, 'repeat');
*
* const textPattern = new Text({
* text: 'PixiJS',
* style: {
* fontSize: 36,
* fill: 0xffffff,
* stroke: { fill: pat, width: 10 },
* },
* });
*
* textPattern.y = (textGradient.height);
*/
export declare class FillPattern implements CanvasPattern {
/**
* unique id for this fill pattern
* @internal
*/
readonly uid: number;
/**
* Internal tick counter to track changes in the pattern.
* This is used to invalidate the pattern when the texture or transform changes.
* @internal
*/
_tick: number;
/** @internal */
_texture: Texture;
/** The transform matrix applied to the pattern */
transform: Matrix;
constructor(texture: Texture, repetition?: PatternRepetition);
/**
* Sets the transform for the pattern
* @param transform - The transform matrix to apply to the pattern.
* If not provided, the pattern will use the default transform.
*/
setTransform(transform?: Matrix): void;
/** Internal texture used to render the gradient */
get texture(): Texture;
set texture(value: Texture);
/**
* Returns a unique key for this instance.
* This key is used for caching.
* @returns {string} Unique key for the instance
*/
get styleKey(): string;
/** Destroys the fill pattern, releasing resources. This will also destroy the internal texture. */
destroy(): void;
}
/**
* Determines how texture coordinates are calculated
* Local Space: Global Space:
* ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
* │ A B │ │ A B │ │ A...B │ │ ...B... │
* │ │ │ │ │ │ │ │
* │ C D │ │ C D │ │ C...D │ │ ...D... │
* └─────────┘ └─────────┘ └─────────┘ └─────────┘
* (Each shape (Each shape (Texture continues across
* gets full gets full shapes as if they're texture) texture) windows to same texture)
* @category scene
* @advanced
*/
export type TextureSpace =
/**
* 'local' - Texture coordinates are relative to the shape's bounds.
* The texture will stretch/fit to each individual shape's boundaries.
* Think of it like the shape having its own coordinate system.
*/
"local"
/**
* 'global' - Texture coordinates are in world space.
* The texture position is consistent across all shapes,
* as if the texture was laid down first and shapes were cut out of it.
* Think of it like wallpaper that shows through shaped holes.
*/
| "global";
/**
* Defines the style properties used for filling shapes in graphics and text operations.
* This interface provides options for colors, textures, patterns, and gradients.
* @example
* ```ts
* // Basic color fill
* const fillStyle = {
* color: 0xff0000, // Red
* alpha: 0.5 // 50% opacity
* };
*
* // Textured fill ( Graphics only )
* const fillStyle = {
* texture: Texture.from('myImage.png'),
* matrix: new Matrix().scale(0.5, 0.5),
* };
*
* // Gradient fill
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* })
*
* const fillStyle = {
* fill: gradient,
* alpha: 1
* };
* ```
* @see {@link FillPattern} For creating pattern fills
* @see {@link FillGradient} For creating gradient fills
* @see {@link TextureSpace} For texture coordinate calculation modes
* @category scene
* @standard
*/
export interface FillStyle {
/**
* The color to use for the fill.
* This can be any valid color source, such as a hex value, a Color object, or a string.
* @example
* ```ts
* // Using a hex color
* const fillStyle = { color: 0xff0000 }; // Red
* // Using a Color object
* const fillStyle = { color: new Color(1, 0, 0) }; // Red
* // Using a string color
* const fillStyle = { color: 'red' }; // Red
* // Using object string
* const fillStyle = { color: 'rgb(255, 0, 0)' }; // Red
* ```
* @see {@link ColorSource} For more details on color sources
*/
color?: ColorSource;
/**
* The alpha value to use for the fill.
* This value should be between 0 (fully transparent) and 1 (fully opaque).
* @example
* ```ts
* const fillStyle = { alpha: 0.5 }; // 50% opacity
* ```
* @default 1
* @see {@link ColorSource} For more details on color sources
* @see {@link FillStyle#color} For color usage
*/
alpha?: number;
/**
* The texture to use for the fill.
* @example
* ```ts
* const fillStyle = { texture: Texture.from('myImage.png') };
* ```
* @see {@link Texture} For more details on textures
*/
texture?: Texture | null;
/**
* The transformation matrix to apply to the fill pattern or texture.
* Used to scale, rotate, translate, or skew the fill.
* @example
* ```ts
* // Scale and rotate a texture fill
* const fillStyle = {
* texture: Texture.from('myImage.png'),
* matrix: new Matrix()
* .scale(0.5, 0.5)
* .rotate(Math.PI / 4)
* };
* ```
* @default null
*/
matrix?: Matrix | null;
/**
* The fill pattern or gradient to use. This can be either a FillPattern for
* repeating textures or a FillGradient for color transitions.
* @example
* ```ts
* // Using a gradient
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* });
*
* const fillStyle = {
* fill: gradient,
* alpha: 0.8
* };
*
* // Using a pattern
* const pattern = new FillPattern(
* Texture.from('pattern.png'),
* 'repeat' // or 'no-repeat', 'repeat-x', 'repeat-y'
* );
*
* const fillStyle = {
* fill: pattern
* };
* ```
* @see {@link FillPattern} For creating pattern fills
* @see {@link FillGradient} For creating gradient fills
*/
fill?: FillPattern | FillGradient | null;
/**
* Determines how texture coordinates are calculated across shapes.
* - 'local': Texture coordinates are relative to each shape's bounds
* - 'global': Texture coordinates are in world space
* @example
* ```ts
* // Local space - texture fits each shape independently
* const fillStyle = {
* texture: Texture.from('myImage.png'),
* textureSpace: 'local'
* };
*
* // Global space - texture continues across shapes
* const fillStyle = {
* texture: Texture.from('myImage.png'),
* textureSpace: 'global'
* };
* ```
* @default 'local'
* @see {@link TextureSpace} For more details on texture spaces
*/
textureSpace?: TextureSpace;
}
/**
* A stroke attribute object that defines how lines and shape outlines are drawn.
* Controls properties like width, alignment, line caps, joins, and more.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic stroke with width
* graphics.stroke({
* width: 4,
* color: 0xff0000 // Or use a Color object
* });
*
* // Stroke with rounded corners and ends
* const text = new Text('Hello World', {
* fontSize: 32,
* fill: 0x000000, // Text color
* stroke: {
* width: 8,
* color: 0x00ff00, // Or use a Color object
* cap: 'round', // Round end caps
* join: 'round', // Round corner joins
* alignment: 0.5 // Center alignment
* }
* });
*
* // Stroke with mitered corners
* graphics.stroke({
* width: 6,
* color: 0x0000ff, // Or use a Color object
* join: 'miter',
* miterLimit: 3, // Limit how far miter extends
* alignment: 0 // Outside alignment
* });
*
* // Pixel-perfect line
* graphics.stroke({
* width: 1,
* pixelLine: true, // Ensures crisp 1px lines
* color: 0x000000 // Or use a Color object
* });
* ```
* @see {@link Graphics#stroke} For applying strokes to paths
* @see {@link LineCap} For line end cap options
* @see {@link LineJoin} For line join options
* @category scene
* @standard
*/
export interface StrokeAttributes {
/**
* The width of the stroke in pixels.
* @example
* ```ts
* const stroke = { width: 4 };
* ```
* @default 1
*/
width?: number;
/**
* The alignment of the stroke relative to the path.
* - 1: Inside the shape
* - 0.5: Centered on the path (default)
* - 0: Outside the shape
* @example
* ```ts
* // Inside alignment
* const stroke = { alignment: 1 };
* // Centered alignment
* const stroke = { alignment: 0.5 };
* // Outside alignment
* const stroke = { alignment: 0 };
* ```
* @default 0.5
*/
alignment?: number;
/**
* The style to use for the ends of open paths.
* - 'butt': Ends at path end
* - 'round': Rounds past path end
* - 'square': Squares past path end
* @example
* ```ts
* const stroke = { cap: 'round' };
* ```
* @default 'butt'
* @see {@link LineCap} For line cap options
*/
cap?: LineCap;
/**
* The style to use where paths connect.
* - 'miter': Sharp corner
* - 'round': Rounded corner
* - 'bevel': Beveled corner
* @example
* ```ts
* const stroke = { join: 'round' };
* ```
* @default 'miter'
* @see {@link LineJoin} For line join options
*/
join?: LineJoin;
/**
* Controls how far miter joins can extend. Only applies when join is 'miter'.
* Higher values allow sharper corners.
* @example
* ```ts
* const stroke = {
* join: 'miter',
* miterLimit: 3,
* };
* ```
* @default 10
*/
miterLimit?: number;
/**
* When true, ensures crisp 1px lines by aligning to pixel boundaries.
* > [!NOTE] Only available for Graphics fills.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw pixel-perfect line
* graphics
* .moveTo(50, 50)
* .lineTo(150, 50)
* .stroke({
* width: 1,
* pixelLine: true,
* color: 0x000000
* });
* ```
* @default false
*/
pixelLine?: boolean;
}
/**
* A stroke style object that combines fill properties with stroke attributes to define
* both the visual style and stroke behavior of lines, shape outlines, and text strokes.
* @example
* ```ts
* // --- Graphics Examples ---
* const graphics = new Graphics();
*
* // Basic solid color stroke
* graphics.stroke({
* width: 4,
* color: 0xff0000,
* alpha: 0.8,
* join: 'round'
* });
*
* // Gradient stroke with attributes
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* });
*
* graphics.stroke({
* width: 8,
* fill: gradient,
* cap: 'round',
* join: 'round',
* alignment: 0.5
* });
*
* // --- Text Examples ---
*
* // Basic text stroke
* const text = new Text('Hello World', {
* fontSize: 48,
* stroke: {
* width: 4,
* color: 0x000000,
* alignment: 0 // Outside stroke
* }
* });
*
* // Gradient text stroke
* const textGradient = new FillGradient({
* end: { x: 1, y: 0 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* });
*
* const fancyText = new Text('Gradient Outline', {
* fontSize: 64,
* fill: 0xffffff,
* stroke: {
* width: 6,
* fill: textGradient,
* alignment: 0.5,
* join: 'round'
* }
* });
* ```
* @see {@link FillStyle} For fill properties
* @see {@link StrokeAttributes} For stroke properties
* @see {@link Graphics#stroke} For applying strokes to paths
* @see {@link Text} For text stroke options
* @category scene
* @standard
* @interface
*/
export interface StrokeStyle extends FillStyle, StrokeAttributes {
}
/**
* These can be directly used as a fill or a stroke
* ```ts
* graphics.fill(0xff0000);
* graphics.fill(new FillPattern(texture));
* graphics.fill(new FillGradient(0, 0, 200, 0));
* graphics.fill({
* color: 0xff0000,
* alpha: 0.5,
* texture?: null,
* matrix?: null,
* });
* graphics.fill({
* fill: new FillPattern(texture),
* });
* graphics.fill({
* fill: new FillGradient(0, 0, 200, 0),
* });
* ```
* @category scene
* @standard
*/
export type FillInput = ColorSource | FillGradient | FillPattern | FillStyle | Texture;
/**
* These can be directly used as a stroke
* ```ts
* graphics.stroke(0xff0000);
* graphics.stroke(new FillPattern(texture));
* graphics.stroke(new FillGradient(0, 0, 200, 0));
* graphics.stroke({
* color: 0xff0000,
* width?: 1,
* alignment?: 0.5,
* });
* graphics.stroke({
* fill: new FillPattern(texture),
* width: 1,
* alignment: 0.5,
* });
* graphics.stroke({
* fill: new FillGradient(0, 0, 200, 0),
* width: 1,
* alignment: 0.5,
* });
* ```
* @category scene
* @standard
*/
export type StrokeInput = ColorSource | FillGradient | FillPattern | StrokeStyle;
/**
* used internally and is a complete fill style
* @category scene
* @advanced
* @interface
*/
export type ConvertedFillStyle = Omit<Required<FillStyle>, "color"> & {
color: number;
};
/**
* used internally and is a complete stroke style
* @category scene
* @advanced
* @interface
*/
export type ConvertedStrokeStyle = ConvertedFillStyle & Required<StrokeAttributes>;
/**
* @deprecated since v8.1.6
* @see FillInput
* @category scene
* @standard
*/
export type FillStyleInputs = ColorSource | FillGradient | FillPattern | FillStyle | ConvertedFillStyle | StrokeStyle | ConvertedStrokeStyle;
/**
* Typed and cleaned up version of:
* https://stackoverflow.com/questions/44855794/html5-canvas-triangle-with-rounded-corners/44856925#44856925
* @param g - Graphics to be drawn on.
* @param points - Corners of the shape to draw. Minimum length is 3.
* @param radius - Corners default radius.
* @ignore
*/
export declare function roundedShapeArc(g: ShapePath, points: RoundedPoint[], radius: number): void;
/**
* Data structure for points with optional radius.
* @category scene
* @standard
*/
export type RoundedPoint = PointData & {
radius?: number;
};
/**
* Typed and cleaned up version of:
* https://stackoverflow.com/questions/44855794/html5-canvas-triangle-with-rounded-corners/56214413#56214413
* @param g - Graphics to be drawn on.
* @param points - Corners of the shape to draw. Minimum length is 3.
* @param radius - Corners default radius.
* @ignore
*/
export declare function roundedShapeQuadraticCurve(g: ShapePath, points: RoundedPoint[], radius: number, smoothness?: number): void;
/**
* A type representing a shape primitive with optional transformation and holes.
* @category scene
* @advanced
*/
export type ShapePrimitiveWithHoles = {
shape: ShapePrimitive;
transform?: Matrix;
holes?: ShapePrimitiveWithHoles[];
};
/**
* The `ShapePath` class acts as a bridge between high-level drawing commands
* and the lower-level `GraphicsContext` rendering engine.
* It translates drawing commands, such as those for creating lines, arcs, ellipses, rectangles, and complex polygons, into a
* format that can be efficiently processed by a `GraphicsContext`. This includes handling path starts,
* ends, and transformations for shapes.
*
* It is used internally by `GraphicsPath` to build up the path.
* @category scene
* @advanced
*/
export declare class ShapePath {
/** The list of shape primitives that make up the path. */
shapePrimitives: ShapePrimitiveWithHoles[];
private _currentPoly;
private readonly _graphicsPath2D;
private readonly _bounds;
readonly signed: boolean;
constructor(graphicsPath2D: GraphicsPath);
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x: number, y: number): this;
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x: number, y: number): this;
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise: boolean): this;
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the control point.
* @param cp1y - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothing - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cp1x: number, cp1y: number, x: number, y: number, smoothing?: number): this;
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath(): this;
/**
* Adds another path to the current path. This method allows for the combination of multiple paths into one.
* @param path - The `GraphicsPath` object representing the path to add.
* @param transform - An optional `Matrix` object to apply a transformation to the path before adding it.
* @returns The instance of the current object for chaining.
*/
addPath(path: GraphicsPath, transform?: Matrix): this;
/**
* Finalizes the drawing of the current path. Optionally, it can close the path.
* @param closePath - A boolean indicating whether to close the path after finishing. False by default.
*/
finish(closePath?: boolean): void;
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x: number, y: number, w: number, h: number, transform?: Matrix): this;
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x: number, y: number, radius: number, transform?: Matrix): this;
/**
* Draws a polygon shape. This method allows for the creation of complex polygons by specifying a sequence of points.
* @param points - An array of numbers, or or an array of PointData objects eg [{x,y}, {x,y}, {x,y}]
* representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
poly(points: number[] | PointData[], close?: boolean, transform?: Matrix): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param smoothness - Optional parameter to adjust the smoothness of the rounding.
* @returns The instance of the current object for chaining.
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number, smoothness?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param transform - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number, transform?: Matrix): this;
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number, transform?: Matrix): this;
/**
* Draws a given shape on the canvas.
* This is a generic method that can draw any type of shape specified by the `ShapePrimitive` parameter.
* An optional transformation matrix can be applied to the shape, allowing for complex transformations.
* @param shape - The shape to draw, defined as a `ShapePrimitive` object.
* @param matrix - An optional `Matrix` for transforming the shape. This can include rotations,
* scaling, and translations.
* @returns The instance of the current object for chaining.
*/
drawShape(shape: ShapePrimitive, matrix?: Matrix): this;
/**
* Starts a new polygon path from the specified starting point.
* This method initializes a new polygon or ends the current one if it exists.
* @param x - The x-coordinate of the starting point of the new polygon.
* @param y - The y-coordinate of the starting point of the new polygon.
* @returns The instance of the current object for chaining.
*/
startPoly(x: number, y: number): this;
/**
* Ends the current polygon path. If `closePath` is set to true,
* the path is closed by connecting the last point to the first one.
* This method finalizes the current polygon and prepares it for drawing or adding to the shape primitives.
* @param closePath - A boolean indicating whether to close the polygon by connecting the last point
* back to the starting point. False by default.
* @returns The instance of the current object for chaining.
*/
endPoly(closePath?: boolean): this;
private _ensurePoly;
/** Builds the path. */
buildPath(): void;
/** Gets the bounds of the path. */
get bounds(): Bounds;
}
/**
* Represents a single drawing instruction in a `GraphicsPath`.
* Each instruction consists of an action type and associated data.
* @category scene
* @advanced
*/
export interface PathInstruction {
action: "moveTo" | "lineTo" | "quadraticCurveTo" | "bezierCurveTo" | "arc" | "closePath" | "addPath" | "arcTo" | "ellipse" | "rect" | "roundRect" | "arcToSvg" | "poly" | "circle" | "regularPoly" | "roundPoly" | "roundShape" | "filletRect" | "chamferRect";
data: any[];
}
/**
* The `GraphicsPath` class is designed to represent a graphical path consisting of multiple drawing instructions.
* This class serves as a collection of drawing commands that can be executed to render shapes and paths on a canvas or
* similar graphical context. It supports high-level drawing operations like lines, arcs, curves, and more, enabling
* complex graphic constructions with relative ease.
* @category scene
* @advanced
*/
export declare class GraphicsPath {
instructions: PathInstruction[];
/** unique id for this graphics path */
readonly uid: number;
private _dirty;
private _shapePath;
/**
* Controls whether shapes in this path should be checked for holes using the non-zero fill rule.
* When true, any closed shape that is fully contained within another shape will become
* a hole in that shape during filling operations.
*
* This follows SVG's non-zero fill rule where:
* 1. Shapes are analyzed to find containment relationships
* 2. If Shape B is fully contained within Shape A, Shape B becomes a hole in Shape A
* 3. Multiple nested holes are supported
*
* Mainly used internally by the SVG parser to correctly handle holes in complex paths.
* When false, all shapes are filled independently without checking for holes.
*/
checkForHoles: boolean;
/**
* Provides access to the internal shape path, ensuring it is up-to-date with the current instructions.
* @returns The `ShapePath` instance associated with this `GraphicsPath`.
*/
get shapePath(): ShapePath;
/**
* Creates a `GraphicsPath` instance optionally from an SVG path string or an array of `PathInstruction`.
* @param instructions - An SVG path string or an array of `PathInstruction` objects.
* @param signed
*/
constructor(instructions?: string | PathInstruction[], signed?: boolean);
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* @param path - The `GraphicsPath` to add.
* @param transform - An optional transformation to apply to the added path.
* @returns The instance of the current object for chaining.
*/
addPath(path: GraphicsPath, transform?: Matrix): this;
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): this;
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires two points: the second control point and the end point. The first control point is assumed to be
* The starting point is the last point in the current path.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveToShort(cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath(): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param matrix - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number, matrix?: Matrix): this;
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x: number, y: number): this;
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x: number, y: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cpx - The x-coordinate of the control point.
* @param cpy - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a quadratic curve to the path. It uses the previous point as the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveToShort(x: number, y: number, smoothness?: number): this;
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x: number, y: number, w: number, h: number, transform?: Matrix): this;
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x: number, y: number, radius: number, transform?: Matrix): this;
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number, transform?: Matrix): this;
/**
* Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons,
* which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled,
* rotated, or translated as needed.
* @param points - An array of numbers representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining further drawing commands.
*/
poly(points: number[] | PointData[], close?: boolean, transform?: Matrix): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @returns The instance of the current object for chaining.
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @param x - The x-coordinate of the center of the star.
* @param y - The y-coordinate of the center of the star.
* @param points - The number of points of the star.
* @param radius - The outer radius of the star (distance from the center to the outer points).
* @param innerRadius - Optional. The inner radius of the star
* (distance from the center to the inner points between the outer points).
* If not provided, defaults to half of the `radius`.
* @param rotation - Optional. The rotation of the star in radians, where 0 is aligned with the y-axis.
* Defaults to 0, meaning one point is directly upward.
* @param transform - An optional `Matrix` object to apply a transformation to the star.
* This can include rotations, scaling, and translations.
* @returns The instance of the current object for chaining further drawing commands.
*/
star(x: number, y: number, points: number, radius: number, innerRadius?: number, rotation?: number, transform?: Matrix): this;
/**
* Creates a copy of the current `GraphicsPath` instance. This method supports both shallow and deep cloning.
* A shallow clone copies the reference of the instructions array, while a deep clone creates a new array and
* copies each instruction individually, ensuring that modifications to the instructions of the cloned `GraphicsPath`
* do not affect the original `GraphicsPath` and vice versa.
* @param deep - A boolean flag indicating whether the clone should be deep.
* @returns A new `GraphicsPath` instance that is a clone of the current instance.
*/
clone(deep?: boolean): GraphicsPath;
clear(): this;
/**
* Applies a transformation matrix to all drawing instructions within the `GraphicsPath`.
* This method enables the modification of the path's geometry according to the provided
* transformation matrix, which can include translations, rotations, scaling, and skewing.
*
* Each drawing instruction in the path is updated to reflect the transformation,
* ensuring the visual representation of the path is consistent with the applied matrix.
*
* Note: The transformation is applied directly to the coordinates and control points of the drawing instructions,
* not to the path as a whole. This means the transformation's effects are baked into the individual instructions,
* allowing for fine-grained control over the path's appearance.
* @param matrix - A `Matrix` object representing the transformation to apply.
* @returns The instance of the current object for chaining further operations.
*/
transform(matrix: Matrix): this;
get bounds(): Bounds;
/**
* Retrieves the last point from the current drawing instructions in the `GraphicsPath`.
* This method is useful for operations that depend on the path's current endpoint,
* such as connecting subsequent shapes or paths. It supports various drawing instructions,
* ensuring the last point's position is accurately determined regardless of the path's complexity.
*
* If the last instruction is a `closePath`, the method iterates backward through the instructions
* until it finds an actionable instruction that defines a point (e.g., `moveTo`, `lineTo`,
* `quadraticCurveTo`, etc.). For compound paths added via `addPath`, it recursively retrieves
* the last point from the nested path.
* @param out - A `Point` object where the last point's coordinates will be stored.
* This object is modified directly to contain the result.
* @returns The `Point` object containing the last point's coordinates.
*/
getLastPoint(out: Point): Point;
}
/**
* Constructor options used for Graphics instances.
* Configures the initial state and behavior of a Graphics object.
* @example
* ```ts
* const graphics = new Graphics({
* roundPixels: true,
* position: { x: 100.5, y: 100.5 }
* });
*
* // Reuse graphics context
* const sharedContext = new GraphicsContext();
* const graphics1 = new Graphics({ context: sharedContext });
* const graphics2 = new Graphics({ context: sharedContext });
* ```
* @see {@link Graphics} For the graphics class implementation
* @see {@link GraphicsContext} For the graphics context API
* @category scene
* @standard
*/
export interface GraphicsOptions extends PixiMixins.GraphicsOptions, ViewContainerOptions {
/**
* The GraphicsContext to use, useful for reuse and optimisation
* If not provided, a new GraphicsContext will be created.
* @example
* ```ts
* const sharedContext = new GraphicsContext();
* const graphics1 = new Graphics({ context: sharedContext });
* const graphics2 = new Graphics({ context: sharedContext });
* ```
*/
context?: GraphicsContext;
/**
* Whether or not to round the x/y position.
* @default false
* @example
* ```ts
* const graphics = new Graphics({ roundPixels: true });
* ```
*/
roundPixels?: boolean;
}
export interface Graphics extends PixiMixins.Graphics, ViewContainer<GraphicsGpuData> {
}
/**
* The Graphics class is primarily used to render primitive shapes such as lines, circles and
* rectangles to the display, and to color and fill them. It can also be used to create complex
* masks and hit areas for interaction.
* @example
* ```ts
* // Create a new graphics object
* const graphics = new Graphics();
*
* // Draw a filled rectangle with a stroke
* graphics
* .rect(0, 0, 100, 100)
* .fill({ color: 0xff0000 }) // Fill with red
* .stroke({ width: 2, color: 0x000000 }); // Stroke with black
*
* // Draw a complex shape
* graphics
* .moveTo(50, 50)
* .lineTo(100, 100)
* .arc(100, 100, 50, 0, Math.PI)
* .closePath()
* .fill({ color: 0x00ff00, alpha: 0.5 }); // Fill the shape
*
* // Use as a mask
* sprite.mask = graphics;
* ```
* @see {@link GraphicsContext} For the underlying drawing API
* @see {@link GraphicsPath} For path creation
* @category scene
* @standard
*/
export declare class Graphics extends ViewContainer<GraphicsGpuData> implements Instruction {
/** @internal */
readonly renderPipeId: string;
/** @internal */
batched: boolean;
private _context;
private readonly _ownedContext;
/**
* Creates a new Graphics object.
* @param options - Options for the Graphics.
*/
constructor(options?: GraphicsOptions | GraphicsContext);
set context(context: GraphicsContext);
/**
* The underlying graphics context used for drawing operations.
* Controls how shapes and paths are rendered.
* @example
* ```ts
* // Create a shared context
* const sharedContext = new GraphicsContext();
*
* // Create graphics objects sharing the same context
* const graphics1 = new Graphics();
* const graphics2 = new Graphics();
*
* // Assign shared context
* graphics1.context = sharedContext;
* graphics2.context = sharedContext;
*
* // Both graphics will show the same shapes
* sharedContext
* .rect(0, 0, 100, 100)
* .fill({ color: 0xff0000 });
* ```
* @see {@link GraphicsContext} For drawing operations
* @see {@link GraphicsOptions} For context configuration
*/
get context(): GraphicsContext;
/**
* The local bounds of the graphics object.
* Returns the boundaries after all graphical operations but before any transforms.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a shape
* graphics
* .rect(0, 0, 100, 100)
* .fill({ color: 0xff0000 });
*
* // Get bounds information
* const bounds = graphics.bounds;
* console.log(bounds.width); // 100
* console.log(bounds.height); // 100
* ```
* @readonly
* @see {@link Bounds} For bounds operations
* @see {@link Container#getBounds} For transformed bounds
*/
get bounds(): Bounds;
/**
* Graphics objects do not need to update their bounds as the context handles this.
* @private
*/
protected updateBounds(): void;
/**
* Checks if the object contains the given point.
* Returns true if the point lies within the Graphics object's rendered area.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a shape
* graphics
* .rect(0, 0, 100, 100)
* .fill({ color: 0xff0000 });
*
* // Check point intersection
* if (graphics.containsPoint({ x: 50, y: 50 })) {
* console.log('Point is inside rectangle!');
* }
* ```
* @param point - The point to check in local coordinates
* @returns True if the point is inside the Graphics object
* @see {@link Graphics#bounds} For bounding box checks
* @see {@link PointData} For point data structure
*/
containsPoint(point: PointData): boolean;
/**
* Destroys this graphics renderable and optionally its context.
* @param options - Options parameter. A boolean will act as if all options
*
* If the context was created by this graphics and `destroy(false)` or `destroy()` is called
* then the context will still be destroyed.
*
* If you want to explicitly not destroy this context that this graphics created,
* then you should pass destroy({ context: false })
*
* If the context was passed in as an argument to the constructor then it will not be destroyed
* @example
* ```ts
* // Destroy the graphics and its context
* graphics.destroy();
* graphics.destroy(true);
* graphics.destroy({ context: true, texture: true, textureSource: true });
* ```
*/
destroy(options?: DestroyOptions): void;
/**
* @param now - The current time in milliseconds.
* @internal
*/
_onTouch(now: number): void;
private _callContextMethod;
/**
* Sets the current fill style of the graphics context.
* The fill style can be a color, gradient, pattern, or a complex style object.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic color fill
* graphics
* .setFillStyle({ color: 0xff0000 }) // Red fill
* .rect(0, 0, 100, 100)
* .fill();
*
* // Gradient fill
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 }, // Red at start
* { offset: 0.5, color: 0x00ff00 }, // Green at middle
* { offset: 1, color: 0x0000ff }, // Blue at end
* ],
* });
*
* graphics
* .setFillStyle(gradient)
* .circle(100, 100, 50)
* .fill();
*
* // Pattern fill
* const pattern = new FillPattern(texture);
* graphics
* .setFillStyle({
* fill: pattern,
* alpha: 0.5
* })
* .rect(0, 0, 200, 200)
* .fill();
* ```
* @param {FillInput} args - The fill style to apply
* @returns The Graphics instance for chaining
* @see {@link FillStyle} For fill style options
* @see {@link FillGradient} For gradient fills
* @see {@link FillPattern} For pattern fills
*/
setFillStyle(...args: Parameters<GraphicsContext["setFillStyle"]>): this;
/**
* Sets the current stroke style of the graphics context.
* Similar to fill styles, stroke styles can encompass colors, gradients, patterns, or more detailed configurations.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic color stroke
* graphics
* .setStrokeStyle({
* width: 2,
* color: 0x000000
* })
* .rect(0, 0, 100, 100)
* .stroke();
*
* // Complex stroke style
* graphics
* .setStrokeStyle({
* width: 4,
* color: 0xff0000,
* alpha: 0.5,
* join: 'round',
* cap: 'round',
* alignment: 0.5
* })
* .circle(100, 100, 50)
* .stroke();
*
* // Gradient stroke
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 }, // Red at start
* { offset: 0.5, color: 0x00ff00 }, // Green at middle
* { offset: 1, color: 0x0000ff }, // Blue at end
* ],
* });
*
* graphics
* .setStrokeStyle({
* width: 10,
* fill: gradient
* })
* .poly([0,0, 100,50, 0,100])
* .stroke();
* ```
* @param {StrokeInput} args - The stroke style to apply
* @returns The Graphics instance for chaining
* @see {@link StrokeStyle} For stroke style options
* @see {@link FillGradient} For gradient strokes
* @see {@link FillPattern} For pattern strokes
*/
setStrokeStyle(...args: Parameters<GraphicsContext["setStrokeStyle"]>): this;
/**
* Fills the current or given path with the current fill style or specified style.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Fill with direct color
* graphics
* .circle(50, 50, 25)
* .fill('red'); // Red fill
*
* // Fill with texture
* graphics
* .rect(0, 0, 100, 100)
* .fill(myTexture); // Fill with texture
*
* // Fill with complex style
* graphics
* .rect(0, 0, 100, 100)
* .fill({
* color: 0x00ff00,
* alpha: 0.5,
* texture: myTexture,
* matrix: new Matrix()
* });
*
* // Fill with gradient
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 },
* { offset: 0.5, color: 0x00ff00 },
* { offset: 1, color: 0x0000ff },
* ],
* });
*
* graphics
* .circle(100, 100, 50)
* .fill(gradient);
* ```
* @param {FillInput} style - The style to fill the path with. Can be:
* - A ColorSource
* - A gradient
* - A pattern
* - A complex style object
* If omitted, uses current fill style.
* @returns The Graphics instance for chaining
* @see {@link FillStyle} For fill style options
* @see {@link FillGradient} For gradient fills
* @see {@link FillPattern} For pattern fills
*/
fill(style?: FillInput): this;
/** @deprecated 8.0.0 */
fill(color: ColorSource, alpha?: number): this;
/**
* Strokes the current path with the current stroke style or specified style.
* Outlines the shape using the stroke settings.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Stroke with direct color
* graphics
* .circle(50, 50, 25)
* .stroke({
* width: 2,
* color: 0xff0000
* }); // 2px red stroke
*
* // Fill with texture
* graphics
* .rect(0, 0, 100, 100)
* .stroke(myTexture); // Fill with texture
*
* // Stroke with gradient
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 },
* { offset: 0.5, color: 0x00ff00 },
* { offset: 1, color: 0x0000ff },
* ],
* });
*
* graphics
* .rect(0, 0, 100, 100)
* .stroke({
* width: 4,
* fill: gradient,
* alignment: 0.5,
* join: 'round'
* });
* ```
* @param {StrokeStyle} args - Optional stroke style to apply. Can be:
* - A stroke style object with width, color, etc.
* - A gradient
* - A pattern
* If omitted, uses current stroke style.
* @returns The Graphics instance for chaining
* @see {@link StrokeStyle} For stroke style options
* @see {@link FillGradient} For gradient strokes
* @see {@link setStrokeStyle} For setting default stroke style
*/
stroke(...args: Parameters<GraphicsContext["stroke"]>): this;
/**
* Adds a texture to the graphics context. This method supports multiple ways to draw textures
* including basic textures, tinted textures, and textures with custom dimensions.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic texture drawing
* graphics.texture(myTexture);
*
* // Tinted texture with position
* graphics.texture(myTexture, 0xff0000); // Red tint
*
* // Texture with custom position and dimensions
* graphics
* .texture(
* myTexture, // texture
* 0xffffff, // white tint
* 100, 100, // position
* 200, 150 // dimensions
* );
* ```
* Basic texture drawing:
* @param texture - The Texture object to use.
* @returns The instance of the current Graphics for chaining.
*
* Extended texture drawing:
* @param texture - The Texture object to use.
* tint - A ColorSource to tint the texture (defaults to white).
* dx - The x-coordinate for the texture placement.
* dy - The y-coordinate for the texture placement.
* dw - The width to draw the texture (defaults to texture width).
* dh - The height to draw the texture (defaults to texture height).
* @returns The instance of the current Graphics for chaining.
* @see {@link Texture} For texture creation
* @see {@link FillPattern} For pattern fills
*/
texture(texture: Texture): this;
texture(texture: Texture, tint?: ColorSource, dx?: number, dy?: number, dw?: number, dh?: number): this;
/**
* Resets the current path. Any previous path and its commands are discarded and a new path is
* started. This is typically called before beginning a new shape or series of drawing commands.
* @example
* ```ts
* const graphics = new Graphics();
* graphics
* .circle(150, 150, 50)
* .fill({ color: 0x00ff00 })
* .beginPath() // Starts a new path
* .circle(250, 150, 50)
* .fill({ color: 0x0000ff });
* ```
* @returns The Graphics instance for chaining
* @see {@link Graphics#moveTo} For starting a new subpath
* @see {@link Graphics#closePath} For closing the current path
*/
beginPath(): this;
/**
* Applies a cutout to the last drawn shape. This is used to create holes or complex shapes by
* subtracting a path from the previously drawn path.
*
* If a hole is not completely in a shape, it will fail to cut correctly.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw outer circle
* graphics
* .circle(100, 100, 50)
* .fill({ color: 0xff0000 });
* .circle(100, 100, 25) // Inner circle
* .cut() // Cuts out the inner circle from the outer circle
* ```
*/
cut(): this;
/**
* Adds an arc to the current path, which is centered at (x, y) with the specified radius,
* starting and ending angles, and direction.
* @example
* ```ts
* // Draw a simple arc (quarter circle)
* const graphics = new Graphics();
* graphics
* .arc(100, 100, 50, 0, Math.PI/2)
* .stroke({ width: 2, color: 0xff0000 });
*
* // Draw a full circle using an arc
* graphics
* .arc(200, 200, 30, 0, Math.PI * 2)
* .stroke({ color: 0x00ff00 });
*
* // Draw a counterclockwise arc
* graphics
* .arc(150, 150, 40, Math.PI, 0, true)
* .stroke({ width: 2, color: 0x0000ff });
* ```
* @param x - The x-coordinate of the arc's center
* @param y - The y-coordinate of the arc's center
* @param radius - The arc's radius (must be positive)
* @param startAngle - The starting point of the arc, in radians
* @param endAngle - The end point of the arc, in radians
* @param counterclockwise - Optional. If true, draws the arc counterclockwise.
* If false (default), draws clockwise.
* @returns The Graphics instance for method chaining
* @see {@link Graphics#circle} For drawing complete circles
* @see {@link Graphics#arcTo} For drawing arcs between points
* @see {@link Graphics#arcToSvg} For SVG-style arc drawing
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): this;
/**
* Adds an arc to the current path that connects two points using a radius.
* The arc is drawn between the current point and the specified end point,
* using the given control point to determine the curve of the arc.
* @example
* ```ts
* // Draw a simple curved corner
* const graphics = new Graphics();
* graphics
* .moveTo(50, 50)
* .arcTo(100, 50, 100, 100, 20) // Rounded corner with 20px radius
* .stroke({ width: 2, color: 0xff0000 });
*
* // Create a rounded rectangle using arcTo
* graphics
* .moveTo(150, 150)
* .arcTo(250, 150, 250, 250, 30) // Top right corner
* .arcTo(250, 250, 150, 250, 30) // Bottom right corner
* .arcTo(150, 250, 150, 150, 30) // Bottom left corner
* .arcTo(150, 150, 250, 150, 30) // Top left corner
* .fill({ color: 0x00ff00 });
* ```
* @param x1 - The x-coordinate of the control point
* @param y1 - The y-coordinate of the control point
* @param x2 - The x-coordinate of the end point
* @param y2 - The y-coordinate of the end point
* @param radius - The radius of the arc in pixels (must be positive)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#arc} For drawing arcs using center point and angles
* @see {@link Graphics#arcToSvg} For SVG-style arc drawing
* @see {@link Graphics#roundRect} For drawing rectangles with rounded corners
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* This is particularly useful when converting SVG paths to Graphics or creating complex curved shapes.
* @example
* ```ts
* // Draw a simple elliptical arc
* const graphics = new Graphics();
* graphics
* .moveTo(100, 100)
* .arcToSvg(50, 30, 0, 0, 1, 200, 100)
* .stroke({ width: 2, color: 0xff0000 });
*
* // Create a complex path with rotated elliptical arc
* graphics
* .moveTo(150, 150)
* .arcToSvg(
* 60, // rx
* 30, // ry
* 45, // x-axis rotation (45 degrees)
* 1, // large arc flag
* 0, // sweep flag
* 250, // end x
* 200 // end y
* )
* .stroke({ width: 4, color: 0x00ff00 });
*
* // Chain multiple arcs for complex shapes
* graphics
* .moveTo(300, 100)
* .arcToSvg(40, 20, 0, 0, 1, 350, 150)
* .arcToSvg(40, 20, 0, 0, 1, 300, 200)
* .fill({ color: 0x0000ff, alpha: 0.5 });
* ```
* @param rx - The x-radius of the ellipse (must be non-negative)
* @param ry - The y-radius of the ellipse (must be non-negative)
* @param xAxisRotation - The rotation of the ellipse's x-axis relative to the x-axis, in degrees
* @param largeArcFlag - Either 0 or 1, determines if the larger of the two possible arcs is chosen (1) or not (0)
* @param sweepFlag - Either 0 or 1, determines if the arc should be swept in
* a positive angle direction (1) or negative (0)
* @param x - The x-coordinate of the arc's end point
* @param y - The y-coordinate of the arc's end point
* @returns The Graphics instance for method chaining
* @see {@link Graphics#arc} For simple circular arcs
* @see {@link Graphics#arcTo} For connecting points with circular arcs
* @see {@link Graphics#svg} For parsing complete SVG paths
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bézier curve to the path, from the current point to the specified end point.
* The curve is influenced by two control points that define its shape and curvature.
* @example
* ```ts
* // Draw a simple curved line
* const graphics = new Graphics();
* graphics
* .moveTo(50, 50)
* .bezierCurveTo(
* 100, 25, // First control point
* 150, 75, // Second control point
* 200, 50 // End point
* )
* .stroke({ width: 2, color: 0xff0000 });
*
* // Adjust curve smoothness
* graphics
* .moveTo(50, 200)
* .bezierCurveTo(
* 100, 150,
* 200, 250,
* 250, 200,
* 0.5 // Smoothness factor
* )
* .stroke({ width: 4, color: 0x0000ff });
* ```
* @param cp1x - The x-coordinate of the first control point
* @param cp1y - The y-coordinate of the first control point
* @param cp2x - The x-coordinate of the second control point
* @param cp2y - The y-coordinate of the second control point
* @param x - The x-coordinate of the end point
* @param y - The y-coordinate of the end point
* @param smoothness - Optional parameter to adjust the curve's smoothness (0-1)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#quadraticCurveTo} For simpler curves with one control point
* @see {@link Graphics#arc} For circular arcs
* @see {@link Graphics#arcTo} For connecting points with circular arcs
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Closes the current path by drawing a straight line back to the start point.
*
* This is useful for completing shapes and ensuring they are properly closed for fills.
* @example
* ```ts
* // Create a triangle with closed path
* const graphics = new Graphics();
* graphics
* .moveTo(50, 50)
* .lineTo(100, 100)
* .lineTo(0, 100)
* .closePath()
* ```
* @returns The Graphics instance for method chaining
* @see {@link Graphics#beginPath} For starting a new path
* @see {@link Graphics#fill} For filling closed paths
* @see {@link Graphics#stroke} For stroking paths
*/
closePath(): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a basic ellipse
* graphics
* .ellipse(100, 100, 50, 30)
* .fill({ color: 0xff0000 });
*
* // Draw an ellipse with stroke
* graphics
* .ellipse(200, 100, 70, 40)
* .stroke({ width: 2, color: 0x00ff00 });
* ```
* @param x - The x-coordinate of the center of the ellipse
* @param y - The y-coordinate of the center of the ellipse
* @param radiusX - The horizontal radius of the ellipse
* @param radiusY - The vertical radius of the ellipse
* @returns The Graphics instance for method chaining
* @see {@link Graphics#circle} For drawing perfect circles
* @see {@link Graphics#arc} For drawing partial circular arcs
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number): this;
/**
* Draws a circle shape at the specified location with the given radius.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a simple filled circle
* graphics
* .circle(100, 100, 50)
* .fill({ color: 0xff0000 });
*
* // Draw a circle with gradient fill
* const gradient = new FillGradient({
* end: { x: 1, y: 0 },
* colorStops: [
* { offset: 0, color: 0xff0000 }, // Red at start
* { offset: 0.5, color: 0x00ff00 }, // Green at middle
* { offset: 1, color: 0x0000ff }, // Blue at end
* ],
* });
*
* graphics
* .circle(250, 100, 40)
* .fill({ fill: gradient });
* ```
* @param x - The x-coordinate of the center of the circle
* @param y - The y-coordinate of the center of the circle
* @param radius - The radius of the circle
* @returns The Graphics instance for method chaining
* @see {@link Graphics#ellipse} For drawing ellipses
* @see {@link Graphics#arc} For drawing partial circles
*/
circle(x: number, y: number, radius: number): this;
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* This allows for reuse of complex paths and shapes across different graphics instances.
* @example
* ```ts
* const graphics = new Graphics();
* // Create a reusable path
* const heartPath = new GraphicsPath()
* .moveTo(0, 0)
* .bezierCurveTo(-50, -25, -50, -75, 0, -100)
* .bezierCurveTo(50, -75, 50, -25, 0, 0);
*
* // Use the path multiple times
* graphics
* .path(heartPath)
* .fill({ color: 0xff0000 })
* .translateTransform(200, 200)
* .path(heartPath)
* .fill({ color: 0xff0000, alpha: 0.5 });
* ```
* @param path - The `GraphicsPath` to add to the current path
* @returns The Graphics instance for method chaining
* @see {@link GraphicsPath} For creating reusable paths
* @see {@link Matrix} For creating transformations
* @see {@link Graphics#transform} For applying transformations
*/
path(path: GraphicsPath): this;
/**
* Connects the current point to a new point with a straight line.
* Any subsequent drawing commands will start from this new point.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a triangle
* graphics
* .moveTo(50, 50)
* .lineTo(100, 100)
* .lineTo(0, 100)
* .fill({ color: 0xff0000 });
*
* // Create a complex shape with multiple lines
* graphics
* .moveTo(200, 50)
* .lineTo(250, 50)
* .lineTo(250, 100)
* .lineTo(200, 100)
* .stroke({ width: 2, color: 0x00ff00 });
* ```
* @param x - The x-coordinate of the line's end point
* @param y - The y-coordinate of the line's end point
* @returns The Graphics instance for method chaining
* @see {@link Graphics#moveTo} For starting a new sub-path
*/
lineTo(x: number, y: number): this;
/**
* Sets the starting point for a new sub-path.
*
* Moves the "pen" to a new location without drawing a line.
* Any subsequent drawing commands will start from this point.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Create multiple separate lines
* graphics
* .moveTo(50, 50)
* .lineTo(100, 50)
* .moveTo(50, 100) // Start a new line
* .lineTo(100, 100)
* .stroke({ width: 2, color: 0xff0000 });
*
* // Create disconnected shapes
* graphics
* .moveTo(150, 50)
* .rect(150, 50, 50, 50)
* .fill({ color: 0x00ff00 })
* .moveTo(250, 50) // Start a new shape
* .circle(250, 75, 25)
* .fill({ color: 0x0000ff });
*
* // Position before curved paths
* graphics
* .moveTo(300, 50)
* .bezierCurveTo(
* 350, 25, // Control point 1
* 400, 75, // Control point 2
* 450, 50 // End point
* )
* .stroke({ width: 3, color: 0xff00ff });
* ```
* @param x - The x-coordinate to move to
* @param y - The y-coordinate to move to
* @returns The Graphics instance for method chaining
* @see {@link Graphics#lineTo} For drawing lines
* @see {@link Graphics#beginPath} For starting a completely new path
*/
moveTo(x: number, y: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a simple curve
* graphics
* .moveTo(50, 50)
* .quadraticCurveTo(100, 25, 150, 50)
* .stroke({ width: 2, color: 0xff0000 });
*
* // Adjust curve smoothness
* graphics
* .moveTo(50, 200)
* .quadraticCurveTo(
* 150, 150, // Control point
* 250, 200, // End point
* 0.5 // Smoothness factor
* )
* .stroke({
* width: 4,
* color: 0x0000ff,
* alpha: 0.7
* });
* ```
* @param cpx - The x-coordinate of the control point
* @param cpy - The y-coordinate of the control point
* @param x - The x-coordinate of the end point
* @param y - The y-coordinate of the end point
* @param smoothness - Optional parameter to adjust the curve's smoothness (0-1)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#bezierCurveTo} For curves with two control points
* @see {@link Graphics#arc} For circular arcs
* @see {@link Graphics#arcTo} For connecting points with circular arcs
*/
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number, smoothness?: number): this;
/**
* Draws a rectangle shape.
*
* This method adds a new rectangle path to the current drawing.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a simple filled rectangle
* graphics
* .rect(50, 50, 100, 75)
* .fill({ color: 0xff0000 });
*
* // Rectangle with stroke
* graphics
* .rect(200, 50, 100, 75)
* .stroke({ width: 2, color: 0x00ff00 });
* ```
* @param x - The x-coordinate of the top-left corner of the rectangle
* @param y - The y-coordinate of the top-left corner of the rectangle
* @param w - The width of the rectangle
* @param h - The height of the rectangle
* @returns The Graphics instance for method chaining
* @see {@link Graphics#roundRect} For drawing rectangles with rounded corners
* @see {@link Graphics#filletRect} For drawing rectangles with filleted corners
* @see {@link Graphics#chamferRect} For drawing rectangles with chamfered corners
*/
rect(x: number, y: number, w: number, h: number): this;
/**
* Draws a rectangle with rounded corners. The corner radius can be specified to
* determine how rounded the corners should be.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic rounded rectangle
* graphics
* .roundRect(50, 50, 100, 75, 15)
* .fill({ color: 0xff0000 });
* ```
* @param x - The x-coordinate of the top-left corner of the rectangle
* @param y - The y-coordinate of the top-left corner of the rectangle
* @param w - The width of the rectangle
* @param h - The height of the rectangle
* @param radius - The radius of the rectangle's corners (must be non-negative)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#rect} For drawing rectangles with sharp corners
* @see {@link Graphics#filletRect} For drawing rectangles with filleted corners
* @see {@link Graphics#chamferRect} For drawing rectangles with chamfered corners
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number): this;
/**
* Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons,
* which can be both open and closed.
*
* An optional transformation can be applied, enabling the polygon to be scaled,
* rotated, or translated as needed.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a triangle using array of numbers [x1,y1, x2,y2, x3,y3]
* graphics
* .poly([50,50, 100,100, 0,100], true)
* .fill({ color: 0xff0000 });
*
* // Draw a polygon using point objects
* graphics
* .poly([
* { x: 200, y: 50 },
* { x: 250, y: 100 },
* { x: 200, y: 150 },
* { x: 150, y: 100 }
* ])
* .fill({ color: 0x00ff00 });
*
* // Draw an open polygon with stroke
* graphics
* .poly([300,50, 350,50, 350,100, 300,100], false)
* .stroke({
* width: 2,
* color: 0x0000ff,
* join: 'round'
* });
* ```
* @param points - An array of numbers [x1,y1, x2,y2, ...] or an array of point objects [{x,y}, ...]
* representing the vertices of the polygon in sequence
* @param close - Whether to close the polygon path by connecting the last point to the first.
* Default is true.
* @returns The Graphics instance for method chaining
* @see {@link Graphics#regularPoly} For drawing regular polygons
* @see {@link Graphics#roundPoly} For drawing polygons with rounded corners
* @see {@link Graphics#star} For drawing star shapes
*/
poly(points: number[] | PointData[], close?: boolean): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal,
* making shapes like triangles, squares, pentagons, etc.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a simple triangle (3 sides)
* graphics
* .regularPoly(100, 100, 50, 3)
* .fill({ color: 0xff0000 });
*
* // Draw a hexagon (6 sides) with rotation
* graphics
* .regularPoly(
* 250, 100, // center position
* 40, // radius
* 6, // sides
* Math.PI / 6 // rotation (30 degrees)
* )
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
*
* // Draw an octagon (8 sides) with transform
* const transform = new Matrix()
* .scale(1.5, 1) // stretch horizontally
* .rotate(Math.PI/4); // rotate 45 degrees
*
* graphics
* .regularPoly(400, 100, 30, 8, 0, transform)
* .fill({ color: 0x0000ff, alpha: 0.5 });
* ```
* @param x - The x-coordinate of the center of the polygon
* @param y - The y-coordinate of the center of the polygon
* @param radius - The radius of the circumscribed circle of the polygon
* @param sides - The number of sides of the polygon (must be 3 or more)
* @param rotation - The rotation angle of the polygon in radians (default: 0)
* @param transform - Optional Matrix to transform the polygon's shape
* @returns The Graphics instance for method chaining
* @see {@link Graphics#poly} For drawing custom polygons
* @see {@link Graphics#roundPoly} For drawing polygons with rounded corners
* @see {@link Graphics#star} For drawing star shapes
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
*
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a basic rounded triangle
* graphics
* .roundPoly(100, 100, 50, 3, 10)
* .fill({ color: 0xff0000 });
*
* // Draw a rounded hexagon with rotation
* graphics
* .roundPoly(
* 250, 150, // center position
* 40, // radius
* 6, // sides
* 8, // corner radius
* Math.PI / 6 // rotation (30 degrees)
* )
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
* ```
* @param x - The x-coordinate of the center of the polygon
* @param y - The y-coordinate of the center of the polygon
* @param radius - The radius of the circumscribed circle of the polygon
* @param sides - The number of sides of the polygon (must be 3 or more)
* @param corner - The radius of the corner rounding (must be non-negative)
* @param rotation - The rotation angle of the polygon in radians (default: 0)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#regularPoly} For drawing polygons without rounded corners
* @see {@link Graphics#poly} For drawing custom polygons
* @see {@link Graphics#roundRect} For drawing rectangles with rounded corners
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a custom shape with rounded corners
* graphics
* .roundShape([
* { x: 100, y: 100, radius: 20 },
* { x: 200, y: 100, radius: 10 },
* { x: 200, y: 200, radius: 15 },
* { x: 100, y: 200, radius: 5 }
* ], 10)
* .fill({ color: 0xff0000 });
*
* // Using quadratic curves for corners
* graphics
* .roundShape([
* { x: 250, y: 100 },
* { x: 350, y: 100 },
* { x: 350, y: 200 },
* { x: 250, y: 200 }
* ], 15, true, 0.5)
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
*
* // Shape with varying corner radii
* graphics
* .roundShape([
* { x: 400, y: 100, radius: 30 },
* { x: 500, y: 100, radius: 5 },
* { x: 450, y: 200, radius: 15 }
* ], 10)
* .fill({ color: 0x0000ff, alpha: 0.5 });
* ```
* @param points - An array of `RoundedPoint` representing the corners of the shape.
* Each point can have its own radius or use the default.
* A minimum of 3 points is required.
* @param radius - The default radius for corners without a specific radius defined.
* Applied to any point that doesn't specify its own radius.
* @param useQuadratic - When true, corners are drawn using quadratic curves instead
* of arcs, creating a different visual style. Defaults to false.
* @param smoothness - Controls the smoothness of quadratic corners when useQuadratic
* is true. Values range from 0-1, higher values create smoother curves.
* @returns The Graphics instance for method chaining
* @see {@link Graphics#roundRect} For drawing rectangles with rounded corners
* @see {@link Graphics#roundPoly} For drawing regular polygons with rounded corners
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draws a rectangle with fillet corners. Unlike rounded rectangles, this supports negative corner
* radii which create external rounded corners rather than internal ones.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a rectangle with internal fillets
* graphics
* .filletRect(50, 50, 100, 80, 15)
* .fill({ color: 0xff0000 });
*
* // Draw a rectangle with external fillets
* graphics
* .filletRect(200, 50, 100, 80, -20)
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
* ```
* @param x - The x-coordinate of the top-left corner of the rectangle
* @param y - The y-coordinate of the top-left corner of the rectangle
* @param width - The width of the rectangle
* @param height - The height of the rectangle
* @param fillet - The radius of the corner fillets (can be positive or negative)
* @returns The Graphics instance for method chaining
* @see {@link Graphics#roundRect} For standard rounded corners
* @see {@link Graphics#chamferRect} For angled corners
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draws a rectangle with chamfered (angled) corners. Each corner is cut off at
* a 45-degree angle based on the chamfer size.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a basic chamfered rectangle
* graphics
* .chamferRect(50, 50, 100, 80, 15)
* .fill({ color: 0xff0000 });
*
* // Add transform and stroke
* const transform = new Matrix()
* .rotate(Math.PI / 4); // 45 degrees
*
* graphics
* .chamferRect(200, 50, 100, 80, 20, transform)
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
* ```
* @param x - The x-coordinate of the top-left corner of the rectangle
* @param y - The y-coordinate of the top-left corner of the rectangle
* @param width - The width of the rectangle
* @param height - The height of the rectangle
* @param chamfer - The size of the corner chamfers (must be non-zero)
* @param transform - Optional Matrix to transform the rectangle
* @returns The Graphics instance for method chaining
* @see {@link Graphics#roundRect} For rounded corners
* @see {@link Graphics#filletRect} For rounded corners with negative radius support
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
*
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw a basic 5-pointed star
* graphics
* .star(100, 100, 5, 50)
* .fill({ color: 0xff0000 });
*
* // Star with custom inner radius
* graphics
* .star(250, 100, 6, 50, 20)
* .fill({ color: 0x00ff00 })
* .stroke({ width: 2, color: 0x000000 });
* ```
* @param x - The x-coordinate of the center of the star
* @param y - The y-coordinate of the center of the star
* @param points - The number of points on the star (must be >= 3)
* @param radius - The outer radius of the star (distance from center to point tips)
* @param innerRadius - Optional. The inner radius of the star (distance from center to inner vertices).
* If not specified, defaults to half of the outer radius
* @param rotation - Optional. The rotation of the star in radians. Default is 0,
* which aligns one point straight up
* @returns The Graphics instance for method chaining
* @see {@link Graphics#regularPoly} For drawing regular polygons
* @see {@link Graphics#poly} For drawing custom polygons
* @see {@link Graphics#path} For creating custom shapes
*/
star(x: number, y: number, points: number, radius: number, innerRadius?: number, rotation?: number): this;
/**
* Parses and renders an SVG string into the graphics context. This allows for complex shapes
* and paths defined in SVG format to be drawn within the graphics context.
* @example
* ```ts
* const graphics = new Graphics();
* graphics
* .svg(`
* <path d="M 50,50 L 100,50 L 100,100 L 50,100 Z"
* fill="blue" />
* <circle cx="150" cy="75" r="25"
* fill="green" />
* `)
* .stroke({ width: 2, color: 0x000000 });
* ```
* @param svg - The SVG string to be parsed and rendered
* @returns The Graphics instance for method chaining
* @see {@link Graphics#path} For adding custom paths
* @see {@link Graphics#fill} For filling shapes after SVG parsing
* @see {@link Graphics#stroke} For stroking shapes after SVG parsing
*/
svg(svg: string): this;
/**
* Restores the most recently saved graphics state by popping the top of the graphics state stack.
* This includes transformations, fill styles, and stroke styles.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Save current state
* graphics.save();
*
* // Make temporary changes
* graphics
* .translateTransform(100, 100)
* .setFillStyle({ color: 0xff0000 })
* .circle(0, 0, 50)
* .fill();
*
* // Restore to previous state
* graphics.restore();
*
* // Draw with original transform and styles
* graphics
* .circle(50, 50, 30)
* .fill();
* ```
* @returns The Graphics instance for method chaining
* @see {@link Graphics#save} For saving the current state
*/
restore(): this;
/**
* Saves the current graphics state onto a stack. The state includes:
* - Current transformation matrix
* - Current fill style
* - Current stroke style
* @example
* ```ts
* const graphics = new Graphics();
*
* // Save state before complex operations
* graphics.save();
*
* // Create transformed and styled shape
* graphics
* .translateTransform(100, 100)
* .rotateTransform(Math.PI / 4)
* .setFillStyle({
* color: 0xff0000,
* alpha: 0.5
* })
* .rect(-25, -25, 50, 50)
* .fill();
*
* // Restore to original state
* graphics.restore();
*
* // Continue drawing with previous state
* graphics
* .circle(50, 50, 25)
* .fill();
* ```
* @returns The Graphics instance for method chaining
* @see {@link Graphics#restore} For restoring the saved state
* @see {@link Graphics#setTransform} For setting transformations
*/
save(): this;
/**
* Returns the current transformation matrix of the graphics context.
* This matrix represents all accumulated transformations including translate, scale, and rotate.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Apply some transformations
* graphics
* .translateTransform(100, 100)
* .rotateTransform(Math.PI / 4);
*
* // Get the current transform matrix
* const matrix = graphics.getTransform();
* console.log(matrix.tx, matrix.ty); // 100, 100
*
* // Use the matrix for other operations
* graphics
* .setTransform(matrix)
* .circle(0, 0, 50)
* .fill({ color: 0xff0000 });
* ```
* @returns The current transformation matrix.
* @see {@link Graphics#setTransform} For setting the transform matrix
* @see {@link Matrix} For matrix operations
*/
getTransform(): Matrix;
/**
* Resets the current transformation matrix to the identity matrix, effectively removing
* any transformations (rotation, scaling, translation) previously applied.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Apply transformations
* graphics
* .translateTransform(100, 100)
* .scaleTransform(2, 2)
* .circle(0, 0, 25)
* .fill({ color: 0xff0000 });
* // Reset transform to default state
* graphics
* .resetTransform()
* .circle(50, 50, 25) // Will draw at actual coordinates
* .fill({ color: 0x00ff00 });
* ```
* @returns The Graphics instance for method chaining
* @see {@link Graphics#getTransform} For getting the current transform
* @see {@link Graphics#setTransform} For setting a specific transform
* @see {@link Graphics#save} For saving the current transform state
* @see {@link Graphics#restore} For restoring a previous transform state
*/
resetTransform(): this;
/**
* Applies a rotation transformation to the graphics context around the current origin.
* Positive angles rotate clockwise, while negative angles rotate counterclockwise.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Rotate 45 degrees clockwise
* graphics
* .rotateTransform(Math.PI / 4)
* .rect(-25, -25, 50, 50)
* .fill({ color: 0xff0000 });
* ```
* @param angle - The angle of rotation in radians
* @returns The Graphics instance for method chaining
* @see {@link Graphics#scaleTransform} For scaling transformations
* @see {@link Graphics#translateTransform} For position transformations
*/
rotateTransform(angle: number): this;
/**
* Applies a scaling transformation to the graphics context, scaling drawings by x horizontally
* and by y vertically relative to the current origin.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Uniform scaling
* graphics
* .scaleTransform(2) // Scale both dimensions by 2
* .circle(0, 0, 25)
* .fill({ color: 0xff0000 });
*
* // Non-uniform scaling
* graphics
* .scaleTransform(0.5, 2) // Half width, double height
* .rect(100, 100, 50, 50)
* .fill({ color: 0x00ff00 });
* ```
* @param x - The scale factor in the horizontal direction
* @param y - The scale factor in the vertical direction. If omitted, equals x
* @returns The Graphics instance for method chaining
* @see {@link Graphics#rotateTransform} For rotation transformations
* @see {@link Graphics#translateTransform} For position transformations
*/
scaleTransform(x: number, y?: number): this;
/**
* Sets the current transformation matrix of the graphics context.
*
* This method can either
* take a Matrix object or individual transform values to create a new transformation matrix.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Using a Matrix object
* const matrix = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4);
*
* graphics
* .setTransform(matrix)
* .rect(0, 0, 50, 50)
* .fill({ color: 0xff0000 });
*
* // Using individual transform values
* graphics
* .setTransform(
* 2, 0, // scale x by 2
* 0, 1, // no skew
* 100, 100 // translate x,y by 100
* )
* .circle(0, 0, 25)
* .fill({ color: 0x00ff00 });
* ```
* @param transform - The matrix to set as the current transformation matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setTransform(transform: Matrix): this;
/**
* Sets the current transformation matrix of the graphics context to the specified matrix or values.
* This replaces the current transformation matrix.
* @param a - The value for the a property of the matrix, or a Matrix object to use directly.
* @param b - The value for the b property of the matrix.
* @param c - The value for the c property of the matrix.
* @param d - The value for the d property of the matrix.
* @param dx - The value for the tx (translate x) property of the matrix.
* @param dy - The value for the ty (translate y) property of the matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setTransform(a: number, b: number, c: number, d: number, dx: number, dy: number): this;
setTransform(a: number | Matrix, b?: number, c?: number, d?: number, dx?: number, dy?: number): this;
/**
* Applies a transformation matrix to the current graphics context by multiplying
* the current matrix with the specified matrix. This allows for complex transformations
* combining multiple operations.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Using a Matrix object
* const matrix = new Matrix()
* .scale(2, 1) // Scale horizontally
* .rotate(Math.PI/6); // Rotate 30 degrees
*
* graphics
* .transform(matrix)
* .rect(0, 0, 50, 50)
* .fill({ color: 0xff0000 });
*
* // Using individual transform values
* graphics
* .transform(
* 1, 0.5, // Skew horizontally
* 0, 1, // No vertical skew
* 100, 100 // Translate
* )
* .circle(0, 0, 25)
* .fill({ color: 0x00ff00 });
* ```
* @param transform - The matrix to apply to the current transformation.
* @returns The instance of the current GraphicsContext for method chaining.
*/
transform(transform: Matrix): this;
/**
* Applies the specified transformation matrix to the current graphics context by multiplying
* the current matrix with the specified matrix.
* @param a - The value for the a property of the matrix, or a Matrix object to use directly.
* @param b - The value for the b property of the matrix.
* @param c - The value for the c property of the matrix.
* @param d - The value for the d property of the matrix.
* @param dx - The value for the tx (translate x) property of the matrix.
* @param dy - The value for the ty (translate y) property of the matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
transform(a: number, b: number, c: number, d: number, dx: number, dy: number): this;
transform(a: number | Matrix, b?: number, c?: number, d?: number, dx?: number, dy?: number): this;
/**
* Applies a translation transformation to the graphics context, moving the origin by the specified amounts.
* This affects all subsequent drawing operations.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic translation
* graphics
* .translateTransform(100, 100)
* .circle(0, 0, 25)
* .fill({ color: 0xff0000 });
* ```
* @param x - The amount to translate in the horizontal direction
* @param y - The amount to translate in the vertical direction. If omitted, equals x
* @returns The Graphics instance for method chaining
* @see {@link Graphics#setTransform} For setting absolute transformations
* @see {@link Graphics#transform} For applying complex transformations
* @see {@link Graphics#save} For saving the current transform state
*/
translateTransform(x: number, y?: number): this;
/**
* Clears all drawing commands from the graphics context, effectively resetting it.
* This includes clearing the current path, fill style, stroke style, and transformations.
*
* > [!NOTE] Graphics objects are not designed to be continuously cleared and redrawn.
* > Instead, they are intended to be used for static or semi-static graphics that
* > can be redrawn as needed. Frequent clearing and redrawing may lead to performance issues.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Draw some shapes
* graphics
* .circle(100, 100, 50)
* .fill({ color: 0xff0000 })
* .rect(200, 100, 100, 50)
* .fill({ color: 0x00ff00 });
*
* // Clear all graphics
* graphics.clear();
*
* // Start fresh with new shapes
* graphics
* .circle(150, 150, 30)
* .fill({ color: 0x0000ff });
* ```
* @returns The Graphics instance for method chaining
* @see {@link Graphics#beginPath} For starting a new path without clearing styles
* @see {@link Graphics#save} For saving the current state
* @see {@link Graphics#restore} For restoring a previous state
*/
clear(): this;
/**
* Gets or sets the current fill style for the graphics context. The fill style determines
* how shapes are filled when using the fill() method.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic color fill
* graphics.fillStyle = {
* color: 0xff0000, // Red
* alpha: 1
* };
*
* // Using gradients
* const gradient = new FillGradient({
* end: { x: 0, y: 1 }, // Vertical gradient
* stops: [
* { offset: 0, color: 0xff0000, alpha: 1 }, // Start color
* { offset: 1, color: 0x0000ff, alpha: 1 } // End color
* ]
* });
*
* graphics.fillStyle = {
* fill: gradient,
* alpha: 0.8
* };
*
* // Using patterns
* graphics.fillStyle = {
* texture: myTexture,
* alpha: 1,
* matrix: new Matrix()
* .scale(0.5, 0.5)
* .rotate(Math.PI / 4)
* };
* ```
* @type {ConvertedFillStyle}
* @see {@link FillStyle} For all available fill style options
* @see {@link FillGradient} For creating gradient fills
* @see {@link Graphics#fill} For applying the fill to paths
*/
get fillStyle(): GraphicsContext["fillStyle"];
set fillStyle(value: FillInput);
/**
* Gets or sets the current stroke style for the graphics context. The stroke style determines
* how paths are outlined when using the stroke() method.
* @example
* ```ts
* const graphics = new Graphics();
*
* // Basic stroke style
* graphics.strokeStyle = {
* width: 2,
* color: 0xff0000,
* alpha: 1
* };
*
* // Using with gradients
* const gradient = new FillGradient({
* end: { x: 0, y: 1 },
* stops: [
* { offset: 0, color: 0xff0000, alpha: 1 },
* { offset: 1, color: 0x0000ff, alpha: 1 }
* ]
* });
*
* graphics.strokeStyle = {
* width: 4,
* fill: gradient,
* alignment: 0.5,
* join: 'round',
* cap: 'round'
* };
*
* // Complex stroke settings
* graphics.strokeStyle = {
* width: 6,
* color: 0x00ff00,
* alpha: 0.5,
* join: 'miter',
* miterLimit: 10,
* };
* ```
* @see {@link StrokeStyle} For all available stroke style options
* @see {@link Graphics#stroke} For applying the stroke to paths
*/
get strokeStyle(): GraphicsContext["strokeStyle"];
set strokeStyle(value: StrokeStyle);
/**
* Creates a new Graphics object that copies the current graphics content.
* The clone can either share the same context (shallow clone) or have its own independent
* context (deep clone).
* @example
* ```ts
* const graphics = new Graphics();
*
* // Create original graphics content
* graphics
* .circle(100, 100, 50)
* .fill({ color: 0xff0000 });
*
* // Create a shallow clone (shared context)
* const shallowClone = graphics.clone();
*
* // Changes to original affect the clone
* graphics
* .circle(200, 100, 30)
* .fill({ color: 0x00ff00 });
*
* // Create a deep clone (independent context)
* const deepClone = graphics.clone(true);
*
* // Modify deep clone independently
* deepClone
* .translateTransform(100, 100)
* .circle(0, 0, 40)
* .fill({ color: 0x0000ff });
* ```
* @param deep - Whether to create a deep clone of the graphics object.
* If false (default), the context will be shared between objects.
* If true, creates an independent copy of the context.
* @returns A new Graphics instance with either shared or copied context
* @see {@link Graphics#context} For accessing the underlying graphics context
* @see {@link GraphicsContext} For understanding the shared context behavior
*/
clone(deep?: boolean): Graphics;
/**
* @param width
* @param color
* @param alpha
* @deprecated since 8.0.0 Use {@link Graphics#setStrokeStyle} instead
*/
lineStyle(width?: number, color?: ColorSource, alpha?: number): this;
/**
* @param color
* @param alpha
* @deprecated since 8.0.0 Use {@link Graphics#fill} instead
*/
beginFill(color: ColorSource, alpha?: number): this;
/**
* @deprecated since 8.0.0 Use {@link Graphics#fill} instead
*/
endFill(): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#circle} instead
*/
drawCircle(...args: Parameters<GraphicsContext["circle"]>): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#ellipse} instead
*/
drawEllipse(...args: Parameters<GraphicsContext["ellipse"]>): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#poly} instead
*/
drawPolygon(...args: Parameters<GraphicsContext["poly"]>): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#rect} instead
*/
drawRect(...args: Parameters<GraphicsContext["rect"]>): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#roundRect} instead
*/
drawRoundedRect(...args: Parameters<GraphicsContext["roundRect"]>): this;
/**
* @param {...any} args
* @deprecated since 8.0.0 Use {@link Graphics#star} instead
*/
drawStar(...args: Parameters<GraphicsContext["star"]>): this;
}
/**
* A batchable graphics object.
* @ignore
*/
export declare class BatchableGraphics implements DefaultBatchableMeshElement {
readonly packAsQuad = false;
batcherName: string;
texture: Texture;
topology: Topology;
renderable: Graphics;
indexOffset: number;
indexSize: number;
attributeOffset: number;
attributeSize: number;
baseColor: number;
alpha: number;
applyTransform: boolean;
roundPixels: 0 | 1;
_indexStart: number;
_textureId: number;
_attributeStart: number;
_batcher: Batcher;
_batch: Batch;
geometryData: {
vertices: number[];
uvs: number[];
indices: number[];
};
get uvs(): number[];
get positions(): number[];
get indices(): number[];
get blendMode(): BLEND_MODES;
get color(): number;
get transform(): Matrix;
copyTo(gpuBuffer: BatchableGraphics): void;
reset(): void;
destroy(): void;
}
interface GeometryData {
vertices: number[];
uvs: number[];
indices: number[];
}
/**
* A class that holds batchable graphics data for a GraphicsContext.
* @category rendering
* @ignore
*/
export declare class GpuGraphicsContext implements GPUData {
isBatchable: boolean;
context: GraphicsContext;
batches: BatchableGraphics[];
geometryData: GeometryData;
graphicsData: GraphicsContextRenderData;
reset(): void;
destroy(): void;
}
/**
* A class that holds the render data for a GraphicsContext.
* @category rendering
* @ignore
*/
export declare class GraphicsContextRenderData {
batcher: DefaultBatcher;
instructions: InstructionSet;
init(options: BatcherOptions): void;
/**
* @deprecated since version 8.0.0
* Use `batcher.geometry` instead.
* @see {Batcher#geometry}
*/
get geometry(): BatchGeometry;
destroy(): void;
}
/**
* Options for the GraphicsContextSystem.
* @category rendering
* @advanced
*/
export interface GraphicsContextSystemOptions {
/** A value from 0 to 1 that controls the smoothness of bezier curves (the higher the smoother) */
bezierSmoothness?: number;
}
/**
* A system that manages the rendering of GraphicsContexts.
* @category rendering
* @advanced
*/
export declare class GraphicsContextSystem implements System<GraphicsContextSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "graphicsContext";
};
/** The default options for the GraphicsContextSystem. */
static readonly defaultOptions: GraphicsContextSystemOptions;
private readonly _renderer;
private readonly _managedContexts;
constructor(renderer: Renderer);
/**
* Runner init called, update the default options
* @ignore
*/
init(options?: GraphicsContextSystemOptions): void;
/**
* Returns the render data for a given GraphicsContext.
* @param context - The GraphicsContext to get the render data for.
* @internal
*/
getContextRenderData(context: GraphicsContext): GraphicsContextRenderData;
/**
* Updates the GPU context for a given GraphicsContext.
* If the context is dirty, it will rebuild the batches and geometry data.
* @param context - The GraphicsContext to update.
* @returns The updated GpuGraphicsContext.
* @internal
*/
updateGpuContext(context: GraphicsContext): GpuGraphicsContext;
/**
* Returns the GpuGraphicsContext for a given GraphicsContext.
* If it does not exist, it will initialize a new one.
* @param context - The GraphicsContext to get the GpuGraphicsContext for.
* @returns The GpuGraphicsContext for the given GraphicsContext.
* @internal
*/
getGpuContext(context: GraphicsContext): GpuGraphicsContext;
private _initContextRenderData;
private _initContext;
destroy(): void;
}
/**
* The mode for batching graphics instructions.
*
* It can be:
* - 'auto': Automatically determines whether to batch based on the number of instructions.
* - 'batch': Forces batching of all instructions.
* - 'no-batch': Disables batching, processing each instruction individually.
* @category scene
* @advanced
*/
export type BatchMode = "auto" | "batch" | "no-batch";
/** @internal */
export interface FillInstruction {
action: "fill" | "cut";
data: {
style: ConvertedFillStyle;
path: GraphicsPath;
hole?: GraphicsPath;
};
}
/** @internal */
export interface StrokeInstruction {
action: "stroke";
data: {
style: ConvertedStrokeStyle;
path: GraphicsPath;
hole?: GraphicsPath;
};
}
/** @internal */
export interface TextureInstruction {
action: "texture";
data: {
image: Texture;
dx: number;
dy: number;
dw: number;
dh: number;
transform: Matrix;
alpha: number;
style: number;
};
}
/** @internal */
export type GraphicsInstructions = FillInstruction | StrokeInstruction | TextureInstruction;
/**
* The GraphicsContext class allows for the creation of lightweight objects that contain instructions for drawing shapes and paths.
* It is used internally by the Graphics class to draw shapes and paths, and can be used directly and shared between Graphics objects,
*
* This sharing of a `GraphicsContext` means that the intensive task of converting graphics instructions into GPU-ready geometry is done once, and the results are reused,
* much like sprites reusing textures.
* @category scene
* @standard
*/
export declare class GraphicsContext extends EventEmitter<{
update: GraphicsContext;
destroy: GraphicsContext;
unload: GraphicsContext;
}> implements GCable {
/** @internal */
_gpuData: Record<number | string, GpuGraphicsContext>;
/** @internal */
_gcData?: GCData;
/** If set to true, the resource will be garbage collected automatically when it is not used. */
autoGarbageCollect: boolean;
/** @internal */
_gcLastUsed: number;
/** The default fill style to use when none is provided. */
static defaultFillStyle: ConvertedFillStyle;
/** The default stroke style to use when none is provided. */
static defaultStrokeStyle: ConvertedStrokeStyle;
/**
* unique id for this graphics context
* @internal
*/
readonly uid: number;
/**
* Indicates whether content is updated and have to be re-rendered.
* @internal
*/
dirty: boolean;
/** The batch mode for this graphics context. It can be 'auto', 'batch', or 'no-batch'. */
batchMode: BatchMode;
/** @internal */
instructions: GraphicsInstructions[];
/**
* Custom shader to apply to the graphics when rendering.
* @advanced
*/
customShader?: Shader;
/** Whether the graphics context has been destroyed. */
destroyed: boolean;
private _activePath;
private _transform;
private _fillStyle;
private _strokeStyle;
private _stateStack;
private _tick;
private _bounds;
private _boundsDirty;
/**
* Creates a new GraphicsContext object that is a clone of this instance, copying all properties,
* including the current drawing state, transformations, styles, and instructions.
* @returns A new GraphicsContext instance with the same properties and state as this one.
*/
clone(): GraphicsContext;
/**
* The current fill style of the graphics context. This can be a color, gradient, pattern, or a more complex style defined by a FillStyle object.
*/
get fillStyle(): ConvertedFillStyle;
set fillStyle(value: FillInput);
/**
* The current stroke style of the graphics context. Similar to fill styles, stroke styles can encompass colors, gradients, patterns, or more detailed configurations via a StrokeStyle object.
*/
get strokeStyle(): ConvertedStrokeStyle;
set strokeStyle(value: FillInput);
/**
* Sets the current fill style of the graphics context. The fill style can be a color, gradient,
* pattern, or a more complex style defined by a FillStyle object.
* @param style - The fill style to apply. This can be a simple color, a gradient or pattern object,
* or a FillStyle or ConvertedFillStyle object.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setFillStyle(style: FillInput): this;
/**
* Sets the current stroke style of the graphics context. Similar to fill styles, stroke styles can
* encompass colors, gradients, patterns, or more detailed configurations via a StrokeStyle object.
* @param style - The stroke style to apply. Can be defined as a color, a gradient or pattern,
* or a StrokeStyle or ConvertedStrokeStyle object.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setStrokeStyle(style: StrokeInput): this;
/**
* Adds a texture to the graphics context. This method supports multiple overloads for specifying the texture.
* If only a texture is provided, it uses the texture's width and height for drawing.
* @param texture - The Texture object to use.
* @returns The instance of the current GraphicsContext for method chaining.
*/
texture(texture: Texture): this;
/**
* Adds a texture to the graphics context. This method supports multiple overloads for specifying the texture,
* tint, and dimensions. If only a texture is provided, it uses the texture's width and height for drawing.
* Additional parameters allow for specifying a tint color, and custom dimensions for the texture drawing area.
* @param texture - The Texture object to use.
* @param tint - (Optional) A ColorSource to tint the texture. If not provided, defaults to white (0xFFFFFF).
* @param dx - (Optional) The x-coordinate in the destination canvas at which to place the top-left corner of
* the source image.
* @param dy - (Optional) The y-coordinate in the destination canvas at which to place the top-left corner of
* the source image.
* @param dw - (Optional) The width of the rectangle within the source image to draw onto the destination canvas.
* If not provided, uses the texture's frame width.
* @param dh - (Optional) The height of the rectangle within the source image to draw onto the destination canvas.
* If not provided, uses the texture's frame height.
* @returns The instance of the current GraphicsContext for method chaining.
*/
texture(texture: Texture, tint?: ColorSource, dx?: number, dy?: number, dw?: number, dh?: number): this;
/**
* Resets the current path. Any previous path and its commands are discarded and a new path is
* started. This is typically called before beginning a new shape or series of drawing commands.
* @returns The instance of the current GraphicsContext for method chaining.
*/
beginPath(): this;
/**
* Fills the current or given path with the current fill style. This method can optionally take
* a color and alpha for a simple fill, or a more complex FillInput object for advanced fills.
* @param style - (Optional) The style to fill the path with. Can be a color, gradient, pattern, or a complex style object. If omitted, uses the current fill style.
* @returns The instance of the current GraphicsContext for method chaining.
*/
fill(style?: FillInput): this;
/** @deprecated 8.0.0 */
fill(color: ColorSource, alpha: number): this;
private _initNextPathLocation;
/**
* Strokes the current path with the current stroke style. This method can take an optional
* FillInput parameter to define the stroke's appearance, including its color, width, and other properties.
* @param style - (Optional) The stroke style to apply. Can be defined as a simple color or a more complex style object. If omitted, uses the current stroke style.
* @returns The instance of the current GraphicsContext for method chaining.
*/
stroke(style?: StrokeInput): this;
/**
* Applies a cutout to the last drawn shape. This is used to create holes or complex shapes by
* subtracting a path from the previously drawn path. If a hole is not completely in a shape, it will
* fail to cut correctly!
* @returns The instance of the current GraphicsContext for method chaining.
*/
cut(): this;
/**
* Adds an arc to the current path, which is centered at (x, y) with the specified radius,
* starting and ending angles, and direction.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The arc's radius.
* @param startAngle - The starting angle, in radians.
* @param endAngle - The ending angle, in radians.
* @param counterclockwise - (Optional) Specifies whether the arc is drawn counterclockwise (true) or clockwise (false). Defaults to false.
* @returns The instance of the current GraphicsContext for method chaining.
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): this;
/**
* Adds an arc to the current path with the given control points and radius, connected to the previous point
* by a straight line if necessary.
* @param x1 - The x-coordinate of the first control point.
* @param y1 - The y-coordinate of the first control point.
* @param x2 - The x-coordinate of the second control point.
* @param y2 - The y-coordinate of the second control point.
* @param radius - The arc's radius.
* @returns The instance of the current GraphicsContext for method chaining.
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath(): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @returns The instance of the current object for chaining.
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number): this;
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @returns The instance of the current object for chaining.
*/
circle(x: number, y: number, radius: number): this;
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* @param path - The `GraphicsPath` to add.
* @returns The instance of the current object for chaining.
*/
path(path: GraphicsPath): this;
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x: number, y: number): this;
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x: number, y: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cpx - The x-coordinate of the control point.
* @param cpy - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number, smoothness?: number): this;
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x: number, y: number, w: number, h: number): this;
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @returns The instance of the current object for chaining.
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number): this;
/**
* Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons,
* which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled,
* rotated, or translated as needed.
* @param points - An array of numbers, or an array of PointData objects eg [{x,y}, {x,y}, {x,y}]
* representing the x and y coordinates, of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
*/
poly(points: number[] | PointData[], close?: boolean): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @returns The instance of the current object for chaining.
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @param x - The x-coordinate of the center of the star.
* @param y - The y-coordinate of the center of the star.
* @param points - The number of points of the star.
* @param radius - The outer radius of the star (distance from the center to the outer points).
* @param innerRadius - Optional. The inner radius of the star
* (distance from the center to the inner points between the outer points).
* If not provided, defaults to half of the `radius`.
* @param rotation - Optional. The rotation of the star in radians, where 0 is aligned with the y-axis.
* Defaults to 0, meaning one point is directly upward.
* @returns The instance of the current object for chaining further drawing commands.
*/
star(x: number, y: number, points: number, radius: number, innerRadius?: number, rotation?: number): this;
/**
* Parses and renders an SVG string into the graphics context. This allows for complex shapes and paths
* defined in SVG format to be drawn within the graphics context.
* @param svg - The SVG string to be parsed and rendered.
*/
svg(svg: string): this;
/**
* Restores the most recently saved graphics state by popping the top of the graphics state stack.
* This includes transformations, fill styles, and stroke styles.
*/
restore(): this;
/** Saves the current graphics state, including transformations, fill styles, and stroke styles, onto a stack. */
save(): this;
/**
* Returns the current transformation matrix of the graphics context.
* @returns The current transformation matrix.
*/
getTransform(): Matrix;
/**
* Resets the current transformation matrix to the identity matrix, effectively removing any transformations (rotation, scaling, translation) previously applied.
* @returns The instance of the current GraphicsContext for method chaining.
*/
resetTransform(): this;
/**
* Applies a rotation transformation to the graphics context around the current origin.
* @param angle - The angle of rotation in radians.
* @returns The instance of the current GraphicsContext for method chaining.
*/
rotate(angle: number): this;
/**
* Applies a scaling transformation to the graphics context, scaling drawings by x horizontally and by y vertically.
* @param x - The scale factor in the horizontal direction.
* @param y - (Optional) The scale factor in the vertical direction. If not specified, the x value is used for both directions.
* @returns The instance of the current GraphicsContext for method chaining.
*/
scale(x: number, y?: number): this;
/**
* Sets the current transformation matrix of the graphics context to the specified matrix or values.
* This replaces the current transformation matrix.
* @param transform - The matrix to set as the current transformation matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setTransform(transform: Matrix): this;
/**
* Sets the current transformation matrix of the graphics context to the specified matrix or values.
* This replaces the current transformation matrix.
* @param a - The value for the a property of the matrix, or a Matrix object to use directly.
* @param b - The value for the b property of the matrix.
* @param c - The value for the c property of the matrix.
* @param d - The value for the d property of the matrix.
* @param dx - The value for the tx (translate x) property of the matrix.
* @param dy - The value for the ty (translate y) property of the matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
setTransform(a: number, b: number, c: number, d: number, dx: number, dy: number): this;
/**
* Applies the specified transformation matrix to the current graphics context by multiplying
* the current matrix with the specified matrix.
* @param transform - The matrix to apply to the current transformation.
* @returns The instance of the current GraphicsContext for method chaining.
*/
transform(transform: Matrix): this;
/**
* Applies the specified transformation matrix to the current graphics context by multiplying
* the current matrix with the specified matrix.
* @param a - The value for the a property of the matrix, or a Matrix object to use directly.
* @param b - The value for the b property of the matrix.
* @param c - The value for the c property of the matrix.
* @param d - The value for the d property of the matrix.
* @param dx - The value for the tx (translate x) property of the matrix.
* @param dy - The value for the ty (translate y) property of the matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
transform(a: number, b: number, c: number, d: number, dx: number, dy: number): this;
/**
* Applies a translation transformation to the graphics context, moving the origin by the specified amounts.
* @param x - The amount to translate in the horizontal direction.
* @param y - (Optional) The amount to translate in the vertical direction. If not specified, the x value is used for both directions.
* @returns The instance of the current GraphicsContext for method chaining.
*/
translate(x: number, y?: number): this;
/**
* Clears all drawing commands from the graphics context, effectively resetting it. This includes clearing the path,
* and optionally resetting transformations to the identity matrix.
* @returns The instance of the current GraphicsContext for method chaining.
*/
clear(): this;
protected onUpdate(): void;
/** The bounds of the graphic shape. */
get bounds(): Bounds;
/**
* Check to see if a point is contained within this geometry.
* @param point - Point to check if it's contained.
* @returns {boolean} `true` if the point is contained within geometry.
*/
containsPoint(point: PointData): boolean;
/** Unloads the GPU data from the graphics context. */
unload(): void;
/**
* Destroys the GraphicsData object.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* context.destroy();
* context.destroy(true);
* context.destroy({ texture: true, textureSource: true });
*/
destroy(options?: TypeOrBool<TextureDestroyOptions>): void;
}
/**
* The alignment of the text.
*
* - 'left': Aligns text to the left edge.
* - 'center': Centers text horizontally.
* - 'right': Aligns text to the right edge.
* - 'justify': Justifies text, aligning both left and right edges.
* @example
* ```ts
* import { TextStyle } from 'pixi.js';
* const style = new TextStyle({
* align: 'center', // or 'left', 'right', 'justify'
* });
* ```
* @category text
* @standard
*/
export type TextStyleAlign = "left" | "center" | "right" | "justify";
/**
* The fill style input for text styles.
*
* This can be:
* - A color string like 'red', '#00FF00', or 'rgba(255,0,0,0.5)'
* - A hex number like 0xff0000 for red
* - A FillStyle object with properties like { color: 0xff0000, alpha: 0.5 }
* - A FillGradient for gradient fills
* - A FillPattern for pattern/texture fills
* @example
* ```ts
* // Simple Fills
* new TextStyle({ fill: 'red' }); // Color string
* new TextStyle({ fill: 0x00ff00 }); // Hex color
* new TextStyle({ fill: 'rgb(255,0,0)' }); // RGB string
* // Gradients
* new TextStyle({
* fill: new FillGradient({
* end: { x: 1, y: 1 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* }),
* });
* // Patterns
* new TextStyle({
* fill: new FillPattern(Assets.get('pattern.png'))
* });
* ```
* @category text
* @standard
*/
export type TextStyleFill = string | string[] | number | number[] | CanvasGradient | CanvasPattern;
/**
* The font style input for text styles. Controls the slant or italicization of the text.
* @example
* ```ts
* // Create text with normal font style
* const normalText = new Text({
* text: 'Normal Style Text',
* style: {
* fontStyle: 'normal',
* fontSize: 24
* }
* });
*
* // Create italic text
* const italicText = new Text({
* text: 'Italic Style Text',
* style: {
* fontStyle: 'italic',
* fontSize: 24,
* fontFamily: 'Arial'
* }
* });
*
* // Create oblique text
* const obliqueText = new Text({
* text: 'Oblique Style Text',
* style: {
* fontStyle: 'oblique',
* fontSize: 24,
* fontFamily: 'Times New Roman'
* }
* });
*
* // Dynamic style changes
* let isItalic = false;
* text.style = {
* ...text.style,
* fontStyle: isItalic ? 'italic' : 'normal'
* };
* ```
*
* Supported values:
* - 'normal': Regular upright text with no slant
* - 'italic': True italics using specifically designed italic glyphs
* - 'oblique': Slanted version of the regular glyphs
* @remarks
* - 'italic' uses specially designed glyphs with cursive characteristics
* - 'oblique' is a mechanical slant of the normal glyphs
* - Not all fonts include true italic designs; some may fall back to oblique
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font-style | MDN font-style}
* @category text
* @standard
*/
export type TextStyleFontStyle = "normal" | "italic" | "oblique";
/**
* The font variant input for text styles. Controls the capitalization and presentation of letters.
* Used to enable special rendering like small caps.
* @example
* ```ts
* // Create text with normal font variant
* const normalText = new Text({
* text: 'Normal Text',
* style: {
* fontVariant: 'normal',
* fontSize: 24
* }
* });
*
* // Create text with small-caps variant
* const smallCapsText = new Text({
* text: 'Small Caps Text',
* style: {
* fontVariant: 'small-caps',
* fontSize: 24,
* fontFamily: 'Arial'
* }
* });
*
* // Use in a TextStyle instance
* const style = new TextStyle({
* fontVariant: 'small-caps',
* fontSize: 32,
* fill: 0x4a4a4a
* });
*
* // Update variant dynamically
* text.style = {
* ...text.style,
* fontVariant: text.style.fontVariant === 'normal' ? 'small-caps' : 'normal'
* };
* ```
*
* Supported values:
* - 'normal': Regular text rendering with standard capitalization
* - 'small-caps': Renders lowercase letters as smaller versions of capital letters
* @remarks
* Small caps are only available if the font supports them.
* Not all fonts include true small caps glyphs.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant | MDN font-variant}
* @category text
* @standard
*/
export type TextStyleFontVariant = "normal" | "small-caps";
/**
* The font weight input for text styles. Controls the thickness or boldness of the text.
* @example
* ```ts
* // Create text with different font weights
* const normalText = new Text({
* text: 'Normal Weight',
* style: { fontWeight: 'normal' }
* });
*
* const boldText = new Text({
* text: 'Bold Weight',
* style: { fontWeight: 'bold' }
* });
*
* // Using numeric weights
* const lightText = new Text({
* text: 'Light Weight',
* style: { fontWeight: '300' }
* });
*
* const mediumText = new Text({
* text: 'Medium Weight',
* style: { fontWeight: '500' }
* });
*
* const heavyText = new Text({
* text: 'Heavy Weight',
* style: { fontWeight: '900' }
* });
*
* // Responsive weight changes
* const adaptiveText = new Text({
* text: 'Adaptive Weight',
* style: { fontWeight: window.innerWidth > 600 ? 'bold' : 'normal' }
* });
* ```
*
* Supported values:
* - 'normal': Standard weight (equivalent to 400)
* - 'bold': Bold weight (equivalent to 700)
* - 'bolder': One weight darker than the parent element
* - 'lighter': One weight lighter than the parent element
* - '100': Thin (Hairline)
* - '200': Extra Light (Ultra Light)
* - '300': Light
* - '400': Normal
* - '500': Medium
* - '600': Semi Bold (Demi Bold)
* - '700': Bold
* - '800': Extra Bold (Ultra Bold)
* - '900': Heavy (Black)
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight | MDN font-weight}
* @category text
* @standard
*/
export type TextStyleFontWeight = "normal" | "bold" | "bolder" | "lighter" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900";
/**
* The line join style for text strokes. Determines how lines connect at corners.
* @example
* ```ts
* // Create text with miter joins (sharp corners)
* const sharpText = new Text({
* text: 'Sharp Corners',
* style: {
* fontSize: 36,
* stroke: {
* color: '#4a1850',
* width: 4,
* lineJoin: 'miter' // Sharp corners
* }
* }
* });
*
* // Create text with round joins
* const roundText = new Text({
* text: 'Rounded Corners',
* style: {
* fontSize: 36,
* stroke: {
* color: '#4a1850',
* width: 4,
* lineJoin: 'round' // Smooth rounded corners
* }
* }
* });
*
* // Create text with beveled joins
* const bevelText = new Text({
* text: 'Beveled Corners',
* style: {
* fontSize: 36,
* stroke: {
* color: '#4a1850',
* width: 4,
* lineJoin: 'bevel' // Flattened corners
* }
* }
* });
* ```
* Available values:
* - 'miter': Creates sharp corners by extending the outer edges until they meet
* - 'round': Creates smooth, rounded corners using a circular arc
* - 'bevel': Creates flattened corners by filling an additional triangle between the outer edges
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin | MDN lineJoin}
* @category text
* @standard
*/
export type TextStyleLineJoin = "miter" | "round" | "bevel";
/**
* The text baseline for text styles.
*
* This can be:
* - 'alphabetic': The alphabetic baseline
* - 'top': The top of the text
* - 'hanging': The hanging baseline
* - 'middle': The middle of the text
* - 'ideographic': The ideographic baseline
* - 'bottom': The bottom of the text
* @category text
* @standard
*/
export type TextStyleTextBaseline = "alphabetic" | "top" | "hanging" | "middle" | "ideographic" | "bottom";
/**
* Controls how whitespace (spaces, tabs, and line breaks) is handled within the text.
* This affects text wrapping and spacing behavior.
* @example
* ```ts
* // Normal mode (collapse spaces and newlines)
* const normalText = new Text({
* text: 'Hello World\n\nNew Line',
* style: {
* whiteSpace: 'normal',
* fontSize: 24
* }
* }); // Renders as: "Hello World New Line"
*
* // Pre mode (preserve all whitespace)
* const preText = new Text({
* text: 'Hello World\n\nNew Line',
* style: {
* whiteSpace: 'pre',
* fontSize: 24
* }
* }); // Preserves spaces and line breaks exactly
*
* // Pre-line mode (preserve newlines, collapse spaces)
* const preLineText = new Text({
* text: 'Hello World\n\nNew Line',
* style: {
* whiteSpace: 'pre-line',
* fontSize: 24
* }
* }); // Preserves line breaks, collapses multiple spaces
*
* // With word wrap enabled
* const wrappedText = new Text({
* text: 'A long text with multiple spaces\nand line breaks',
* style: {
* whiteSpace: 'pre-line',
* wordWrap: true,
* wordWrapWidth: 200,
* fontSize: 24
* }
* });
* ```
*
* Supported values:
* - 'normal': Collapses all whitespace (spaces, tabs, line breaks) into a single space
* - 'pre': Preserves all whitespace characters exactly as written
* - 'pre-line': Preserves line breaks but collapses multiple spaces into a single space
* @remarks
* - 'normal' is best for single-line text or when you want to ignore formatting
* - 'pre' is useful for code blocks or when exact spacing is important
* - 'pre-line' is good for formatted text where you want to keep line breaks but clean up spaces
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/white-space | MDN white-space}
* @see {@link TextStyle#wordWrap} For controlling text wrapping
* @category text
* @standard
*/
export type TextStyleWhiteSpace = "normal" | "pre" | "pre-line";
/**
* Defines a drop shadow effect for text rendering.
* Drop shadows add depth and emphasis to text by creating a shadow offset from the text.
* @example
* ```ts
* // Create text with basic drop shadow
* const text = new Text({
* text: 'Shadow Text',
* style: {
* fontSize: 48,
* dropShadow: {
* alpha: 0.5, // 50% opacity shadow
* angle: Math.PI / 6, // 30 degrees
* blur: 4, // Soft shadow edge
* color: '#000000', // Black shadow
* distance: 6 // Shadow offset
* }
* }
* });
*
* // Dynamic shadow updates
* text.style.dropShadow = {
* alpha: Math.sin(Date.now() / 1000) * 0.5 + 0.5, // Pulsing opacity
* angle: Date.now() / 1000, // Rotating angle
* blur: 4,
* color: '#000000',
* distance: 6
* };
* ```
* @category text
* @standard
*/
export type TextDropShadow = {
/**
* The opacity of the drop shadow.
* - Range: 0 to 1
* - 0 = fully transparent
* - 1 = fully opaque
* @example
* ```ts
* // Set drop shadow opacity to 50%
* dropShadow: {
* alpha: 0.5
* }
* ```
* @default 1
*/
alpha: number;
/**
* The angle of the drop shadow in radians.
* - 0 = right
* - Math.PI/2 = down
* - Math.PI = left
* - Math.PI*1.5 = up
* @example
* ```ts
* // Set drop shadow angle to 30 degrees
* dropShadow: {
* angle: Math.PI / 6 // 30 degrees
* }
* ```
* @default Math.PI/6 (30 degrees)
*/
angle: number;
/**
* The blur radius of the shadow.
* - 0 = sharp shadow
* - Higher values = softer shadow
* @example
* ```ts
* // Set drop shadow blur radius to 10 pixels
* dropShadow: {
* blur: 10
* }
* ```
* @default 0
*/
blur: number;
/**
* The color of the drop shadow.
* Accepts any valid CSS color string, hex number, or RGB/RGBA values.
* @example '#000000', 'rgba(0,0,0,0.5)', 0x000000
* @default 'black'
*/
color: ColorSource;
/**
* The distance of the drop shadow from the text.
* Measured in pixels.
* @example
* ```ts
* // Set drop shadow distance to 5 pixels
* dropShadow: {
* distance: 5
* }
* ```
* @default 5
*/
distance: number;
};
/**
* Constructor options used for `TextStyle` instances. Defines the visual appearance and layout of text.
* @example
* ```ts
* // Basic text style
* const basicStyle = new TextStyle({
* fontSize: 24,
* fill: 'black',
* fontFamily: 'Arial'
* });
*
* // Rich text style with multiple features
* const richStyle = new TextStyle({
* fontFamily: ['Arial', 'Helvetica', 'sans-serif'],
* fontSize: 36,
* fontWeight: 'bold',
* fill: 'red',
* stroke: { color: '#4a1850', width: 5 },
* align: 'center',
* dropShadow: {
* color: '#000000',
* blur: 4,
* distance: 6,
* angle: Math.PI / 6
* },
* wordWrap: true,
* wordWrapWidth: 440,
* lineHeight: 40,
* textBaseline: 'middle'
* });
* ```
* @see {@link TextStyle} For the main style class
* @category text
* @standard
*/
export interface TextStyleOptions {
/**
* Alignment for multiline text, does not affect single line text
* @default 'left'
*/
align?: TextStyleAlign;
/**
* Whether to allow line breaks within words.
* Requires wordWrap to be true.
* @example
* ```ts
* // Enable word breaking
* const style = new TextStyle({
* breakWords: true,
* wordWrap: true,
* wordWrapWidth: 200
* });
* ```
* @default false
*/
breakWords?: boolean;
/**
* Drop shadow configuration for the text.
* Can be boolean or a TextDropShadow object.
* @default null
*/
dropShadow?: boolean | Partial<TextDropShadow>;
/**
* Fill style for the text.
* Can be a color, gradient, or pattern.
* @default 'black'
*/
fill?: FillInput;
/**
* Font family or families to use.
* Can be single name or array of fallbacks.
* @example
* ```ts
* // Single font family
* fontFamily: 'Arial'
* // Multiple font families
* fontFamily: ['Helvetica', 'Arial', 'sans-serif']
* ```
* @default 'Arial'
*/
fontFamily?: string | string[];
/**
* Font size in pixels or as string.
*
* Equivalents are '26px','20pt','160%' or '1.6em')
* @example
* ```ts
* // Numeric size
* fontSize: 26
* // String size
* fontSize: '26px'
* // Percentage size
* fontSize: '160%' // 1.6 times the parent element's font size
* // Em size
* fontSize: '1.6em' // 1.6 times the parent element's font size
* @default 26
*/
fontSize?: number | string;
/**
* Font style (normal, italic, oblique).
* @default 'normal'
*/
fontStyle?: TextStyleFontStyle;
/**
* Font variant (normal, small-caps).
* @default 'normal'
*/
fontVariant?: TextStyleFontVariant;
/**
* Font weight (normal, bold, bolder, lighter, 100-900).
* @default 'normal'
*/
fontWeight?: TextStyleFontWeight;
/** The height of the line, a number that represents the vertical space that a letter uses. */
leading?: number;
/** The amount of spacing between letters, default is 0 */
letterSpacing?: number;
/** The line height, a number that represents the vertical space that a letter uses */
lineHeight?: number;
/**
* Padding around the text.
*
* Occasionally some fonts are cropped. Adding some padding will prevent this from
* happening by adding padding to all sides of the text.
*/
padding?: number;
/**
* Stroke style for text outline.
* @default null
*/
stroke?: StrokeInput;
/**
* Vertical alignment baseline.
* @default 'alphabetic'
*/
textBaseline?: TextStyleTextBaseline;
/**
* Whether to trim transparent edges.
* > [!NOTE] This is an expensive operation and should only be used when necessary.
* @default false
*/
trim?: boolean;
/**
* How to handle whitespace.
*
* It needs wordWrap to be set to true for this to have an effect.
* @default 'pre'
*/
whiteSpace?: TextStyleWhiteSpace;
/** Indicates if word wrap should be used */
wordWrap?: boolean;
/** The width at which text will wrap, it needs wordWrap to be set to true */
wordWrapWidth?: number;
/**
* Array of filters to apply to the text.
*
* These filters will be applied to the text as it is created, resulting in faster rendering for static text
* compared to applying the filter directly to the text object (which would be applied at run time).
* @default undefined
*/
filters?: Filter[] | readonly Filter[];
}
/**
* A TextStyle Object contains information to decorate Text objects.
* An instance can be shared between multiple Text objects; then changing the style will update all text objects using it.
* @example
* ```ts
* // Create a basic text style
* const style = new TextStyle({
* fontFamily: ['Helvetica', 'Arial', 'sans-serif'],
* fontSize: 36,
* fill: 0xff1010,
* align: 'center'
* });
*
* // Create a rich text style with multiple features
* const richStyle = new TextStyle({
* fontFamily: 'Arial',
* fontSize: 32,
* fill: 'white',
* stroke: {
* color: '#4a1850',
* width: 5
* },
* dropShadow: {
* color: '#000000',
* blur: 4,
* distance: 6,
* angle: Math.PI / 6
* },
* wordWrap: true,
* wordWrapWidth: 440,
* lineHeight: 40,
* align: 'center'
* });
*
* // Share style between multiple text objects
* const text1 = new Text({
* text: 'Hello',
* style: richStyle
* });
*
* const text2 = new Text({
* text: 'World',
* style: richStyle
* });
*
* // Update style dynamically - affects all text objects
* richStyle.fontSize = 48;
* richStyle.fill = 0x00ff00;
* ```
*
* Key Features:
* - Shared styling between multiple text objects
* - Rich text formatting options
* - Gradient and pattern fills
* - Drop shadows and strokes
* - Word wrapping and alignment
* - Dynamic updates
* @category text
* @standard
*/
export declare class TextStyle extends EventEmitter<{
update: TextDropShadow;
}> {
/**
* Default drop shadow settings used when enabling drop shadows on text.
* These values are used as the base configuration when drop shadows are enabled without specific settings.
* @example
* ```ts
* // Customize default settings globally
* TextStyle.defaultDropShadow.alpha = 0.5; // 50% opacity for all shadows
* TextStyle.defaultDropShadow.blur = 2; // 2px blur for all shadows
* TextStyle.defaultDropShadow.color = 'blue'; // Blue shadows by default
* ```
*/
static defaultDropShadow: TextDropShadow;
/**
* Unique identifier for the TextStyle class.
* This is used to track instances and ensure uniqueness.
* @internal
*/
uid: number;
/**
* Internal tick counter used to track updates and changes.
* This is incremented whenever the style is modified, allowing for efficient change detection.
* @internal
*/
_tick: number;
/**
* Default text style settings used when creating new text objects.
* These values serve as the base configuration and can be customized globally.
* @example
* ```ts
* // Customize default text style globally
* TextStyle.defaultTextStyle.fontSize = 16;
* TextStyle.defaultTextStyle.fill = 0x333333;
* TextStyle.defaultTextStyle.fontFamily = ['Arial', 'Helvetica', 'sans-serif'];
* ```
*/
static defaultTextStyle: TextStyleOptions;
/** @internal */
_fill: ConvertedFillStyle;
private _originalFill;
/** @internal */
_stroke: ConvertedStrokeStyle;
private _originalStroke;
private _dropShadow;
private _fontFamily;
private _fontSize;
private _fontStyle;
private _fontVariant;
private _fontWeight;
private _breakWords;
private _align;
private _leading;
private _letterSpacing;
private _lineHeight;
private _textBaseline;
private _whiteSpace;
private _wordWrap;
private _wordWrapWidth;
private _filters;
private _padding;
private _trim;
constructor(style?: Partial<TextStyleOptions>);
/**
* Alignment for multiline text, does not affect single line text.
* @type {'left'|'center'|'right'|'justify'}
*/
get align(): TextStyleAlign;
set align(value: TextStyleAlign);
/** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */
get breakWords(): boolean;
set breakWords(value: boolean);
/** Set a drop shadow for the text. */
get dropShadow(): TextDropShadow;
set dropShadow(value: boolean | TextDropShadow);
/** The font family, can be a single font name, or a list of names where the first is the preferred font. */
get fontFamily(): string | string[];
set fontFamily(value: string | string[]);
/** The font size (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') */
get fontSize(): number;
set fontSize(value: string | number);
/**
* The font style.
* @type {'normal'|'italic'|'oblique'}
*/
get fontStyle(): TextStyleFontStyle;
set fontStyle(value: TextStyleFontStyle);
/**
* The font variant.
* @type {'normal'|'small-caps'}
*/
get fontVariant(): TextStyleFontVariant;
set fontVariant(value: TextStyleFontVariant);
/**
* The font weight.
* @type {'normal'|'bold'|'bolder'|'lighter'|'100'|'200'|'300'|'400'|'500'|'600'|'700'|'800'|'900'}
*/
get fontWeight(): TextStyleFontWeight;
set fontWeight(value: TextStyleFontWeight);
/** The space between lines. */
get leading(): number;
set leading(value: number);
/** The amount of spacing between letters, default is 0. */
get letterSpacing(): number;
set letterSpacing(value: number);
/** The line height, a number that represents the vertical space that a letter uses. */
get lineHeight(): number;
set lineHeight(value: number);
/**
* Occasionally some fonts are cropped. Adding some padding will prevent this from happening
* by adding padding to all sides of the text.
* > [!NOTE] This will NOT affect the positioning or bounds of the text.
*/
get padding(): number;
set padding(value: number);
/**
* An optional filter or array of filters to apply to the text, allowing for advanced visual effects.
* These filters will be applied to the text as it is created, resulting in faster rendering for static text
* compared to applying the filter directly to the text object (which would be applied at run time).
* @default null
*/
get filters(): readonly Filter[];
set filters(value: Filter[]);
/**
* Trim transparent borders from the text texture.
* > [!IMPORTANT] PERFORMANCE WARNING:
* > This is a costly operation as it requires scanning pixel alpha values.
* > Avoid using `trim: true` for dynamic text, as it could significantly impact performance.
*/
get trim(): boolean;
set trim(value: boolean);
/**
* The baseline of the text that is rendered.
* @type {'alphabetic'|'top'|'hanging'|'middle'|'ideographic'|'bottom'}
*/
get textBaseline(): TextStyleTextBaseline;
set textBaseline(value: TextStyleTextBaseline);
/**
* How newlines and spaces should be handled.
* Default is 'pre' (preserve, preserve).
*
* value | New lines | Spaces
* --- | --- | ---
* 'normal' | Collapse | Collapse
* 'pre' | Preserve | Preserve
* 'pre-line' | Preserve | Collapse
* @type {'normal'|'pre'|'pre-line'}
*/
get whiteSpace(): TextStyleWhiteSpace;
set whiteSpace(value: TextStyleWhiteSpace);
/** Indicates if word wrap should be used. */
get wordWrap(): boolean;
set wordWrap(value: boolean);
/** The width at which text will wrap, it needs wordWrap to be set to true. */
get wordWrapWidth(): number;
set wordWrapWidth(value: number);
/**
* The fill style that will be used to color the text.
* This can be:
* - A color string like 'red', '#00FF00', or 'rgba(255,0,0,0.5)'
* - A hex number like 0xff0000 for red
* - A FillStyle object with properties like { color: 0xff0000, alpha: 0.5 }
* - A FillGradient for gradient fills
* - A FillPattern for pattern/texture fills
*
* When using a FillGradient, vertical gradients (angle of 90 degrees) are applied per line of text,
* while gradients at any other angle are spread across the entire text body as a whole.
* @example
* // Vertical gradient applied per line
* const verticalGradient = new FillGradient(0, 0, 0, 1)
* .addColorStop(0, 0xff0000)
* .addColorStop(1, 0x0000ff);
*
* const text = new Text({
* text: 'Line 1\nLine 2',
* style: { fill: verticalGradient }
* });
*
* To manage the gradient in a global scope, set the textureSpace property of the FillGradient to 'global'.
* @type {string|number|FillStyle|FillGradient|FillPattern}
*/
get fill(): FillInput;
set fill(value: FillInput);
/** A fillstyle that will be used on the text stroke, e.g., 'blue', '#FCFF00'. */
get stroke(): StrokeInput;
set stroke(value: StrokeInput);
update(): void;
/** Resets all properties to the default values */
reset(): void;
/**
* Returns a unique key for this instance.
* This key is used for caching.
* @returns {string} Unique key for the instance
*/
get styleKey(): string;
/**
* Creates a new TextStyle object with the same values as this one.
* @returns New cloned TextStyle object
*/
clone(): TextStyle;
/**
* Returns the final padding for the text style, taking into account any filters applied.
* Used internally for correct measurements
* @internal
* @returns {number} The final padding for the text style.
*/
_getFinalPadding(): number;
/**
* Destroys this text style.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* // Destroy the text style and its textures
* textStyle.destroy({ texture: true, textureSource: true });
* textStyle.destroy(true);
*/
destroy(options?: TypeOrBool<TextureDestroyOptions>): void;
private _createProxy;
private _isFillStyle;
}
/**
* Options for HTML text style, extends standard text styling with HTML-specific capabilities.
* Omits certain base text properties that don't apply to HTML rendering.
* @example
* ```ts
* // Basic HTML text style
* const text = new HTMLText({
* text: '<p>Hello World</p>',
* style: {
* fontSize: 24,
* fill: '#ff0000',
* fontFamily: 'Arial',
* align: 'center'
* }
* });
*
* // Custom tag styling
* const taggedText = new HTMLText({
* text: '<custom>Custom Tag</custom>',
* style: {
* fontSize: 16,
* tagStyles: {
* custom: {
* fontSize: 32,
* fill: '#00ff00',
* fontStyle: 'italic'
* }
* }
* }
* });
* ```
* @category text
* @standard
*/
export interface HTMLTextStyleOptions extends Omit<TextStyleOptions, "leading" | "textBaseline" | "trim" | "filters"> {
/**
* List of CSS style overrides to apply to the HTML text.
* These styles are added after the built-in styles and can override any default styling.
* @advanced
*/
cssOverrides?: string[];
/**
* Custom styles to apply to specific HTML tags.
* Allows for consistent styling of custom elements without CSS overrides.
* @example
* ```ts
* const text = new HTMLText({
* text: `
* <red>Main Title</red>
* <grey>The subtitle</grey>
* <blue>Regular content text</blue>
* `,
* style: {
* tagStyles: {
* red: {
* fill: '#ff0000',
* },
* grey: {
* fill: '#666666',
* },
* blue: {
* fill: 'blue',
* }
* }
* }
* });
* ```
* @standard
*/
tagStyles?: Record<string, HTMLTextStyleOptions>;
}
/**
* A TextStyle object rendered by the HTMLTextSystem.
* @category text
*/
export declare class HTMLTextStyle extends TextStyle {
private _cssOverrides;
private _cssStyle;
/**
* Custom styles to apply to specific HTML tags.
* Allows for consistent styling of custom elements without CSS overrides.
* @example
* new HTMLText({
* text:'<red>Red</red>,<blue>Blue</blue>,<green>Green</green>',
* style:{
* fontFamily: 'DM Sans',
* fill: 'white',
* fontSize:100,
* tagStyles:{
* red:{
* fill:'red',
* },
* blue:{
* fill:'blue',
* },
* green:{
* fill:'green',
* }
* }
* }
* );
* @standard
*/
tagStyles: Record<string, HTMLTextStyleOptions>;
constructor(options?: HTMLTextStyleOptions);
/**
* List of CSS style overrides to apply to the HTML text.
* These styles are added after the built-in styles and can override any default styling.
* @advanced
*/
set cssOverrides(value: string | string[]);
/** @advanced */
get cssOverrides(): string[];
/**
* Updates the text style and triggers a refresh of the CSS style cache.
* This method is called automatically when style properties are changed.
* @example
* ```ts
* // Update after multiple changes
* const text = new HTMLText({
* text: 'Hello World',
* style
* });
*
* style.fontSize = 32;
* style.fill = '#00ff00';
* style.fontFamily = 'Arial';
* style.update(); // Apply all changes at once
* ```
* @advanced
* @see {@link HTMLTextStyle#cssStyle} For accessing the generated CSS
* @see {@link HTMLTextStyle#cssOverrides} For managing CSS overrides
*/
update(): void;
/**
* Creates a new HTMLTextStyle object with the same values as this one.
* This creates a deep copy of all style properties, including dropShadow and tag styles.
* @example
* ```ts
* // Create original style
* const originalStyle = new HTMLTextStyle({
* fontSize: 24,
* fill: '#ff0000',
* tagStyles: {
* header: { fontSize: 32, fill: '#00ff00' }
* }
* });
*
* // Clone the style
* const clonedStyle = originalStyle.clone();
*
* // Modify cloned style independently
* clonedStyle.fontSize = 36;
* clonedStyle.fill = '#0000ff';
*
* // Original style remains unchanged
* console.log(originalStyle.fontSize); // Still 24
* console.log(originalStyle.fill); // Still '#ff0000'
* ```
*
* Properties that are cloned:
* - Basic text properties (fontSize, fontFamily, etc.)
* - Fill and stroke styles
* - Drop shadow configuration
* - CSS overrides
* - Tag styles (deep copied)
* - Word wrap settings
* - Alignment and spacing
* @returns {HTMLTextStyle} A new HTMLTextStyle instance with the same properties
* @see {@link HTMLTextStyle} For available style properties
* @see {@link HTMLTextStyle#cssOverrides} For CSS override handling
* @see {@link HTMLTextStyle#tagStyles} For tag style configuration
* @standard
*/
clone(): HTMLTextStyle;
/**
* The CSS style string that will be applied to the HTML text.
* @advanced
*/
get cssStyle(): string;
/**
* Add a style override, this can be any CSS property
* it will override any built-in style. This is the
* property and the value as a string (e.g., `color: red`).
* This will override any other internal style.
* @param {string} value - CSS style(s) to add.
* @example
* style.addOverride('background-color: red');
* @advanced
*/
addOverride(...value: string[]): void;
/**
* Remove any overrides that match the value.
* @param {string} value - CSS style to remove.
* @example
* style.removeOverride('background-color: red');
* @advanced
*/
removeOverride(...value: string[]): void;
/**
* Sets the fill style for the text. HTML text only supports color fills (string or number values).
* Texture fills are not supported and will trigger a warning in debug mode.
* @example
* ```ts
* // Using hex colors
* const text = new HTMLText({
* text: 'Colored Text',
* style: {
* fill: 0xff0000 // Red color
* }
* });
*
* // Using CSS color strings
* text.style.fill = '#00ff00'; // Hex string (Green)
* text.style.fill = 'blue'; // Named color
* text.style.fill = 'rgb(255,0,0)' // RGB
* text.style.fill = '#f0f'; // Short hex
*
* // Invalid usage (will trigger warning in debug)
* text.style.fill = {
* type: 'pattern',
* texture: Texture.from('pattern.png')
* }; // Not supported, falls back to default
* ```
* @param value - The fill color to use. Must be a string or number.
* @throws {Warning} In debug mode when attempting to use unsupported fill types
* @see {@link TextStyle#fill} For full fill options in canvas text
* @standard
*/
set fill(value: FillInput);
/**
* Sets the stroke style for the text. HTML text only supports color strokes (string or number values).
* Texture strokes are not supported and will trigger a warning in debug mode.
* @example
* ```ts
* // Using hex colors
* const text = new HTMLText({
* text: 'Outlined Text',
* style: {
* stroke: 0xff0000 // Red outline
* }
* });
*
* // Using CSS color strings
* text.style.stroke = '#00ff00'; // Hex string (Green)
* text.style.stroke = 'blue'; // Named color
* text.style.stroke = 'rgb(255,0,0)' // RGB
* text.style.stroke = '#f0f'; // Short hex
*
* // Using stroke width
* text.style = {
* stroke: {
* color: '#ff0000',
* width: 2
* }
* };
*
* // Remove stroke
* text.style.stroke = null;
*
* // Invalid usage (will trigger warning in debug)
* text.style.stroke = {
* type: 'pattern',
* texture: Texture.from('pattern.png')
* }; // Not supported, falls back to default
* ```
* @param value - The stroke style to use. Must be a string, number, or stroke configuration object
* @throws {Warning} In debug mode when attempting to use unsupported stroke types
* @see {@link TextStyle#stroke} For full stroke options in canvas text
* @standard
*/
set stroke(value: StrokeInput);
}
/**
* A string or number that can be used as text.
* @example
* ```ts
* const text: TextString = 'Hello Pixi!';
* const text2: TextString = 12345;
* const text3: TextString = { toString: () => 'Hello Pixi!' };
* ```
* @category text
* @standard
*/
export type TextString = string | number | {
toString: () => string;
};
/**
* A union of all text styles, including HTML, Bitmap and Canvas text styles.
* This is used to allow for any text style to be passed to a text object.
* @example
* ```ts
* import { TextStyle, HTMLTextStyle } from 'pixi.js';
* const style: AnyTextStyle = new TextStyle({ fontSize: 24 });
* const htmlStyle: AnyTextStyle = new HTMLTextStyle({ fontSize: '24px' });
* ```
* @category text
* @standard
* @see TextStyle
* @see HTMLTextStyle
*/
export type AnyTextStyle = TextStyle | HTMLTextStyle;
/**
* A union of all text style options, including HTML, Bitmap and Canvas text style options.
* This is used to allow for any text style options to be passed to a text object.
* @example
* ```ts
* import { TextStyleOptions, HTMLTextStyleOptions } from 'pixi.js';
* const styleOptions: AnyTextStyleOptions = { fontSize: 24 } as TextStyleOptions;
* const htmlStyleOptions: AnyTextStyleOptions = { fontSize: '24px' } as HTMLTextStyleOptions;
* ```
* @category text
* @standard
* @see TextStyleOptions
* @see HTMLTextStyleOptions
*/
export type AnyTextStyleOptions = TextStyleOptions | HTMLTextStyleOptions;
/**
* Options for creating text objects in PixiJS. This interface defines the common properties
* used across different text rendering implementations (Canvas, HTML, and Bitmap).
* @example
* ```ts
* // Create basic text with minimal options
* const basicText = new Text({
* text: 'Hello Pixi!',
* style: {
* fontSize: 24,
* fill: 0xff1010
* }
* });
*
* // Create text with advanced styling
* const styledText = new Text({
* text: 'Styled Text',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: new FillGradient({
* end: { x: 1, y: 1 },
* stops: [
* { color: 0xff0000, offset: 0 }, // Red at start
* { color: 0x0000ff, offset: 1 }, // Blue at end
* ]
* }),
* stroke: { color: '#4a1850', width: 5 },
* dropShadow: {
* color: '#000000',
* blur: 4,
* distance: 6
* },
* align: 'center'
* },
* anchor: 0.5,
* resolution: window.devicePixelRatio
* });
*
* // Create multiline text with word wrap
* const wrappedText = new Text({
* text: 'This is a long piece of text that will wrap onto multiple lines',
* style: {
* fontSize: 20,
* wordWrap: true,
* wordWrapWidth: 200,
* lineHeight: 30
* },
* resolution: 2,
* roundPixels: true
* });
* ```
* @category text
* @standard
* @noInheritDoc
*/
export interface TextOptions<TEXT_STYLE extends TextStyle = TextStyle, TEXT_STYLE_OPTIONS extends TextStyleOptions = TextStyleOptions> extends PixiMixins.TextOptions, ViewContainerOptions {
/**
* The anchor point of the text that controls the origin point for positioning and rotation.
* Can be a number (same value for x/y) or a PointData object.
* - (0,0) is top-left
* - (0.5,0.5) is center
* - (1,1) is bottom-right
* ```ts
* // Set anchor to center
* const text = new Text({
* text: 'Hello Pixi!',
* anchor: 0.5 // Same as { x: 0.5, y: 0.5 }
* });
* // Set anchor to top-left
* const text2 = new Text({
* text: 'Hello Pixi!',
* anchor: { x: 0, y: 0 } // Top-left corner
* });
* // Set anchor to bottom-right
* const text3 = new Text({
* text: 'Hello Pixi!',
* anchor: { x: 1, y: 1 } // Bottom-right corner
* });
* ```
* @default { x: 0, y: 0 }
*/
anchor?: PointData | number;
/**
* The text content to display. Use '\n' for line breaks.
* Accepts strings, numbers, or objects with toString() method.
* @example
* ```ts
* const text = new Text({
* text: 'Hello Pixi!',
* });
* const multilineText = new Text({
* text: 'Line 1\nLine 2\nLine 3',
* });
* const numberText = new Text({
* text: 12345, // Will be converted to '12345'
* });
* const objectText = new Text({
* text: { toString: () => 'Object Text' }, // Custom toString
* });
* ```
* @default ''
*/
text?: TextString;
/**
* The resolution/device pixel ratio for rendering.
* Higher values result in sharper text at the cost of performance.
* Set to null for auto-resolution based on device.
* @example
* ```ts
* const text = new Text({
* text: 'Hello Pixi!',
* resolution: 2 // High DPI for sharper text
* });
* const autoResText = new Text({
* text: 'Auto Resolution',
* resolution: null // Use device's pixel ratio
* });
* ```
* @default null
*/
resolution?: number;
/**
* The style configuration for the text.
* Can be a TextStyle instance or a configuration object.
* Supports canvas text styles, HTML text styles, and bitmap text styles.
* @example
* ```ts
* const text = new Text({
* text: 'Styled Text',
* style: {
* fontSize: 24,
* fill: 0xff1010, // Red color
* fontFamily: 'Arial',
* align: 'center', // Center alignment
* stroke: { color: '#4a1850', width: 5 }, // Purple stroke
* dropShadow: {
* color: '#000000', // Black shadow
* blur: 4, // Shadow blur
* distance: 6 // Shadow distance
* }
* }
* });
* const htmlText = new HTMLText({
* text: 'HTML Styled Text',
* style: {
* fontSize: '20px',
* fill: 'blue',
* fontFamily: 'Verdana',
* }
* });
* const bitmapText = new BitmapText({
* text: 'Bitmap Styled Text',
* style: {
* fontName: 'Arial',
* fontSize: 32,
* }
* })
*/
style?: TEXT_STYLE | TEXT_STYLE_OPTIONS;
/**
* Whether to round the x/y position to whole pixels.
* Enabling can prevent anti-aliasing of text edges but may cause slight position shifting.
* @example
* ```ts
* const text = new Text({
* text: 'Rounded Text',
* roundPixels: true // Rounds position to whole pixels
* });
* @default false
*/
roundPixels?: boolean;
}
/**
* An abstract Text class, used by all text type in Pixi. This includes Canvas, HTML, and Bitmap Text.
* @see Text
* @see BitmapText
* @see HTMLText
* @category text
* @advanced
*/
export declare abstract class AbstractText<TEXT_STYLE extends TextStyle = TextStyle, TEXT_STYLE_OPTIONS extends TextStyleOptions = TextStyleOptions, TEXT_OPTIONS extends TextOptions<TEXT_STYLE, TEXT_STYLE_OPTIONS> = TextOptions<TEXT_STYLE, TEXT_STYLE_OPTIONS>, GPU_DATA extends {
destroy: () => void;
} = any> extends ViewContainer<GPU_DATA> implements View {
/** @internal */
batched: boolean;
/** @internal */
_anchor: ObservablePoint;
/** @internal */
_resolution: number;
/** @internal */
_autoResolution: boolean;
/** @internal */
_style: TEXT_STYLE;
/** @internal */
_didTextUpdate: boolean;
protected _text: string;
private readonly _styleClass;
constructor(options: TEXT_OPTIONS, styleClass: new (options: TEXT_STYLE_OPTIONS) => TEXT_STYLE);
/**
* The anchor point of the text that controls the origin point for positioning and rotation.
* Can be a number (same value for x/y) or a PointData object.
* - (0,0) is top-left
* - (0.5,0.5) is center
* - (1,1) is bottom-right
* ```ts
* // Set anchor to center
* const text = new Text({
* text: 'Hello Pixi!',
* anchor: 0.5 // Same as { x: 0.5, y: 0.5 }
* });
* // Set anchor to top-left
* const text2 = new Text({
* text: 'Hello Pixi!',
* anchor: { x: 0, y: 0 } // Top-left corner
* });
* // Set anchor to bottom-right
* const text3 = new Text({
* text: 'Hello Pixi!',
* anchor: { x: 1, y: 1 } // Bottom-right corner
* });
* ```
* @default { x: 0, y: 0 }
*/
get anchor(): ObservablePoint;
set anchor(value: PointData | number);
/**
* The text content to display. Use '\n' for line breaks.
* Accepts strings, numbers, or objects with toString() method.
* @example
* ```ts
* const text = new Text({
* text: 'Hello Pixi!',
* });
* const multilineText = new Text({
* text: 'Line 1\nLine 2\nLine 3',
* });
* const numberText = new Text({
* text: 12345, // Will be converted to '12345'
* });
* const objectText = new Text({
* text: { toString: () => 'Object Text' }, // Custom toString
* });
*
* // Update text dynamically
* text.text = 'Updated Text'; // Re-renders with new text
* text.text = 67890; // Updates to '67890'
* text.text = { toString: () => 'Dynamic Text' }; // Uses custom toString method
* // Clear text
* text.text = ''; // Clears the text
* ```
* @default ''
*/
set text(value: TextString);
get text(): string;
/**
* The resolution/device pixel ratio for rendering.
* Higher values result in sharper text at the cost of performance.
* Set to null for auto-resolution based on device.
* @example
* ```ts
* const text = new Text({
* text: 'Hello Pixi!',
* resolution: 2 // High DPI for sharper text
* });
* const autoResText = new Text({
* text: 'Auto Resolution',
* resolution: null // Use device's pixel ratio
* });
* ```
* @default null
*/
set resolution(value: number);
get resolution(): number;
get style(): TEXT_STYLE;
/**
* The style configuration for the text.
* Can be a TextStyle instance or a configuration object.
* Supports canvas text styles, HTML text styles, and bitmap text styles.
* @example
* ```ts
* const text = new Text({
* text: 'Styled Text',
* style: {
* fontSize: 24,
* fill: 0xff1010, // Red color
* fontFamily: 'Arial',
* align: 'center', // Center alignment
* stroke: { color: '#4a1850', width: 5 }, // Purple stroke
* dropShadow: {
* color: '#000000', // Black shadow
* blur: 4, // Shadow blur
* distance: 6 // Shadow distance
* }
* }
* });
* const htmlText = new HTMLText({
* text: 'HTML Styled Text',
* style: {
* fontSize: '20px',
* fill: 'blue',
* fontFamily: 'Verdana',
* }
* });
* const bitmapText = new BitmapText({
* text: 'Bitmap Styled Text',
* style: {
* fontName: 'Arial',
* fontSize: 32,
* }
* })
*
* // Update style dynamically
* text.style = {
* fontSize: 30, // Change font size
* fill: 0x00ff00, // Change color to green
* align: 'right', // Change alignment to right
* stroke: { color: '#000000', width: 2 }, // Add black stroke
* }
*/
set style(style: TEXT_STYLE | Partial<TEXT_STYLE> | TEXT_STYLE_OPTIONS);
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set.
* @example
* ```ts
* // Set width directly
* texture.width = 200;
* console.log(texture.scale.x); // Scale adjusted to match width
*
* // For better performance when setting both width and height
* texture.setSize(300, 400); // Avoids recalculating bounds twice
* ```
*/
get width(): number;
set width(value: number);
/**
* The height of the sprite, setting this will actually modify the scale to achieve the value set.
* @example
* ```ts
* // Set height directly
* texture.height = 200;
* console.log(texture.scale.y); // Scale adjusted to match height
*
* // For better performance when setting both width and height
* texture.setSize(300, 400); // Avoids recalculating bounds twice
* ```
*/
get height(): number;
set height(value: number);
/**
* Retrieves the size of the Text as a [Size]{@link Size} object based on the texture dimensions and scale.
* This is faster than getting width and height separately as it only calculates the bounds once.
* @example
* ```ts
* // Basic size retrieval
* const text = new Text({
* text: 'Hello Pixi!',
* style: { fontSize: 24 }
* });
* const size = text.getSize();
* console.log(`Size: ${size.width}x${size.height}`);
*
* // Reuse existing size object
* const reuseSize = { width: 0, height: 0 };
* text.getSize(reuseSize);
* ```
* @param out - Optional object to store the size in, to avoid allocating a new object
* @returns The size of the Sprite
* @see {@link Text#width} For getting just the width
* @see {@link Text#height} For getting just the height
* @see {@link Text#setSize} For setting both width and height
*/
getSize(out?: Size): Size;
/**
* Sets the size of the Text to the specified width and height.
* This is faster than setting width and height separately as it only recalculates bounds once.
* @example
* ```ts
* // Basic size setting
* const text = new Text({
* text: 'Hello Pixi!',
* style: { fontSize: 24 }
* });
* text.setSize(100, 200); // Width: 100, Height: 200
*
* // Set uniform size
* text.setSize(100); // Sets both width and height to 100
*
* // Set size with object
* text.setSize({
* width: 200,
* height: 300
* });
* ```
* @param value - This can be either a number or a {@link Size} object
* @param height - The height to set. Defaults to the value of `width` if not provided
* @see {@link Text#width} For setting width only
* @see {@link Text#height} For setting height only
*/
setSize(value: number | Optional<Size, "height">, height?: number): void;
/**
* Checks if the object contains the given point in local coordinates.
* Uses the text's bounds for hit testing.
* @example
* ```ts
* // Basic point check
* const localPoint = { x: 50, y: 25 };
* const contains = text.containsPoint(localPoint);
* console.log('Point is inside:', contains);
* ```
* @param point - The point to check in local coordinates
* @returns True if the point is within the text's bounds
* @see {@link Container#toLocal} For converting global coordinates to local
*/
containsPoint(point: PointData): boolean;
/** @internal */
onViewUpdate(): void;
/**
* Destroys this text renderable and optionally its style texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* // Destroys the text and its style
* text.destroy({ style: true, texture: true, textureSource: true });
* text.destroy(true);
* text.destroy() // Destroys the text, but not its style
*/
destroy(options?: DestroyOptions): void;
/**
* Returns a unique key for this instance.
* This key is used for caching.
* @returns {string} Unique key for the instance
*/
get styleKey(): string;
}
/**
* Helper function to ensure consistent handling of text options across different text classes.
* This function handles both the new options object format and the deprecated parameter format.
* @example
* // New recommended way:
* const options = ensureTextOptions([{
* text: "Hello",
* style: { fontSize: 20 }
* }], "Text");
*
* // Deprecated way (will show warning in debug):
* const options = ensureTextOptions(["Hello", { fontSize: 20 }], "Text");
* @param args - Arguments passed to text constructor
* @param name - Name of the text class (used in deprecation warning)
* @returns Normalized text options object
* @template TEXT_OPTIONS - The type of the text options
* @internal
*/
export declare function ensureTextOptions<TEXT_OPTIONS extends TextOptions>(args: any[], name: string): TEXT_OPTIONS;
/** @internal */
export declare class BatchableText extends BatchableSprite {
currentKey: string;
}
interface Text$1 extends PixiMixins.Text, AbstractText<TextStyle, TextStyleOptions, CanvasTextOptions, BatchableText> {
}
/**
* Constructor options used for `Text` instances. These options extend TextOptions with
* canvas-specific features like texture styling.
* @example
* ```ts
* // Create basic canvas text
* const text = new Text({
* text: 'Hello Pixi!',
* style: {
* fontSize: 24,
* fill: 0xff1010,
* }
* });
*
* // Create text with custom texture style
* const customText = new Text({
* text: 'Custom Text',
* style: {
* fontSize: 32,
* fill: 0x4a4a4a
* },
* textureStyle: {
* scaleMode: 'nearest',
* }
* });
* ```
* @extends TextOptions
* @category text
* @standard
*/
export interface CanvasTextOptions extends TextOptions {
/**
* Optional texture style to use for the text texture. This allows fine control over
* how the text is rendered to a texture before being displayed.
*
* The texture style can affect:
* - Scale mode (nearest/linear)
* - Resolution
* - Format (rgb/rgba)
* - Alpha handling
* @example
* ```ts
* const text = new Text({
* text: 'Crisp Text',
* textureStyle: {
* scaleMode: 'nearest', // Pixel-perfect scaling
* }
* });
* ```
* @advanced
*/
textureStyle?: TextureStyle | TextureStyleOptions;
}
/**
* A powerful text rendering class that creates one or multiple lines of text using the Canvas API.
* Provides rich text styling capabilities with runtime modifications.
*
* Key features:
* - Dynamic text content and styling
* - Multi-line text support
* - Word wrapping
* - Custom texture styling
* - High-quality text rendering
* @example
* ```ts
* import { Text } from 'pixi.js';
*
* // Basic text creation
* const basicText = new Text({
* text: 'Hello Pixi!',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* }
* });
*
* // Rich text with multiple styles
* const richText = new Text({
* text: 'Styled\nMultiline\nText',
* style: {
* fontFamily: 'Arial',
* fontSize: 36,
* fill: 'red',
* stroke: { color: '#4a1850', width: 5 },
* align: 'center',
* lineHeight: 45,
* dropShadow: {
* color: '#000000',
* blur: 4,
* distance: 6,
* }
* },
* anchor: 0.5,
* });
*
* // Text with custom texture settings
* const crispText = new Text({
* text: 'High Quality Text',
* style: {
* fontSize: 24,
* fill: 0x4a4a4a,
* },
* textureStyle: {
* scaleMode: 'nearest',
* }
* });
*
* // Word-wrapped text
* const wrappedText = new Text({
* text: 'This is a long piece of text that will automatically wrap to multiple lines',
* style: {
* fontSize: 20,
* wordWrap: true,
* wordWrapWidth: 200,
* lineHeight: 30,
* }
* });
* ```
*
* Performance Considerations:
* - Each text instance creates its own texture
* - Texture is regenerated when text or style changes
* - Use BitmapText for better performance with static text
* - Consider texture style options for quality vs performance tradeoffs
* @category text
* @standard
* @see {@link TextStyle} For detailed style options
* @see {@link BitmapText} For better performance with static text
* @see {@link HTMLText} For HTML/CSS-based text rendering
*/
declare class Text$1 extends AbstractText<TextStyle, TextStyleOptions, CanvasTextOptions, BatchableText> implements View {
/** @internal */
readonly renderPipeId: string;
/**
* Optional texture style to use for the text.
* > [!NOTE] Text is not updated when this property is updated,
* > you must update the text manually by calling `text.onViewUpdate()`
* @advanced
*/
textureStyle?: TextureStyle;
/**
* @param {CanvasTextOptions} options - The options of the text.
*/
constructor(options?: CanvasTextOptions);
/** @deprecated since 8.0.0 */
constructor(text?: TextString, options?: Partial<TextStyle>);
/** @private */
protected updateBounds(): void;
}
/**
* The accepted types to pass to the prepare system
* @category rendering
* @advanced
*/
export type PrepareSourceItem = Container | TextureSource | Texture | GraphicsContext;
/**
* The valid types resolved to the queue ready for upload
* @category rendering
* @advanced
*/
export type PrepareQueueItem = TextureSource | Text$1 | GraphicsContext;
/**
* Part of the prepare system. Responsible for uploading all the items to the GPU.
* This class provides the base functionality and handles processing the queue asynchronously.
* @category rendering
* @advanced
*/
export declare abstract class PrepareBase {
/** The number of uploads to process per frame */
static uploadsPerFrame: number;
/** Reference to the renderer */
protected renderer: Renderer;
/** The queue to process over a async timer */
protected queue: PrepareQueueItem[];
/** Collection of callbacks to call when the uploads are finished */
protected resolves: ((value: void | PromiseLike<void>) => void)[];
/** Timeout id for next processing call */
protected timeout?: number;
private _destroyed;
/**
* @param {Renderer} renderer - A reference to the current renderer
*/
constructor(renderer: Renderer);
/** Resolve the given resource type and return an item for the queue */
protected abstract resolveQueueItem(source: PrepareSourceItem, queue: PrepareQueueItem[]): void;
protected abstract uploadQueueItem(item: PrepareQueueItem): void;
/**
* Return a copy of the queue
* @returns {PrepareQueueItem[]} The queue
*/
getQueue(): PrepareQueueItem[];
/**
* Add a textures or graphics resource to the queue
* @param {PrepareSourceItem | PrepareSourceItem[]} resource
*/
add(resource: PrepareSourceItem | PrepareSourceItem[]): this;
/**
* Recursively add a container and its children to the queue
* @param {Container} container - The container to add to the queue
*/
private _addContainer;
/**
* Upload all the textures and graphics to the GPU (optionally add more resources to the queue first)
* @param {PrepareSourceItem | PrepareSourceItem[] | undefined} resource
*/
upload(resource?: PrepareSourceItem | PrepareSourceItem[]): Promise<void>;
/** eliminate duplicates before processing */
dedupeQueue(): void;
destroy(): void;
/** called per frame by the ticker, defer processing to next tick */
private readonly _tick;
/** process the queue up to max item limit per frame */
private readonly _processQueue;
/** Call all the resolve callbacks */
private _resolve;
}
declare global {
namespace PixiMixins {
interface RendererSystems {
/**
* The prepare mixin provides methods to prepare display objects for rendering.
* It is used to ensure that textures and other resources are ready before rendering.
* @category rendering
* @advanced
*/
prepare: PrepareBase;
}
}
}
declare global {
namespace PixiMixins {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ICanvas {
}
interface RendererOptions {
resolution?: number;
failIfMajorPerformanceCaveat?: boolean;
roundPixels?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGLOptions {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGPUOptions {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface RendererSystems {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGLSystems {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGPUSystems {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface CanvasSystems {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface RendererPipes {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGLPipes {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface WebGPUPipes {
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface CanvasPipes {
}
}
}
declare global {
namespace PixiMixins {
interface RendererSystems {
graphicsContext: GraphicsContextSystem;
}
interface RendererPipes {
graphics: GraphicsPipe;
}
interface RendererOptions {
/**
* A value from 0 to 1 that controls the smoothness of bezier curves (the higher the smoother)
* @default 0.5
*/
bezierSmoothness: number;
}
}
}
/**
* Options for the mesh geometry.
* @category scene
* @advanced
*/
export interface MeshGeometryOptions {
/** The positions of the mesh. */
positions?: Float32Array;
/** The UVs of the mesh. If not provided, they will be filled with 0 and match the size of the positions. */
uvs?: Float32Array;
/** The indices of the mesh. */
indices?: Uint32Array;
/** The topology of the mesh. */
topology?: Topology;
/** Whether to shrink the buffers to fit the data. */
shrinkBuffersToFit?: boolean;
}
/**
* A geometry used to batch multiple meshes with the same texture.
* @category scene
* @advanced
*/
export declare class MeshGeometry extends Geometry {
static defaultOptions: MeshGeometryOptions;
batchMode: BatchMode;
/**
* @param {MeshGeometryOptions} options - The options of the mesh geometry.
*/
constructor(options: MeshGeometryOptions);
/** @deprecated since 8.0.0 */
constructor(positions: Float32Array, uvs: Float32Array, indices: Uint32Array);
/** The positions of the mesh. */
get positions(): Float32Array;
/**
* Set the positions of the mesh.
* When setting the positions, its important that the uvs array is at least as long as the positions array.
* otherwise the geometry will not be valid.
* @param {Float32Array} value - The positions of the mesh.
*/
set positions(value: Float32Array);
/** The UVs of the mesh. */
get uvs(): Float32Array;
/**
* Set the UVs of the mesh.
* Its important that the uvs array you set is at least as long as the positions array.
* otherwise the geometry will not be valid.
* @param {Float32Array} value - The UVs of the mesh.
*/
set uvs(value: Float32Array);
/** The indices of the mesh. */
get indices(): Uint32Array;
set indices(value: Uint32Array);
}
/**
* A batchable mesh object.
* @ignore
*/
export declare class BatchableMesh implements DefaultBatchableMeshElement {
batcherName: string;
_topology: Topology;
readonly packAsQuad = false;
location: number;
renderable: ViewContainer;
indexOffset: number;
attributeOffset: number;
texture: Texture;
geometry: MeshGeometry;
transform: Matrix;
roundPixels: 0 | 1;
_attributeStart: number;
_batcher: Batcher;
_batch: Batch;
_indexStart: number;
_textureId: number;
_textureMatrixUpdateId: number;
private _transformedUvs;
private _uvUpdateId;
get blendMode(): BLEND_MODES;
get topology(): Topology;
set topology(value: Topology);
reset(): void;
/**
* Sets the texture for the batchable mesh.
* As it does so, it resets the texture matrix update ID.
* this is to ensure that the texture matrix is recalculated when the uvs are referenced
* @param value - The texture to set.
*/
setTexture(value: Texture): void;
get uvs(): Float32Array;
get positions(): Float32Array;
get indices(): Uint32Array;
get color(): number;
get groupTransform(): Matrix;
get attributeSize(): number;
get indexSize(): number;
}
/**
* Does exactly the same as getGlobalBounds, but does instead makes use of transforming AABBs
* of the various children within the scene graph. This is much faster, but less accurate.
*
* Deprecated, use container.getFastGlobalBounds() instead.
*
* the result will never be smaller - only ever slightly larger (in most cases, it will be the same).
* @param target - The target container to get the bounds from
* @param bounds - The output bounds object.
* @returns The bounds.
* @deprecated since 8.7.0
* @see container.getFastGlobalBounds
* @internal
*/
export declare function getFastGlobalBounds(target: Container, bounds: Bounds): Bounds;
/**
* Gets the global bounds of a container, including all its children
* @param target - The target container to get the bounds from
* @param skipUpdateTransform - If true, the transform will not be updated before calculating bounds.
* @param bounds - The output bounds object.
* @returns The bounds.
* @internal
*/
export declare function getGlobalBounds(target: Container, skipUpdateTransform: boolean, bounds: Bounds): Bounds;
/**
* @param target
* @param parentTransform
* @internal
*/
export declare function updateTransformBackwards(target: Container, parentTransform: Matrix): Matrix;
/**
* @param target
* @param bounds
* @param relativeMatrix
* @internal
*/
export declare function getLocalBounds(target: Container, bounds: Bounds, relativeMatrix?: Matrix): Bounds;
/**
* @param renderables
* @param bounds
* @internal
*/
export declare function getGlobalRenderableBounds(renderables: Renderable[], bounds: Bounds): Bounds;
type MatrixPoolItem = Matrix & PoolItem;
type BoundsPoolItem = Bounds & PoolItem;
/** @internal */
export declare const matrixPool: Pool<MatrixPoolItem>;
/** @internal */
export declare const boundsPool: Pool<BoundsPoolItem>;
/** @ignore */
export interface CacheAsTextureMixinConstructor {
cacheAsTexture?: (val: boolean | CacheAsTextureOptions) => void;
}
/**
* The CacheAsTextureMixin interface provides methods and properties for caching a container as a texture.
* This can improve rendering performance for complex static containers by allowing them to be rendered as a single texture.
* It includes methods to enable or disable caching, update the cached texture, and check
* 1if the container is currently cached.
* @category scene
* @advanced
*/
export interface CacheAsTextureMixin extends Required<CacheAsTextureMixinConstructor> {
/**
* Caches this container as a texture. This allows the container to be rendered as a single texture,
* which can improve performance for complex static containers.
* @example
* ```ts
* // Basic caching
* container.cacheAsTexture(true);
*
* // With custom options
* container.cacheAsTexture({
* resolution: 2,
* antialias: true,
* });
*
* // Disable caching
* container.cacheAsTexture(false);
*
* // Cache a complex UI
* const ui = new Container();
* // Add multiple children...
* ui.cacheAsTexture(true);
* ui.updateCacheTexture(); // Update if contents change
* ```
* @param val - If true, enables caching with default options.
* If false, disables caching.
* Can also pass options object to configure caching behavior.
* @see {@link Container#updateCacheTexture} For updating cached content
* @see {@link Container#isCachedAsTexture} For checking cache state
*/
cacheAsTexture: (val: boolean | CacheAsTextureOptions) => void;
/**
* Updates the cached texture of this container. This will flag the container's cached texture
* to be redrawn on the next render.
* @example
* ```ts
* // Basic update after changes
* container.updateCacheTexture();
* ```
*/
updateCacheTexture: () => void;
/**
* Legacy property for backwards compatibility with PixiJS v7 and below.
* Use `cacheAsTexture` instead.
* @deprecated since 8.0.0
*/
cacheAsBitmap: boolean;
/**
* Whether this container is currently cached as a texture.
* @example
* ```ts
* // Check cache state
* if (container.isCachedAsTexture) {
* console.log('Container is cached');
* }
* ```
* @readonly
* @see {@link Container#cacheAsTexture} For enabling caching
* @see {@link Container#updateCacheTexture} For updating cache
*/
readonly isCachedAsTexture: boolean;
}
/** @internal */
export declare const cacheAsTextureMixin: Partial<Container>;
/**
* Mixin interface for containers that allows them to manage children.
* It provides methods for adding, removing, and manipulating child containers.
* @category scene
* @advanced
*/
export interface ChildrenHelperMixin<C = ContainerChild> {
/** @internal */
allowChildren: boolean;
addChild<U extends C[]>(...children: U): U[0];
removeChild<U extends C[]>(...children: U): U[0];
/**
* Removes all children from this container that are within the begin and end indexes.
* @example
* ```ts
* // Remove all children
* container.removeChildren();
*
* // Remove first 3 children
* const removed = container.removeChildren(0, 3);
* console.log('Removed:', removed.length); // 3
*
* // Remove children from index 2 onwards
* container.removeChildren(2);
*
* // Remove specific range
* const middle = container.removeChildren(1, 4);
* ```
* @param {number} beginIndex - The beginning position
* @param {number} endIndex - The ending position. Default is container size
* @returns List of removed children
* @throws {RangeError} If begin/end indexes are invalid
* @see {@link Container#addChild} For adding children
* @see {@link Container#removeChild} For removing specific children
*/
removeChildren(beginIndex?: number, endIndex?: number): C[];
/**
* Removes a child from the specified index position.
* @example
* ```ts
* // Remove first child
* const removed = container.removeChildAt(0);
*
* // type safe access
* const sprite = container.removeChildAt<Sprite>(1);
*
* // With error handling
* try {
* const child = container.removeChildAt(10);
* } catch (e) {
* console.warn('Index out of bounds');
* }
* ```
* @param {number} index - The index to remove the child from
* @returns The child that was removed
* @throws {Error} If index is out of bounds
* @see {@link Container#removeChild} For removing specific children
* @see {@link Container#removeChildren} For removing multiple children
*/
removeChildAt<U extends C>(index: number): U;
/**
* Returns the child at the specified index.
* @example
* ```ts
* // Get first child
* const first = container.getChildAt(0);
*
* // Type-safe access
* const sprite = container.getChildAt<Sprite>(1);
*
* // With error handling
* try {
* const child = container.getChildAt(10);
* } catch (e) {
* console.warn('Index out of bounds');
* }
* ```
* @param {number} index - The index to get the child from
* @returns The child at the given index
* @throws {Error} If index is out of bounds
* @see {@link Container#children} For direct array access
* @see {@link Container#getChildByLabel} For name-based lookup
*/
getChildAt<U extends C>(index: number): U;
/**
* Changes the position of an existing child in the container.
* @example
* ```ts
* // Basic index change
* container.setChildIndex(sprite, 0); // Move to front
* container.setChildIndex(sprite, container.children.length - 1); // Move to back
*
* // With error handling
* try {
* container.setChildIndex(sprite, 5);
* } catch (e) {
* console.warn('Invalid index or child not found');
* }
* ```
* @param {Container}child - The child Container instance to reposition
* @param {number}index - The resulting index number for the child
* @throws {Error} If index is out of bounds
* @throws {Error} If child is not in container
* @see {@link Container#getChildIndex} For getting current index
* @see {@link Container#swapChildren} For swapping positions
*/
setChildIndex(child: C, index: number): void;
/**
* Returns the index position of a child Container instance.
* @example
* ```ts
* // Basic index lookup
* const index = container.getChildIndex(sprite);
* console.log(`Sprite is at index ${index}`);
*
* // With error handling
* try {
* const index = container.getChildIndex(sprite);
* } catch (e) {
* console.warn('Child not found in container');
* }
* ```
* @param {Container} child - The Container instance to identify
* @returns The index position of the child container
* @throws {Error} If child is not in this container
* @see {@link Container#setChildIndex} For changing index
* @see {@link Container#children} For direct array access
*/
getChildIndex(child: C): number;
/**
* Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown.
* If the child is already in this container, it will be moved to the specified index.
* @example
* ```ts
* // Add at specific index
* container.addChildAt(sprite, 0); // Add to front
*
* // Move existing child
* const index = container.children.length - 1;
* container.addChildAt(existingChild, index); // Move to back
*
* // With error handling
* try {
* container.addChildAt(sprite, 1000);
* } catch (e) {
* console.warn('Index out of bounds');
* }
* ```
* @param {Container} child - The child to add
* @param {number} index - The index where the child will be placed
* @returns The child that was added
* @throws {Error} If index is out of bounds
* @see {@link Container#addChild} For adding to the end
* @see {@link Container#setChildIndex} For moving existing children
*/
addChildAt<U extends C>(child: U, index: number): U;
/**
* Swaps the position of 2 Containers within this container.
* @example
* ```ts
* // Basic swap
* container.swapChildren(sprite1, sprite2);
*
* // With error handling
* try {
* container.swapChildren(sprite1, sprite2);
* } catch (e) {
* console.warn('One or both children not found in container');
* }
* ```
* @remarks
* - Updates render groups
* - No effect if same child
* - Triggers container changes
* - Common in z-ordering
* @param {Container} child - First container to swap
* @param {Container} child2 - Second container to swap
* @throws {Error} If either child is not in container
* @see {@link Container#setChildIndex} For direct index placement
* @see {@link Container#getChildIndex} For getting current positions
*/
swapChildren<U extends C>(child: U, child2: U): void;
/**
* Remove the Container from its parent Container. If the Container has no parent, do nothing.
* @example
* ```ts
* // Basic removal
* sprite.removeFromParent();
*
* // With validation
* if (sprite.parent) {
* sprite.removeFromParent();
* }
* ```
* @see {@link Container#addChild} For adding to a new parent
* @see {@link Container#removeChild} For parent removing children
*/
removeFromParent(): void;
/**
* Reparent a child or multiple children to this container while preserving their world transform.
* This ensures that the visual position and rotation of the children remain the same even when changing parents.
* @example
* ```ts
* // Basic reparenting
* const sprite = new Sprite(texture);
* oldContainer.addChild(sprite);
* // Move to new parent, keeping visual position
* newContainer.reparentChild(sprite);
*
* // Reparent multiple children
* const batch = [sprite1, sprite2, sprite3];
* newContainer.reparentChild(...batch);
* ```
* @param {Container} child - The child or children to reparent
* @returns The first child that was reparented
* @see {@link Container#reparentChildAt} For index-specific reparenting
* @see {@link Container#addChild} For simple parenting
*/
reparentChild<U extends C[]>(...child: U): U[0];
/**
* Reparent the child to this container at the specified index while preserving its world transform.
* This ensures that the visual position and rotation of the child remain the same even when changing parents.
* @example
* ```ts
* // Basic index-specific reparenting
* const sprite = new Sprite(texture);
* oldContainer.addChild(sprite);
* // Move to new parent at index 0 (front)
* newContainer.reparentChildAt(sprite, 0);
* ```
* @param {Container} child - The child to reparent
* @param {number} index - The index to reparent the child to
* @returns The reparented child
* @throws {Error} If index is out of bounds
* @see {@link Container#reparentChild} For appending reparented children
* @see {@link Container#addChildAt} For simple indexed parenting
*/
reparentChildAt<U extends C>(child: U, index: number): U;
/**
* Replace a child in the container with a new child. Copying the local transform from the old child to the new one.
* @param {Container} oldChild - The child to replace.
* @param {Container} newChild - The new child to add.
*/
replaceChild<U extends C, T extends C>(oldChild: U, newChild: T): void;
}
/** @internal */
export declare const childrenHelperMixin: ChildrenHelperMixin<ContainerChild>;
/**
* The CollectRenderablesMixin interface defines methods for collecting renderable objects
* from a container and its children. These methods add the renderables to an instruction set,
* which is used by the renderer to process and display the scene.
* @category scene
* @internal
*/
export interface CollectRenderablesMixin {
/**
* Collects all renderables from the container and its children, adding them to the instruction set.
* This method decides whether to use a simple or advanced collection method based on the container's properties.
* @param {InstructionSet} instructionSet - The set of instructions to which the renderables will be added.
* @param {Renderer} renderer - The renderer responsible for rendering the scene.
* @param {RenderLayer} currentLayer - The current render layer being processed.
* @internal
*/
collectRenderables(instructionSet: InstructionSet, renderer: Renderer, currentLayer: RenderLayer): void;
/**
* Collects renderables using a simple method, suitable for containers marked as simple.
* This method iterates over the container's children and adds their renderables to the instruction set.
* @param {InstructionSet} instructionSet - The set of instructions to which the renderables will be added.
* @param {Renderer} renderer - The renderer responsible for rendering the scene.
* @param {RenderLayer} currentLayer - The current render layer being processed.
* @internal
*/
collectRenderablesSimple(instructionSet: InstructionSet, renderer: Renderer, currentLayer: RenderLayer): void;
/**
* Collects renderables using an advanced method, suitable for containers with complex processing needs.
* This method handles additional effects and transformations that may be applied to the renderables.
* @param {InstructionSet} instructionSet - The set of instructions to which the renderables will be added.
* @param {Renderer} renderer - The renderer responsible for rendering the scene.
* @param {RenderLayer} currentLayer - The current render layer being processed.
* @internal
*/
collectRenderablesWithEffects(instructionSet: InstructionSet, renderer: Renderer, currentLayer: RenderLayer): void;
}
/**
* The collectRenderablesMixin provides implementations for the methods defined in the CollectRenderablesMixin interface.
* It includes logic to determine the appropriate method for collecting renderables based on the container's properties.
* @internal
*/
export declare const collectRenderablesMixin: Partial<Container>;
/** @ignore */
export interface EffectsMixinConstructor {
/**
* The mask to apply, which can be a Container or null.
*
* If null, it clears the existing mask.
* @example
* ```ts
* // Set a mask
* sprite.setMask({
* mask: graphics,
* inverse: false,
* });
*/
mask?: Mask;
setMask?: (options: Partial<MaskOptionsAndMask>) => void;
/**
* Sets the filters for the displayObject.
* Filters are visual effects that can be applied to any display object and its children.
*
* > [!IMPORTANT] This is a WebGL/WebGPU only feature and will be ignored by the canvas renderer.
* @example
* ```ts
* new Container({
* filters: [new BlurFilter(2), new ColorMatrixFilter()],
* });
* ```
* @see {@link Filter} For filter base class
*/
filters?: Filter | readonly Filter[];
}
/**
* The Mask type represents different ways to mask a display object.
* - A number represents a mask ID.
* - A Container represents a mask object, such as a Graphics or Sprite.
* - null indicates that no mask is applied.
* @example
* ```ts
* // Using a Container as a mask
* const maskContainer: Mask = new Graphics();
* // Using a mask ID
* const maskId: Mask = 123;
* // No mask applied
* const noMask: Mask = null;
* ```
* @category scene
* @standard
*/
export type Mask = number | Container | null;
/**
* Options for configuring mask behavior on a display object.
* @example
* ```ts
* // Basic mask inversion
* sprite.setMask({
* mask: graphics,
* inverse: true
* });
* ```
* @see {@link Container#setMask} For applying masks with options
* @see {@link Container#mask} For basic masking
* @category scene
* @standard
*/
export interface MaskOptions {
/**
* Whether the mask should be inverted.
* When true, the masked area becomes transparent and the unmasked area becomes visible.
* @default false
* @example
* ```ts
* // Invert the mask
* sprite.setMask({
* mask: graphics,
* inverse: true
* });
* ```
*/
inverse: boolean;
}
/**
* MaskOptionsAndMask combines MaskOptions with a Mask for configuring masking behavior.
* Used when setting up complex masking effects with additional options.
* @example
* ```ts
* sprite.setMask({
* mask: graphics,
* inverse: true,
* });
*
* // Clear existing mask
* sprite.setMask({
* mask: null,
* inverse: false,
* });
* ```
* @category scene
* @standard
* @see {@link Container#setMask} For applying masks
* @see {@link MaskOptions} For base options
*/
export interface MaskOptionsAndMask extends MaskOptions {
/**
* The mask to apply, which can be a Container or null.
*
* If null, it clears the existing mask.
* @example
* ```ts
* // Set a mask
* sprite.setMask({
* mask: graphics,
* inverse: false,
* });
*/
mask: Mask;
}
/**
* The EffectsMixin interface provides methods and properties for managing effects
* such as masks and filters on a display object.
* It allows for adding, removing, and configuring effects, as well as setting a mask for the display object.
* @category scene
* @advanced
*/
export interface EffectsMixin extends Required<EffectsMixinConstructor> {
/** @private */
_maskEffect?: MaskEffect;
/** @private */
_maskOptions?: MaskOptions;
/** @private */
_filterEffect?: FilterEffect;
/** @private */
_markStructureAsChanged(): void;
/**
* The area the filter is applied to. This is used as an optimization to define a specific region
* for filter effects instead of calculating the display object bounds each frame.
*
* > [!NOTE]
* > Setting this to a custom Rectangle allows you to define a specific area for filter effects,
* > which can improve performance by avoiding expensive bounds calculations.
* @example
* ```ts
* // Set specific filter area
* container.filterArea = new Rectangle(0, 0, 100, 100);
*
* // Optimize filter region
* const screen = app.screen;
* container.filterArea = new Rectangle(
* screen.x,
* screen.y,
* screen.width,
* screen.height
* );
* ```
* @see {@link Container#filters} For applying filters
* @see {@link Rectangle} For area definition
*/
filterArea?: Rectangle;
/**
* todo Needs docs
* @advanced
*/
effects?: Effect[];
/**
* todo Needs docs.
* @param {Effect} effect - The effect to add.
* @ignore
*/
addEffect(effect: Effect): void;
/**
* todo Needs docs.
* @param {Effect} effect - The effect to remove.
* @ignore
*/
removeEffect(effect: Effect): void;
/**
* Used to set mask and control mask options on a display object.
* Allows for more detailed control over masking behavior compared to the mask property.
* @example
* ```ts
* import { Graphics, Sprite } from 'pixi.js';
*
* // Create a circular mask
* const graphics = new Graphics()
* .beginFill(0xFF3300)
* .drawCircle(100, 100, 50)
* .endFill();
*
* // Apply mask with options
* sprite.setMask({
* mask: graphics,
* inverse: true, // Create a hole effect
* });
*
* // Clear existing mask
* sprite.setMask({ mask: null });
* ```
* @param {Partial<MaskOptionsAndMask>} options - Configuration options for the mask
* @see {@link Container#mask} For simple masking
* @see {@link MaskOptionsAndMask} For full options API
*/
setMask(options: Partial<MaskOptionsAndMask>): void;
/**
* Sets a mask for the displayObject. A mask is an object that limits the visibility of an
* object to the shape of the mask applied to it.
*
* > [!IMPORTANT] In PixiJS a regular mask must be a {@link Graphics} or a {@link Sprite} object.
* > This allows for much faster masking in canvas as it utilities shape clipping.
* > Furthermore, a mask of an object must be in the subtree of its parent.
* > Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong.
*
* For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
* @example
* ```ts
* // Apply mask to sprite
* const sprite = new Sprite(texture);
* sprite.mask = graphics;
*
* // Remove mask
* sprite.mask = null;
* ```
* @see {@link Graphics} For creating mask shapes
* @see {@link Sprite} For texture-based masks
* @see {@link Container#setMask} For advanced mask options
*/
mask: Mask;
/**
* Sets the filters for the displayObject.
* Filters are visual effects that can be applied to any display object and its children.
*
* > [!IMPORTANT] This is a WebGL/WebGPU only feature and will be ignored by the canvas renderer.
* @example
* ```ts
* // Add a single filter
* sprite.filters = new BlurFilter(2);
*
* // Apply multiple filters
* container.filters = [
* new BlurFilter(2),
* new ColorMatrixFilter(),
* ];
*
* // Remove filters
* sprite.filters = null;
* ```
* @see {@link Filter} For filter base class
*/
set filters(value: Filter | Filter[] | null | undefined);
get filters(): readonly Filter[];
}
/** @internal */
export declare const effectsMixin: Partial<Container>;
/** @ignore */
export interface FindMixinConstructor {
/**
* The instance label of the object.
* @default null
*/
label?: string;
}
/**
* The FindMixin interface provides methods for finding children within a container by their label.
* It allows for searching for a single child or multiple children with a specific label,
* either directly or recursively through the container's hierarchy.
* @category scene
* @advanced
*/
export interface FindMixin extends Required<FindMixinConstructor> {
/**
* The instance name of the object.
* @deprecated since 8.0.0
* @see Container#label
* @default null
*/
name: string;
/**
* @deprecated since 8.0.0
* @param {string} label - Instance name.
* @param {boolean}[deep=false] - Whether to search recursively
* @returns {Container} The child with the specified name.
* @see Container#getChildByLabel
*/
getChildByName(label: RegExp | string, deep?: boolean): Container | null;
/**
* Returns the first child in the container with the specified label.
* Recursive searches are done in a pre-order traversal.
* @example
* ```ts
* // Basic label search
* const child = container.getChildByLabel('player');
*
* // Search with regular expression
* const enemy = container.getChildByLabel(/enemy-\d+/);
*
* // Deep search through children
* const deepChild = container.getChildByLabel('powerup', true);
* ```
* @param {RegExp|string} label - Instance label to search for
* @param {boolean} deep - Whether to search recursively through children
* @returns The first child with the specified label, or null if none found
* @see {@link Container#getChildrenByLabel} For finding all matches
* @see {@link Container#label} For setting labels
*/
getChildByLabel(label: RegExp | string, deep?: boolean): Container | null;
/**
* Returns all children in the container with the specified label.
* Recursive searches are done in a pre-order traversal.
* @example
* ```ts
* // Basic label search
* const enemies = container.getChildrenByLabel('enemy');
* // Search with regular expression
* const powerups = container.getChildrenByLabel(/powerup-\d+/);
* // Deep search with collection
* const buttons = [];
* container.getChildrenByLabel('button', true, buttons);
* ```
* @param {string|RegExp} label - Instance label to search for
* @param {boolean}[deep=false] - Whether to search recursively through children
* @param {Container[]} [out=[]] - Optional array to store matching children in
* @returns An array of children with the specified label
* @see {@link Container#getChildByLabel} For finding first match
* @see {@link Container#label} For setting labels
*/
getChildrenByLabel(label: RegExp | string, deep?: boolean, out?: Container[]): Container[];
}
/** @internal */
export declare const findMixin: Partial<Container>;
/**
* Interface for the GetFastGlobalBoundsMixin, which provides methods to compute
* an approximate global bounding box for a container and its children.
* @category scene
* @advanced
*/
export interface GetFastGlobalBoundsMixin {
/**
* Computes an approximate global bounding box for the container and its children.
* This method is optimized for speed by using axis-aligned bounding boxes (AABBs),
* and uses the last render results from when it updated the transforms. This function does not update them.
* which may result in slightly larger bounds but never smaller than the actual bounds.
*
* for accurate (but less performant) results use `container.getGlobalBounds`
* @param {boolean} [factorRenderLayers] - A flag indicating whether to consider render layers in the calculation.
* @param {Bounds} [bounds] - The output bounds object to store the result. If not provided, a new one is created.
* @returns {Bounds} The computed bounds.
* @advanced
*/
getFastGlobalBounds(factorRenderLayers?: boolean, bounds?: Bounds): Bounds;
/**
* Recursively calculates the global bounds for the container and its children.
* This method is used internally by getFastGlobalBounds to traverse the scene graph.
* @param {boolean} factorRenderLayers - A flag indicating whether to consider render layers in the calculation.
* @param {Bounds} bounds - The bounds object to update with the calculated values.
* @param {RenderLayer} currentLayer - The current render layer being processed.
* @internal
*/
_getGlobalBoundsRecursive(factorRenderLayers: boolean, bounds: Bounds, currentLayer: RenderLayer): void;
}
/**
* Mixin providing the implementation of the GetFastGlobalBoundsMixin interface.
* It includes methods to compute and recursively calculate global bounds for containers.
* @internal
*/
export declare const getFastGlobalBoundsMixin: Partial<Container>;
/**
* Converts a color from BGR format to RGB format.
* @param color - The color in BGR format (0xBBGGRR).
* @returns The color in RGB format (0xRRGGBB).
* @category utils
* @internal
*/
export declare function bgr2rgb(color: number): number;
/**
* Interface for a mixin that provides methods to retrieve global properties of a container.
* This mixin allows you to get the global alpha, transform matrix, and tint color of a container,
* taking into account its parent containers and render groups.
* It includes methods to optimize performance by using cached values when available.
* @category scene
* @advanced
*/
export interface GetGlobalMixin {
/**
* Returns the global (compound) alpha of the container within the scene.
* @param {boolean} skipUpdate - Performance optimization flag:
* - If false (default): Recalculates the entire alpha chain through parents for accuracy
* - If true: Uses cached worldAlpha from the last render pass for better performance
* @returns The resulting alpha value (between 0 and 1)
* @example
* ```ts
* // Accurate but slower - recalculates entire alpha chain
* const preciseAlpha = container.getGlobalAlpha();
*
* // Faster but may be outdated - uses cached alpha
* const cachedAlpha = container.getGlobalAlpha(true);
* ```
*/
getGlobalAlpha(skipUpdate?: boolean): number;
/**
* Returns the global transform matrix of the container within the scene.
* @param {Matrix} matrix - Optional matrix to store the result. If not provided, a new Matrix will be created.
* @param {boolean} skipUpdate - Performance optimization flag:
* - If false (default): Recalculates the entire transform chain for accuracy
* - If true: Uses cached worldTransform from the last render pass for better performance
* @returns The resulting transformation matrix (either the input matrix or a new one)
* @example
* ```ts
* // Accurate but slower - recalculates entire transform chain
* const preciseTransform = container.getGlobalTransform();
*
* // Faster but may be outdated - uses cached transform
* const cachedTransform = container.getGlobalTransform(undefined, true);
*
* // Reuse existing matrix
* const existingMatrix = new Matrix();
* container.getGlobalTransform(existingMatrix);
* ```
*/
getGlobalTransform(matrix?: Matrix, skipUpdate?: boolean): Matrix;
/**
* Returns the global (compound) tint color of the container within the scene.
* @param {boolean} skipUpdate - Performance optimization flag:
* - If false (default): Recalculates the entire tint chain through parents for accuracy
* - If true: Uses cached worldColor from the last render pass for better performance
* @returns The resulting tint color as a 24-bit RGB number (0xRRGGBB)
* @example
* ```ts
* // Accurate but slower - recalculates entire tint chain
* const preciseTint = container.getGlobalTint();
*
* // Faster but may be outdated - uses cached tint
* const cachedTint = container.getGlobalTint(true);
* ```
*/
getGlobalTint(skipUpdate?: boolean): number;
}
/** @internal */
export declare const getGlobalMixin: Partial<Container>;
/** @internal */
export interface OnRenderMixinConstructor {
/**
* This callback is used when the container is rendered. It runs every frame during the render process,
* making it ideal for per-frame updates and animations.
*
* > [!NOTE] In v7 many users used `updateTransform` for this, however the way v8 renders objects is different
* > and "updateTransform" is no longer called every frame
* @example
* ```ts
* // Basic rotation animation
* const container = new Container();
* container.onRender = () => {
* container.rotation += 0.01;
* };
*
* // Cleanup when done
* container.onRender = null; // Removes callback
* ```
* @param renderer - The renderer instance
* @see {@link Renderer} For renderer capabilities
*/
onRender?: ((renderer: Renderer) => void) | null;
}
/**
* The OnRenderMixin interface provides a way to define a callback that is executed
* every time the container is rendered. This is useful for adding custom rendering logic
* or animations that need to be updated each frame.
* @category scene
* @advanced
*/
export interface OnRenderMixin extends Required<OnRenderMixinConstructor> {
/** @private */
_onRender: ((renderer: Renderer) => void) | null;
}
/** @internal */
export declare const onRenderMixin: Partial<Container>;
/** @ignore */
export interface SortMixinConstructor {
/**
* The zIndex of the container.
*
* Controls the rendering order of children within their parent container.
*
* A higher value will mean it will be moved towards the front of the rendering order.
* @example
* ```ts
* // Add in any order
* container.addChild(character, background, foreground);
*
* // Adjust rendering order
* background.zIndex = 0;
* character.zIndex = 1;
* foreground.zIndex = 2;
* ```
* @see {@link Container#sortableChildren} For enabling sorting
* @see {@link Container#sortChildren} For manual sorting
* @default 0
*/
zIndex?: number;
/**
* Should children be sorted by zIndex at the next render call.
*
* Will get automatically set to true if a new child is added, or if a child's zIndex changes.
* @default false
* @internal
*/
sortDirty?: boolean;
/**
* If set to true, the container will sort its children by `zIndex` value
* when the next render is called, or manually if `sortChildren()` is called.
*
* This actually changes the order of elements in the array of children,
* so it will affect the rendering order.
*
* > [!NOTE] Also be aware of that this may not work nicely with the `addChildAt()` function,
* > as the `zIndex` sorting may cause the child to automatically sorted to another position.
* @example
* ```ts
* container.sortableChildren = true;
* ```
* @default false
*/
sortableChildren?: boolean;
}
/**
* The SortMixin interface provides methods and properties for sorting children of a container
* based on their `zIndex` values. It allows for automatic sorting of children when their `zIndex`
* changes or when new children are added. The mixin includes properties to manage sorting state
* and methods to sort children explicitly.
* @category scene
* @advanced
*/
export interface SortMixin extends Required<SortMixinConstructor> {
/** @internal */
_zIndex: number;
/**
* Sorts children by zIndex value. Only sorts if container is marked as dirty.
* @example
* ```ts
* // Basic sorting
* particles.zIndex = 2; // Will mark as dirty
* container.sortChildren();
* ```
* @see {@link Container#sortableChildren} For enabling automatic sorting
* @see {@link Container#zIndex} For setting child order
*/
sortChildren: () => void;
/** @internal */
depthOfChildModified: () => void;
}
/** @internal */
export declare const sortMixin: Partial<Container>;
/**
* Interface for a mixin that provides methods to convert between local and global coordinates.
* This mixin allows you to get the global position of a container,
* convert a point from local to global coordinates,
* and convert a point from global to local coordinates.
*
* It includes methods to optimize performance by using cached matrices when available.
* @category scene
* @advanced
*/
export interface ToLocalGlobalMixin {
/**
* Returns the global position of the container, taking into account the container hierarchy.
* @example
* ```ts
* // Basic position check
* const globalPos = sprite.getGlobalPosition();
* console.log(`Global: (${globalPos.x}, ${globalPos.y})`);
*
* // Reuse point object
* const point = new Point();
* sprite.getGlobalPosition(point);
*
* // Skip transform update for performance
* const fastPos = container.getGlobalPosition(undefined, true);
* ```
* @param {Point} point - The optional point to write the global value to
* @param {boolean} skipUpdate - Should we skip the update transform
* @returns The updated point
* @see {@link Container#toGlobal} For converting specific points
* @see {@link Container#toLocal} For converting to local space
*/
getGlobalPosition(point?: Point, skipUpdate?: boolean): Point;
/**
* Calculates the global position of a point relative to this container.
* Takes into account the container hierarchy and transforms.
* @example
* ```ts
* // Basic point conversion
* const localPoint = { x: 10, y: 20 };
* const globalPoint = container.toGlobal(localPoint);
*
* // With point reuse
* const reusePoint = new Point();
* container.toGlobal(localPoint, reusePoint);
*
* // Performance optimization
* const fastPoint = container.toGlobal(
* { x: 50, y: 50 },
* undefined,
* true // Skip transform update
* );
* ```
* @param {PointData} position - The local point to convert
* @param {P} point - Optional point to store the result
* @param {boolean} skipUpdate - Whether to skip transform updates
* @returns The global position
* @see {@link Container#toLocal} For reverse conversion
* @see {@link Container#getGlobalPosition} For container position
*/
toGlobal<P extends PointData = Point>(position: PointData, point?: P, skipUpdate?: boolean): P;
/**
* Calculates the local position of the container relative to another point.
* Converts coordinates from any coordinate space to this container's local coordinate space.
* @example
* ```ts
* // Basic coordinate conversion
* const worldPoint = { x: 100, y: 100 };
* const localPos = container.toLocal(worldPoint);
*
* // Convert from another container
* const fromSprite = new Sprite(texture);
* fromSprite.position.set(50, 50);
* const pointInSprite = { x: 10, y: 10 };
* const localPoint = container.toLocal(pointInSprite, fromSprite);
*
* // With point reuse for performance
* const reusePoint = new Point();
* container.toLocal(worldPoint, undefined, reusePoint);
*
* // Skip transform update for static objects
* const fastLocal = container.toLocal(
* worldPoint,
* undefined,
* undefined,
* true
* );
* ```
* @param {PointData} position - The world origin to calculate from
* @param {Container} from - The Container to calculate the global position from
* @param {P} point - A Point object in which to store the value
* @param {boolean} skipUpdate - Should we skip the update transform
* @returns A point object representing the position in local space
* @see {@link Container#toGlobal} For reverse conversion
* @see {@link Container#getGlobalPosition} For container position
*/
toLocal<P extends PointData = Point>(position: PointData, from?: Container, point?: P, skipUpdate?: boolean): P;
}
/** @internal */
export declare const toLocalGlobalMixin: Partial<Container>;
/**
* Assigns properties from one object to another, using an optional array of property names to ignore.
* @param target - The target object to assign properties to.
* @param options - The object to assign properties from.
* @param ignore - An object of property names to ignore ({ propToIgnore: true }).
* @category utils
* @internal
*/
export declare function assignWithIgnore<T extends Record<string, any>>(target: T, options: T, ignore?: Record<string, boolean>): void;
/**
* This function will crawl through the container essentially check if the children have changed.
*
* This function checkChildrenDidChange recursively checks if any child in a Container
* or its children has changed. It does this by comparing a generated changeId for each
* child against a stored value in previousData.
* The changeId is a combination of the child's uid and _didChangeId, bitwise manipulated for uniqueness.
* If a change is detected, it updates previousData and sets didChange to true.
* The function returns a boolean indicating if any change was detected in the entire hierarchy of children.
* @param container - the container to check for changes
* @param previousData - the previous data from the last check made
* @param previousData.data - the data array
* @param previousData.index - the index of the data array
* @param previousData.didChange - did the data change
* @internal
*/
export declare function checkChildrenDidChange(container: Container, previousData: {
data: number[];
index: number;
didChange: boolean;
}): boolean;
/**
* nulls all slots in an array from a certain index.
* assume that when a null item is hit, the rest are also null.
* Which will be the case for where this is used!
* @param list - the array to clean
* @param index - the index to start from
* @category utils
* @internal
*/
export declare function clearList(list: Array<unknown>, index?: number): void;
/**
* Deprecated, please use container.collectRenderables instead.
* @param container - The container to collect renderables from.
* @param instructionSet - The instruction set to add the renderables to.
* @param rendererOrPipes - The renderer to collect the renderables from.
* @deprecated since version 8.7.0
* @see container.collectRenderables
* @internal
*/
export declare function collectAllRenderables(container: Container, instructionSet: InstructionSet, rendererOrPipes: Renderer | RenderPipes): void;
/**
* Returns a new object with all properties from the input object that have defined values.
* @template T - The type of the input object.
* @param {T} obj - The input object.
* @returns {T} - A new object with only the defined properties from the input object.
* @category utils
* @ignore
*/
export declare function definedProps<T extends Record<string, any>>(obj: T): T;
/**
* @param renderGroup
* @param renderer
* @internal
*/
export declare function executeInstructions(renderGroup: RenderGroup, renderer: RenderPipes): void;
/**
* @param localBGRColor
* @param parentBGRColor
* @internal
*/
export declare function multiplyColors(localBGRColor: number, parentBGRColor: number): number;
/**
* @param color1
* @param color2
* @internal
*/
export declare function multiplyHexColors(color1: number, color2: number): number;
/**
* Updates the local transform of a container based on its properties.
* @param lt - The matrix to update with the local transform values.
* @param container - The container whose local transform is being updated.
* @deprecated
* @internal
*/
export declare function updateLocalTransform(lt: Matrix, container: Container): void;
/**
* @param renderGroup
* @param updateChildRenderGroups
* @internal
*/
export declare function updateRenderGroupTransforms(renderGroup: RenderGroup, updateChildRenderGroups?: boolean): void;
/**
* @param renderGroup
* @internal
*/
export declare function updateRenderGroupTransform(renderGroup: RenderGroup): void;
/**
* @param container
* @param updateTick
* @param updateFlags
* @internal
*/
export declare function updateTransformAndChildren(container: Container, updateTick: number, updateFlags: number): void;
/**
* @param local
* @param parent
* @param world
* @deprecated
* @internal
*/
export declare function updateWorldTransform(local: Matrix, parent: Matrix, world: Matrix): void;
/**
* @param renderGroup
* @param renderPipes
* @internal
*/
export declare function validateRenderables(renderGroup: RenderGroup, renderPipes: RenderPipes): boolean;
/**
* A GraphicsAdaptor that uses WebGL to render graphics.
* @category rendering
* @ignore
*/
export declare class GlGraphicsAdaptor implements GraphicsAdaptor {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipesAdaptor
];
readonly name: "graphics";
};
shader: Shader;
contextChange(renderer: Renderer): void;
execute(graphicsPipe: GraphicsPipe, renderable: Graphics): void;
destroy(): void;
}
/**
* @param rgb
* @param alpha
* @param out
* @param offset
* @internal
*/
export declare function colorToUniform(rgb: number, alpha: number, out: Float32Array, offset: number): void;
/**
* @param abgr
* @param out
* @param offset
* @internal
*/
export declare function color32BitToUniform(abgr: number, out: Float32Array, offset: number): void;
/**
* A GraphicsAdaptor that uses the GPU to render graphics.
* @category rendering
* @ignore
*/
export declare class GpuGraphicsAdaptor implements GraphicsAdaptor {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUPipesAdaptor
];
readonly name: "graphics";
};
shader: Shader;
private _maxTextures;
contextChange(renderer: Renderer): void;
execute(graphicsPipe: GraphicsPipe, renderable: Graphics): void;
destroy(): void;
}
/**
* @param points
* @param sX
* @param sY
* @param cp1x
* @param cp1y
* @param cp2x
* @param cp2y
* @param eX
* @param eY
* @param smoothness
* @internal
*/
export declare function buildAdaptiveBezier(points: number[], sX: number, sY: number, cp1x: number, cp1y: number, cp2x: number, cp2y: number, eX: number, eY: number, smoothness?: number): number[];
/**
* @param points
* @param sX
* @param sY
* @param cp1x
* @param cp1y
* @param eX
* @param eY
* @param smoothness
* @internal
*/
export declare function buildAdaptiveQuadratic(points: number[], sX: number, sY: number, cp1x: number, cp1y: number, eX: number, eY: number, smoothness?: number): number[];
/**
* @param points
* @param x
* @param y
* @param radius
* @param start
* @param end
* @param clockwise
* @param steps
* @internal
*/
export declare function buildArc(points: number[], x: number, y: number, radius: number, start: number, end: number, clockwise: boolean, steps?: number): void;
/**
* The arcTo() method creates an arc/curve between two tangents on the canvas.
*
* "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
* @param points
* @param x1
* @param y1
* @param x2
* @param y2
* @param radius
* @internal
*/
export declare function buildArcTo(points: number[], x1: number, y1: number, x2: number, y2: number, radius: number): void;
/**
* @param points
* @param px
* @param py
* @param cx
* @param cy
* @param rx
* @param ry
* @param xAxisRotation
* @param largeArcFlag
* @param sweepFlag
* @internal
*/
export declare function buildArcToSvg(points: number[], px: number, py: number, cx: number, cy: number, rx: number, ry: number, xAxisRotation?: number, largeArcFlag?: number, sweepFlag?: number): void;
/**
* The Circle object represents a circle shape in a two-dimensional coordinate system.
* Used for drawing graphics and specifying hit areas for containers.
* @example
* ```ts
* // Basic circle creation
* const circle = new Circle(100, 100, 50);
*
* // Use as hit area
* container.hitArea = new Circle(0, 0, 100);
*
* // Check point containment
* const isInside = circle.contains(mouseX, mouseY);
*
* // Get bounding box
* const bounds = circle.getBounds();
* ```
* @remarks
* - Defined by center (x,y) and radius
* - Supports point containment tests
* - Can check stroke intersections
* @see {@link Rectangle} For rectangular shapes
* @category maths
* @standard
*/
export declare class Circle implements ShapePrimitive {
/**
* The X coordinate of the center of this circle
* @example
* ```ts
* // Basic x position
* const circle = new Circle();
* circle.x = 100;
*
* // Center circle on point
* circle.x = point.x;
* ```
* @default 0
*/
x: number;
/**
* The Y coordinate of the center of this circle
* @example
* ```ts
* // Basic y position
* const circle = new Circle();
* circle.y = 200;
*
* // Center circle on point
* circle.y = point.y;
* ```
* @default 0
*/
y: number;
/**
* The radius of the circle
* @example
* ```ts
* // Basic radius setting
* const circle = new Circle(100, 100);
* circle.radius = 50;
*
* // Calculate area
* const area = Math.PI * circle.radius * circle.radius;
* ```
* @default 0
*/
radius: number;
/**
* The type of the object, mainly used to avoid `instanceof` checks.
* @example
* ```ts
* // Check shape type
* const shape = new Circle(0, 0, 50);
* console.log(shape.type); // 'circle'
*
* // Use in type guards
* if (shape.type === 'circle') {
* console.log(shape.radius);
* }
* ```
* @remarks
* - Used for shape type checking
* - More efficient than instanceof
* - Read-only property
* @readonly
* @default 'circle'
* @see {@link SHAPE_PRIMITIVE} For all shape types
* @see {@link ShapePrimitive} For shape interface
*/
readonly type: SHAPE_PRIMITIVE;
/**
* @param x - The X coordinate of the center of this circle
* @param y - The Y coordinate of the center of this circle
* @param radius - The radius of the circle
*/
constructor(x?: number, y?: number, radius?: number);
/**
* Creates a clone of this Circle instance.
* @example
* ```ts
* // Basic circle cloning
* const original = new Circle(100, 100, 50);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.radius = 75;
*
* // Verify independence
* console.log(original.radius); // 50
* console.log(modified.radius); // 75
* ```
* @returns A copy of the Circle
* @see {@link Circle.copyFrom} For copying into existing circle
* @see {@link Circle.copyTo} For copying to another circle
*/
clone(): Circle;
/**
* Checks whether the x and y coordinates given are contained within this circle.
*
* Uses the distance formula to determine if a point is inside the circle's radius.
*
* Commonly used for hit testing in PixiJS events and graphics.
* @example
* ```ts
* // Basic containment check
* const circle = new Circle(100, 100, 50);
* const isInside = circle.contains(120, 120);
*
* // Check mouse position
* const circle = new Circle(0, 0, 100);
* container.hitArea = circle;
* container.on('pointermove', (e) => {
* // only called if pointer is within circle
* });
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coordinates are within this Circle
* @see {@link Circle.strokeContains} For checking stroke intersection
* @see {@link Circle.getBounds} For getting bounding box
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this circle including the stroke.
* @example
* ```ts
* // Basic stroke check
* const circle = new Circle(100, 100, 50);
* const isOnStroke = circle.strokeContains(150, 100, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = circle.strokeContains(150, 100, 4, 1); // Inside
* const centerStroke = circle.strokeContains(150, 100, 4, 0.5); // Centered
* const outerStroke = circle.strokeContains(150, 100, 4, 0); // Outside
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @param width - The width of the line to check
* @param alignment - The alignment of the stroke, 0.5 by default
* @returns Whether the x/y coordinates are within this Circle's stroke
* @see {@link Circle.contains} For checking fill containment
* @see {@link Circle.getBounds} For getting stroke bounds
*/
strokeContains(x: number, y: number, width: number, alignment?: number): boolean;
/**
* Returns the framing rectangle of the circle as a Rectangle object.
* @example
* ```ts
* // Basic bounds calculation
* const circle = new Circle(100, 100, 50);
* const bounds = circle.getBounds();
* // bounds: x=50, y=50, width=100, height=100
*
* // Reuse existing rectangle
* const rect = new Rectangle();
* circle.getBounds(rect);
* ```
* @param out - Optional Rectangle object to store the result
* @returns The framing rectangle
* @see {@link Rectangle} For rectangle properties
* @see {@link Circle.contains} For point containment
*/
getBounds(out?: Rectangle): Rectangle;
/**
* Copies another circle to this one.
* @example
* ```ts
* // Basic copying
* const source = new Circle(100, 100, 50);
* const target = new Circle();
* target.copyFrom(source);
* ```
* @param circle - The circle to copy from
* @returns Returns itself
* @see {@link Circle.copyTo} For copying to another circle
* @see {@link Circle.clone} For creating new circle copy
*/
copyFrom(circle: Circle): this;
/**
* Copies this circle to another one.
* @example
* ```ts
* // Basic copying
* const source = new Circle(100, 100, 50);
* const target = new Circle();
* source.copyTo(target);
* ```
* @param circle - The circle to copy to
* @returns Returns given parameter
* @see {@link Circle.copyFrom} For copying from another circle
* @see {@link Circle.clone} For creating new circle copy
*/
copyTo(circle: Circle): Circle;
toString(): string;
}
/**
* The Ellipse object is used to help draw graphics and can also be used to specify a hit area for containers.
* @example
* ```ts
* // Basic ellipse creation
* const ellipse = new Ellipse(100, 100, 20, 10);
*
* // Use as a hit area
* container.hitArea = new Ellipse(0, 0, 50, 25);
*
* // Check point containment
* const isInside = ellipse.contains(mouseX, mouseY);
*
* // Get bounding box
* const bounds = ellipse.getBounds();
* ```
* @remarks
* - Defined by center (x,y) and half dimensions
* - Total width = halfWidth * 2
* - Total height = halfHeight * 2
* @see {@link Rectangle} For rectangular shapes
* @see {@link Circle} For circular shapes
* @category maths
* @standard
*/
export declare class Ellipse implements ShapePrimitive {
/**
* The X coordinate of the center of this ellipse
* @example
* ```ts
* // Basic x position
* const ellipse = new Ellipse();
* ellipse.x = 100;
* ```
* @default 0
*/
x: number;
/**
* The Y coordinate of the center of this ellipse
* @example
* ```ts
* // Basic y position
* const ellipse = new Ellipse();
* ellipse.y = 200;
* ```
* @default 0
*/
y: number;
/**
* The half width of this ellipse
* @example
* ```ts
* // Set half width
* const ellipse = new Ellipse(100, 100);
* ellipse.halfWidth = 50; // Total width will be 100
* ```
* @default 0
*/
halfWidth: number;
/**
* The half height of this ellipse
* @example
* ```ts
* // Set half height
* const ellipse = new Ellipse(100, 100);
* ellipse.halfHeight = 25; // Total height will be 50
* ```
* @default 0
*/
halfHeight: number;
/**
* The type of the object, mainly used to avoid `instanceof` checks
* @example
* ```ts
* // Check shape type
* const shape = new Ellipse(0, 0, 50, 25);
* console.log(shape.type); // 'ellipse'
*
* // Use in type guards
* if (shape.type === 'ellipse') {
* console.log(shape.halfWidth, shape.halfHeight);
* }
* ```
* @readonly
* @default 'ellipse'
* @see {@link SHAPE_PRIMITIVE} For all shape types
*/
readonly type = "ellipse";
/**
* @param x - The X coordinate of the center of this ellipse
* @param y - The Y coordinate of the center of this ellipse
* @param halfWidth - The half width of this ellipse
* @param halfHeight - The half height of this ellipse
*/
constructor(x?: number, y?: number, halfWidth?: number, halfHeight?: number);
/**
* Creates a clone of this Ellipse instance.
* @example
* ```ts
* // Basic cloning
* const original = new Ellipse(100, 100, 50, 25);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.halfWidth *= 2;
* modified.halfHeight *= 2;
*
* // Verify independence
* console.log(original.halfWidth); // 50
* console.log(modified.halfWidth); // 100
* ```
* @returns A copy of the ellipse
* @see {@link Ellipse.copyFrom} For copying into existing ellipse
* @see {@link Ellipse.copyTo} For copying to another ellipse
*/
clone(): Ellipse;
/**
* Checks whether the x and y coordinates given are contained within this ellipse.
* Uses normalized coordinates and the ellipse equation to determine containment.
* @example
* ```ts
* // Basic containment check
* const ellipse = new Ellipse(100, 100, 50, 25);
* const isInside = ellipse.contains(120, 110);
* ```
* @remarks
* - Uses ellipse equation (x²/a² + y²/b² ≤ 1)
* - Returns false if dimensions are 0 or negative
* - Normalized to center (0,0) for calculation
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coords are within this ellipse
* @see {@link Ellipse.strokeContains} For checking stroke intersection
* @see {@link Ellipse.getBounds} For getting containing rectangle
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this ellipse including stroke.
* @example
* ```ts
* // Basic stroke check
* const ellipse = new Ellipse(100, 100, 50, 25);
* const isOnStroke = ellipse.strokeContains(150, 100, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = ellipse.strokeContains(150, 100, 4, 1); // Inside
* const centerStroke = ellipse.strokeContains(150, 100, 4, 0.5); // Centered
* const outerStroke = ellipse.strokeContains(150, 100, 4, 0); // Outside
* ```
* @remarks
* - Uses normalized ellipse equations
* - Considers stroke alignment
* - Returns false if dimensions are 0
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @param strokeWidth - The width of the line to check
* @param alignment - The alignment of the stroke (1 = inner, 0.5 = centered, 0 = outer)
* @returns Whether the x/y coords are within this ellipse's stroke
* @see {@link Ellipse.contains} For checking fill containment
* @see {@link Ellipse.getBounds} For getting stroke bounds
*/
strokeContains(x: number, y: number, strokeWidth: number, alignment?: number): boolean;
/**
* Returns the framing rectangle of the ellipse as a Rectangle object.
* @example
* ```ts
* // Basic bounds calculation
* const ellipse = new Ellipse(100, 100, 50, 25);
* const bounds = ellipse.getBounds();
* // bounds: x=50, y=75, width=100, height=50
*
* // Reuse existing rectangle
* const rect = new Rectangle();
* ellipse.getBounds(rect);
* ```
* @remarks
* - Creates Rectangle if none provided
* - Top-left is (x-halfWidth, y-halfHeight)
* - Width is halfWidth * 2
* - Height is halfHeight * 2
* @param out - Optional Rectangle object to store the result
* @returns The framing rectangle
* @see {@link Rectangle} For rectangle properties
* @see {@link Ellipse.contains} For checking if a point is inside
*/
getBounds(out?: Rectangle): Rectangle;
/**
* Copies another ellipse to this one.
* @example
* ```ts
* // Basic copying
* const source = new Ellipse(100, 100, 50, 25);
* const target = new Ellipse();
* target.copyFrom(source);
* ```
* @param ellipse - The ellipse to copy from
* @returns Returns itself
* @see {@link Ellipse.copyTo} For copying to another ellipse
* @see {@link Ellipse.clone} For creating new ellipse copy
*/
copyFrom(ellipse: Ellipse): this;
/**
* Copies this ellipse to another one.
* @example
* ```ts
* // Basic copying
* const source = new Ellipse(100, 100, 50, 25);
* const target = new Ellipse();
* source.copyTo(target);
* ```
* @param ellipse - The ellipse to copy to
* @returns Returns given parameter
* @see {@link Ellipse.copyFrom} For copying from another ellipse
* @see {@link Ellipse.clone} For creating new ellipse copy
*/
copyTo(ellipse: Ellipse): Ellipse;
toString(): string;
}
/**
* The `RoundedRectangle` object represents a rectangle with rounded corners.
* Defined by position, dimensions and corner radius.
* @example
* ```ts
* // Basic rectangle creation
* const rect = new RoundedRectangle(100, 100, 200, 150, 20);
* // Use as container hit area
* container.hitArea = new RoundedRectangle(0, 0, 100, 100, 10);
* // Check point containment
* const isInside = rect.contains(mouseX, mouseY);
* // Get bounds
* const bounds = rect.getBounds();
* ```
* @remarks
* - Position defined by top-left corner
* - Radius clamped to half smallest dimension
* - Common in UI elements
* @see {@link Rectangle} For non-rounded rectangles
* @category maths
* @standard
*/
export declare class RoundedRectangle implements ShapePrimitive {
/**
* The X coordinate of the upper-left corner of the rounded rectangle
* @example
* ```ts
* // Basic x position
* const rect = new RoundedRectangle();
* rect.x = 100;
* ```
* @default 0
*/
x: number;
/**
* The Y coordinate of the upper-left corner of the rounded rectangle
* @example
* ```ts
* // Basic y position
* const rect = new RoundedRectangle();
* rect.y = 100;
* ```
* @default 0
*/
y: number;
/**
* The overall width of this rounded rectangle
* @example
* ```ts
* // Basic width setting
* const rect = new RoundedRectangle();
* rect.width = 200; // Total width will be 200
* ```
* @default 0
*/
width: number;
/**
* The overall height of this rounded rectangle
* @example
* ```ts
* // Basic height setting
* const rect = new RoundedRectangle();
* rect.height = 150; // Total height will be 150
* ```
* @default 0
*/
height: number;
/**
* Controls the radius of the rounded corners
* @example
* ```ts
* // Basic radius setting
* const rect = new RoundedRectangle(0, 0, 200, 150);
* rect.radius = 20;
*
* // Clamp to maximum safe radius
* rect.radius = Math.min(rect.width, rect.height) / 2;
*
* // Create pill shape
* rect.radius = rect.height / 2;
* ```
* @remarks
* - Automatically clamped to half of smallest dimension
* - Common values: 0-20 for UI elements
* - Higher values create more rounded corners
* @default 20
*/
radius: number;
/**
* The type of the object, mainly used to avoid `instanceof` checks
* @example
* ```ts
* // Check shape type
* const shape = new RoundedRectangle(0, 0, 100, 100, 20);
* console.log(shape.type); // 'roundedRectangle'
*
* // Use in type guards
* if (shape.type === 'roundedRectangle') {
* console.log(shape.radius);
* }
* ```
* @readonly
* @default 'roundedRectangle'
* @see {@link SHAPE_PRIMITIVE} For all shape types
*/
readonly type: SHAPE_PRIMITIVE;
/**
* @param x - The X coordinate of the upper-left corner of the rounded rectangle
* @param y - The Y coordinate of the upper-left corner of the rounded rectangle
* @param width - The overall width of this rounded rectangle
* @param height - The overall height of this rounded rectangle
* @param radius - Controls the radius of the rounded corners
*/
constructor(x?: number, y?: number, width?: number, height?: number, radius?: number);
/**
* Returns the framing rectangle of the rounded rectangle as a Rectangle object
* @example
* ```ts
* // Basic bounds calculation
* const rect = new RoundedRectangle(100, 100, 200, 150, 20);
* const bounds = rect.getBounds();
* // bounds: x=100, y=100, width=200, height=150
*
* // Reuse existing rectangle
* const out = new Rectangle();
* rect.getBounds(out);
* ```
* @remarks
* - Rectangle matches outer dimensions
* - Ignores corner radius
* @param out - Optional rectangle to store the result
* @returns The framing rectangle
* @see {@link Rectangle} For rectangle properties
* @see {@link RoundedRectangle.contains} For checking if a point is inside
*/
getBounds(out?: Rectangle): Rectangle;
/**
* Creates a clone of this Rounded Rectangle.
* @example
* ```ts
* // Basic cloning
* const original = new RoundedRectangle(100, 100, 200, 150, 20);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.radius = 30;
* modified.width *= 2;
*
* // Verify independence
* console.log(original.radius); // 20
* console.log(modified.radius); // 30
* ```
* @returns A copy of the rounded rectangle
* @see {@link RoundedRectangle.copyFrom} For copying into existing rectangle
* @see {@link RoundedRectangle.copyTo} For copying to another rectangle
*/
clone(): RoundedRectangle;
/**
* Copies another rectangle to this one.
* @example
* ```ts
* // Basic copying
* const source = new RoundedRectangle(100, 100, 200, 150, 20);
* const target = new RoundedRectangle();
* target.copyFrom(source);
*
* // Chain with other operations
* const rect = new RoundedRectangle()
* .copyFrom(source)
* .getBounds(rect);
* ```
* @param rectangle - The rectangle to copy from
* @returns Returns itself
* @see {@link RoundedRectangle.copyTo} For copying to another rectangle
* @see {@link RoundedRectangle.clone} For creating new rectangle copy
*/
copyFrom(rectangle: RoundedRectangle): this;
/**
* Copies this rectangle to another one.
* @example
* ```ts
* // Basic copying
* const source = new RoundedRectangle(100, 100, 200, 150, 20);
* const target = new RoundedRectangle();
* source.copyTo(target);
*
* // Chain with other operations
* const result = source
* .copyTo(new RoundedRectangle())
* .getBounds();
* ```
* @param rectangle - The rectangle to copy to
* @returns Returns given parameter
* @see {@link RoundedRectangle.copyFrom} For copying from another rectangle
* @see {@link RoundedRectangle.clone} For creating new rectangle copy
*/
copyTo(rectangle: RoundedRectangle): RoundedRectangle;
/**
* Checks whether the x and y coordinates given are contained within this Rounded Rectangle
* @example
* ```ts
* // Basic containment check
* const rect = new RoundedRectangle(100, 100, 200, 150, 20);
* const isInside = rect.contains(150, 125); // true
* // Check corner radius
* const corner = rect.contains(100, 100); // false if within corner curve
* ```
* @remarks
* - Returns false if width/height is 0 or negative
* - Handles rounded corners with radius check
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coordinates are within this Rounded Rectangle
* @see {@link RoundedRectangle.strokeContains} For checking stroke intersection
* @see {@link RoundedRectangle.getBounds} For getting containing rectangle
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this rectangle including the stroke.
* @example
* ```ts
* // Basic stroke check
* const rect = new RoundedRectangle(100, 100, 200, 150, 20);
* const isOnStroke = rect.strokeContains(150, 100, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = rect.strokeContains(150, 100, 4, 1); // Inside
* const centerStroke = rect.strokeContains(150, 100, 4, 0.5); // Centered
* const outerStroke = rect.strokeContains(150, 100, 4, 0); // Outside
* ```
* @param pX - The X coordinate of the point to test
* @param pY - The Y coordinate of the point to test
* @param strokeWidth - The width of the line to check
* @param alignment - The alignment of the stroke (1 = inner, 0.5 = centered, 0 = outer)
* @returns Whether the x/y coordinates are within this rectangle's stroke
* @see {@link RoundedRectangle.contains} For checking fill containment
* @see {@link RoundedRectangle.getBounds} For getting stroke bounds
*/
strokeContains(pX: number, pY: number, strokeWidth: number, alignment?: number): boolean;
toString(): string;
}
/** @internal */
export interface ShapeBuildCommand<T extends ShapePrimitive = ShapePrimitive> {
extension: ExtensionMetadataDetails;
build(shape: T, points: number[]): boolean;
triangulate(points: number[], vertices: number[], verticesStride: number, verticesOffset: number, indices: number[], indicesOffset: number): void;
}
type RoundedShape = Circle | Ellipse | RoundedRectangle;
/**
* Builds a rectangle to draw
*
* Ignored from docs since it is not directly exposed.
* @internal
*/
export declare const buildCircle: ShapeBuildCommand<RoundedShape>;
/** @internal */
export declare const buildEllipse: {
extension: {
name: string;
type: ExtensionType | ExtensionType[];
priority?: number;
};
build(shape: RoundedShape, points: number[]): boolean;
triangulate(points: number[], vertices: number[], verticesStride: number, verticesOffset: number, indices: number[], indicesOffset: number): void;
};
/** @internal */
export declare const buildRoundedRectangle: {
extension: {
name: string;
type: ExtensionType | ExtensionType[];
priority?: number;
};
build(shape: RoundedShape, points: number[]): boolean;
triangulate(points: number[], vertices: number[], verticesStride: number, verticesOffset: number, indices: number[], indicesOffset: number): void;
};
/**
* Builds a line to draw using the polygon method.
* @param points
* @param lineStyle
* @param flipAlignment
* @param closed
* @param vertices
* @param indices
* @internal
*/
export declare function buildLine(points: number[], lineStyle: StrokeAttributes, flipAlignment: boolean, closed: boolean, vertices: number[], indices: number[]): void;
/**
* Builds a line to draw using the polygon method.
* @param points
* @param closed
* @param vertices
* @param indices
* @internal
*/
export declare function buildPixelLine(points: number[], closed: boolean, vertices: number[], indices: number[]): void;
/**
* A class to define a shape via user defined coordinates.
* Used for creating complex shapes and hit areas with custom points.
* @example
* ```ts
* // Create polygon from array of points
* const polygon1 = new Polygon([
* new Point(0, 0),
* new Point(0, 100),
* new Point(100, 100)
* ]);
*
* // Create from array of coordinates
* const polygon2 = new Polygon([0, 0, 0, 100, 100, 100]);
*
* // Create from sequence of points
* const polygon3 = new Polygon(
* new Point(0, 0),
* new Point(0, 100),
* new Point(100, 100)
* );
*
* // Create from sequence of coordinates
* const polygon4 = new Polygon(0, 0, 0, 100, 100, 100);
*
* // Use as container hit area
* container.hitArea = new Polygon([0, 0, 100, 0, 50, 100]);
* ```
* @see {@link Point} For point objects used in construction
* @category maths
* @standard
*/
export declare class Polygon implements ShapePrimitive {
/**
* An array of the points of this polygon stored as a flat array of numbers.
* @example
* ```ts
* // Access points directly
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* console.log(polygon.points); // [0, 0, 100, 0, 50, 100]
*
* // Modify points
* polygon.points[0] = 10; // Move first x coordinate
* polygon.points[1] = 10; // Move first y coordinate
* ```
* @remarks
* - Stored as [x1, y1, x2, y2, ...]
* - Each pair represents a vertex
* - Length is always even
* - Can be modified directly
*/
points: number[];
/**
* Indicates if the polygon path is closed.
* @example
* ```ts
* // Create open polygon
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* polygon.closePath = false;
*
* // Check path state
* if (polygon.closePath) {
* // Last point connects to first
* }
* ```
* @remarks
* - True by default
* - False after moveTo
* - True after closePath
* @default true
*/
closePath: boolean;
/**
* The type of the object, mainly used to avoid `instanceof` checks
* @example
* ```ts
* // Check shape type
* const shape = new Polygon([0, 0, 100, 0, 50, 100]);
* console.log(shape.type); // 'polygon'
*
* // Use in type guards
* if (shape.type === 'polygon') {
* // TypeScript knows this is a Polygon
* console.log(shape.points.length);
* }
* ```
* @readonly
* @default 'polygon'
* @see {@link SHAPE_PRIMITIVE} For all shape types
*/
readonly type: SHAPE_PRIMITIVE;
constructor(points: PointData[] | number[]);
constructor(...points: PointData[] | number[]);
/**
* Determines whether the polygon's points are arranged in a clockwise direction.
* Uses the shoelace formula (surveyor's formula) to calculate the signed area.
*
* A positive area indicates clockwise winding, while negative indicates counter-clockwise.
*
* The formula sums up the cross products of adjacent vertices:
* For each pair of adjacent points (x1,y1) and (x2,y2), we calculate (x1*y2 - x2*y1)
* The final sum divided by 2 gives the signed area - positive for clockwise.
* @example
* ```ts
* // Check polygon winding
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* console.log(polygon.isClockwise()); // Check direction
*
* // Use in path construction
* const hole = new Polygon([25, 25, 75, 25, 75, 75, 25, 75]);
* if (hole.isClockwise() === shape.isClockwise()) {
* hole.points.reverse(); // Reverse for proper hole winding
* }
* ```
* @returns `true` if the polygon's points are arranged clockwise, `false` if counter-clockwise
*/
isClockwise(): boolean;
/**
* Checks if this polygon completely contains another polygon.
* Used for detecting holes in shapes, like when parsing SVG paths.
* @example
* ```ts
* // Basic containment check
* const outerSquare = new Polygon([0,0, 100,0, 100,100, 0,100]); // A square
* const innerSquare = new Polygon([25,25, 75,25, 75,75, 25,75]); // A smaller square inside
*
* outerSquare.containsPolygon(innerSquare); // Returns true
* innerSquare.containsPolygon(outerSquare); // Returns false
* ```
* @remarks
* - Uses bounds check for quick rejection
* - Tests all points for containment
* @param polygon - The polygon to test for containment
* @returns True if this polygon completely contains the other polygon
* @see {@link Polygon.contains} For single point testing
* @see {@link Polygon.getBounds} For bounds calculation
*/
containsPolygon(polygon: Polygon): boolean;
/**
* Creates a clone of this polygon.
* @example
* ```ts
* // Basic cloning
* const original = new Polygon([0, 0, 100, 0, 50, 100]);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.points[0] = 10; // Modify first x coordinate
* ```
* @returns A copy of the polygon
* @see {@link Polygon.copyFrom} For copying into existing polygon
* @see {@link Polygon.copyTo} For copying to another polygon
*/
clone(): Polygon;
/**
* Checks whether the x and y coordinates passed to this function are contained within this polygon.
* Uses raycasting algorithm for point-in-polygon testing.
* @example
* ```ts
* // Basic containment check
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* const isInside = polygon.contains(25, 25); // true
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coordinates are within this polygon
* @see {@link Polygon.strokeContains} For checking stroke intersection
* @see {@link Polygon.containsPolygon} For polygon-in-polygon testing
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this polygon including the stroke.
* @example
* ```ts
* // Basic stroke check
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* const isOnStroke = polygon.strokeContains(25, 25, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = polygon.strokeContains(25, 25, 4, 1); // Inside
* const centerStroke = polygon.strokeContains(25, 25, 4, 0.5); // Centered
* const outerStroke = polygon.strokeContains(25, 25, 4, 0); // Outside
* ```
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @param strokeWidth - The width of the line to check
* @param alignment - The alignment of the stroke (1 = inner, 0.5 = centered, 0 = outer)
* @returns Whether the x/y coordinates are within this polygon's stroke
* @see {@link Polygon.contains} For checking fill containment
* @see {@link Polygon.getBounds} For getting stroke bounds
*/
strokeContains(x: number, y: number, strokeWidth: number, alignment?: number): boolean;
/**
* Returns the framing rectangle of the polygon as a Rectangle object.
* @example
* ```ts
* // Basic bounds calculation
* const polygon = new Polygon([0, 0, 100, 0, 50, 100]);
* const bounds = polygon.getBounds();
* // bounds: x=0, y=0, width=100, height=100
*
* // Reuse existing rectangle
* const rect = new Rectangle();
* polygon.getBounds(rect);
* ```
* @param out - Optional rectangle to store the result
* @returns The framing rectangle
* @see {@link Rectangle} For rectangle properties
* @see {@link Polygon.contains} For checking if a point is inside
*/
getBounds(out?: Rectangle): Rectangle;
/**
* Copies another polygon to this one.
* @example
* ```ts
* // Basic copying
* const source = new Polygon([0, 0, 100, 0, 50, 100]);
* const target = new Polygon();
* target.copyFrom(source);
* ```
* @param polygon - The polygon to copy from
* @returns Returns itself
* @see {@link Polygon.copyTo} For copying to another polygon
* @see {@link Polygon.clone} For creating new polygon copy
*/
copyFrom(polygon: Polygon): this;
/**
* Copies this polygon to another one.
* @example
* ```ts
* // Basic copying
* const source = new Polygon([0, 0, 100, 0, 50, 100]);
* const target = new Polygon();
* source.copyTo(target);
* ```
* @param polygon - The polygon to copy to
* @returns Returns given parameter
* @see {@link Polygon.copyFrom} For copying from another polygon
* @see {@link Polygon.clone} For creating new polygon copy
*/
copyTo(polygon: Polygon): Polygon;
toString(): string;
/**
* Get the last X coordinate of the polygon.
* @example
* ```ts
* // Basic coordinate access
* const polygon = new Polygon([0, 0, 100, 200, 300, 400]);
* console.log(polygon.lastX); // 300
* ```
* @readonly
* @returns The x-coordinate of the last vertex
* @see {@link Polygon.lastY} For last Y coordinate
* @see {@link Polygon.points} For raw points array
*/
get lastX(): number;
/**
* Get the last Y coordinate of the polygon.
* @example
* ```ts
* // Basic coordinate access
* const polygon = new Polygon([0, 0, 100, 200, 300, 400]);
* console.log(polygon.lastY); // 400
* ```
* @readonly
* @returns The y-coordinate of the last vertex
* @see {@link Polygon.lastX} For last X coordinate
* @see {@link Polygon.points} For raw points array
*/
get lastY(): number;
/**
* Get the last X coordinate of the polygon.
* @readonly
* @deprecated since 8.11.0, use {@link Polygon.lastX} instead.
*/
get x(): number;
/**
* Get the last Y coordinate of the polygon.
* @readonly
* @deprecated since 8.11.0, use {@link Polygon.lastY} instead.
*/
get y(): number;
/**
* Get the first X coordinate of the polygon.
* @example
* ```ts
* // Basic coordinate access
* const polygon = new Polygon([0, 0, 100, 200, 300, 400]);
* console.log(polygon.x); // 0
* ```
* @readonly
* @returns The x-coordinate of the first vertex
* @see {@link Polygon.startY} For first Y coordinate
* @see {@link Polygon.points} For raw points array
*/
get startX(): number;
/**
* Get the first Y coordinate of the polygon.
* @example
* ```ts
* // Basic coordinate access
* const polygon = new Polygon([0, 0, 100, 200, 300, 400]);
* console.log(polygon.y); // 0
* ```
* @readonly
* @returns The y-coordinate of the first vertex
* @see {@link Polygon.startX} For first X coordinate
* @see {@link Polygon.points} For raw points array
*/
get startY(): number;
}
/**
* Builds a rectangle to draw
*
* Ignored from docs since it is not directly exposed.
* @ignore
* @private
*/
export declare const buildPolygon: ShapeBuildCommand<Polygon>;
/**
* Builds a rectangle to draw
*
* Ignored from docs since it is not directly exposed.
* @ignore
* @private
*/
export declare const buildRectangle: ShapeBuildCommand<Rectangle>;
/**
* A class to define a shape of a triangle via user defined coordinates.
*
* Used for creating triangular shapes and hit areas with three points (x,y), (x2,y2), (x3,y3).
* Points are stored in counter-clockwise order.
* @example
* ```ts
* // Basic triangle creation
* const triangle = new Triangle(0, 0, 100, 0, 50, 50);
* // Use as hit area
* container.hitArea = new Triangle(0, 0, 100, 0, 50, 100);
* // Check point containment
* const isInside = triangle.contains(mouseX, mouseY);
* // Get bounding box
* const bounds = triangle.getBounds();
* ```
* @see {@link Rectangle} For rectangular shapes
* @see {@link Circle} For circular shapes
* @see {@link Polygon} For complex shapes
* @category maths
* @standard
*/
export declare class Triangle implements ShapePrimitive {
/**
* The type of the object, mainly used to avoid `instanceof` checks
* @example
* ```ts
* // Check shape type
* const shape = new Triangle(0, 0, 100, 0, 50, 100);
* console.log(shape.type); // 'triangle'
*
* // Use in type guards
* if (shape.type === 'triangle') {
* console.log(shape.x2, shape.y2);
* }
* ```
* @readonly
* @default 'triangle'
* @see {@link SHAPE_PRIMITIVE} For all shape types
*/
readonly type: SHAPE_PRIMITIVE;
/**
* The X coordinate of the first point of the triangle.
* @example
* ```ts
* // Set first point x position
* const triangle = new Triangle();
* triangle.x = 100;
* ```
* @default 0
*/
x: number;
/**
* The Y coordinate of the first point of the triangle.
* @example
* ```ts
* // Set first point y position
* const triangle = new Triangle();
* triangle.y = 100;
* ```
* @default 0
*/
y: number;
/**
* The X coordinate of the second point of the triangle.
* @example
* ```ts
* // Create horizontal line for second point
* const triangle = new Triangle(0, 0);
* triangle.x2 = triangle.x + 100; // 100 units to the right
* ```
* @default 0
*/
x2: number;
/**
* The Y coordinate of the second point of the triangle.
* @example
* ```ts
* // Create vertical line for second point
* const triangle = new Triangle(0, 0);
* triangle.y2 = triangle.y + 100; // 100 units down
* ```
* @default 0
*/
y2: number;
/**
* The X coordinate of the third point of the triangle.
* @example
* ```ts
* // Create equilateral triangle
* const triangle = new Triangle(0, 0, 100, 0);
* triangle.x3 = 50; // Middle point x
* triangle.y3 = 86.6; // Height using sin(60°)
* ```
* @default 0
*/
x3: number;
/**
* The Y coordinate of the third point of the triangle.
* @example
* ```ts
* // Create right triangle
* const triangle = new Triangle(0, 0, 100, 0);
* triangle.x3 = 0; // Align with first point
* triangle.y3 = 100; // 100 units down
* ```
* @default 0
*/
y3: number;
/**
* @param x - The X coord of the first point.
* @param y - The Y coord of the first point.
* @param x2 - The X coord of the second point.
* @param y2 - The Y coord of the second point.
* @param x3 - The X coord of the third point.
* @param y3 - The Y coord of the third point.
*/
constructor(x?: number, y?: number, x2?: number, y2?: number, x3?: number, y3?: number);
/**
* Checks whether the x and y coordinates given are contained within this triangle
* @example
* ```ts
* // Basic containment check
* const triangle = new Triangle(0, 0, 100, 0, 50, 100);
* const isInside = triangle.contains(25, 25); // true
* ```
* @remarks
* - Uses barycentric coordinate system
* - Works with any triangle shape
* @param x - The X coordinate of the point to test
* @param y - The Y coordinate of the point to test
* @returns Whether the x/y coordinates are within this Triangle
* @see {@link Triangle.strokeContains} For checking stroke intersection
* @see {@link Triangle.getBounds} For getting containing rectangle
*/
contains(x: number, y: number): boolean;
/**
* Checks whether the x and y coordinates given are contained within this triangle including the stroke.
* @example
* ```ts
* // Basic stroke check
* const triangle = new Triangle(0, 0, 100, 0, 50, 100);
* const isOnStroke = triangle.strokeContains(25, 25, 4); // 4px line width
*
* // Check with different alignments
* const innerStroke = triangle.strokeContains(25, 25, 4, 1); // Inside
* const centerStroke = triangle.strokeContains(25, 25, 4, 0.5); // Centered
* const outerStroke = triangle.strokeContains(25, 25, 4, 0); // Outside
* ```
* @param pointX - The X coordinate of the point to test
* @param pointY - The Y coordinate of the point to test
* @param strokeWidth - The width of the line to check
* @param _alignment - The alignment of the stroke (1 = inner, 0.5 = centered, 0 = outer)
* @returns Whether the x/y coordinates are within this triangle's stroke
* @see {@link Triangle.contains} For checking fill containment
* @see {@link Triangle.getBounds} For getting stroke bounds
*/
strokeContains(pointX: number, pointY: number, strokeWidth: number, _alignment?: number): boolean;
/**
* Creates a clone of this Triangle
* @example
* ```ts
* // Basic cloning
* const original = new Triangle(0, 0, 100, 0, 50, 100);
* const copy = original.clone();
*
* // Clone and modify
* const modified = original.clone();
* modified.x3 = 75;
* modified.y3 = 150;
*
* // Verify independence
* console.log(original.y3); // 100
* console.log(modified.y3); // 150
* ```
* @returns A copy of the triangle
* @see {@link Triangle.copyFrom} For copying into existing triangle
* @see {@link Triangle.copyTo} For copying to another triangle
*/
clone(): Triangle;
/**
* Copies another triangle to this one.
* @example
* ```ts
* // Basic copying
* const source = new Triangle(0, 0, 100, 0, 50, 100);
* const target = new Triangle();
* target.copyFrom(source);
*
* // Chain with other operations
* const triangle = new Triangle()
* .copyFrom(source)
* .getBounds(rect);
* ```
* @param triangle - The triangle to copy from
* @returns Returns itself
* @see {@link Triangle.copyTo} For copying to another triangle
* @see {@link Triangle.clone} For creating new triangle copy
*/
copyFrom(triangle: Triangle): this;
/**
* Copies this triangle to another one.
* @example
* ```ts
* // Basic copying
* const source = new Triangle(0, 0, 100, 0, 50, 100);
* const target = new Triangle();
* source.copyTo(target);
*
* // Chain with other operations
* const result = source
* .copyTo(new Triangle())
* .getBounds();
* ```
* @remarks
* - Updates target triangle values
* - Copies all point coordinates
* - Returns target for chaining
* - More efficient than clone()
* @param triangle - The triangle to copy to
* @returns Returns given parameter
* @see {@link Triangle.copyFrom} For copying from another triangle
* @see {@link Triangle.clone} For creating new triangle copy
*/
copyTo(triangle: Triangle): Triangle;
/**
* Returns the framing rectangle of the triangle as a Rectangle object
* @example
* ```ts
* // Basic bounds calculation
* const triangle = new Triangle(0, 0, 100, 0, 50, 100);
* const bounds = triangle.getBounds();
* // bounds: x=0, y=0, width=100, height=100
*
* // Reuse existing rectangle
* const rect = new Rectangle();
* triangle.getBounds(rect);
* ```
* @param out - Optional rectangle to store the result
* @returns The framing rectangle
* @see {@link Rectangle} For rectangle properties
* @see {@link Triangle.contains} For checking if a point is inside
*/
getBounds(out?: Rectangle): Rectangle;
}
/**
* Builds a triangle to draw
*
* Ignored from docs since it is not directly exposed.
* @ignore
* @private
*/
export declare const buildTriangle: ShapeBuildCommand<Triangle>;
/**
* Represents a session for SVG parsing. Contains the current state and resources needed during parsing.
* @internal
*/
export interface Session {
/** The graphics context to render to */
context: GraphicsContext;
/** The current path being constructed */
path: GraphicsPath;
/** Map of definitions by id */
defs: Record<string, FillGradient>;
}
/**
* Parses an SVG element or string and renders it to a graphics context.
* Handles both SVG strings and SVG DOM elements as input.
* @param svg - The SVG content to parse, either as a string or element
* @param graphicsContext - Optional graphics context to render to
* @returns The graphics context with the SVG rendered into it
* @internal
*/
export declare function SVGParser(svg: string | SVGElement | SVGSVGElement, graphicsContext?: GraphicsContext): GraphicsContext;
/**
* Parses SVG gradient definitions and stores them in the session for later use.
* Currently supports linear gradients and has placeholder support for radial gradients.
* @param svg - The root SVG element to parse definitions from
* @param session - The parsing session to store definitions in
* @internal
*/
export declare function parseSVGDefinitions(svg: SVGElement, session: Session): void;
/**
* Parses a float value from an SVG element's attribute.
* This is commonly used for parsing numeric attributes like coordinates, dimensions,
* and other measurements from SVG elements.
* @param svg - The SVG element to get the attribute from
* @param id - The name of the attribute to parse (e.g. 'x', 'y', 'width', etc)
* @param defaultValue - The value to return if the attribute doesn't exist or can't be parsed
* @returns The parsed float value, or the default value if parsing fails
* @example
* // For SVG: <rect x="10.5" width="20"/>
* parseSVGFloatAttribute(rectElement, 'x', 0) // Returns 10.5
* parseSVGFloatAttribute(rectElement, 'y', 0) // Returns 0 since y is not specified
* @internal
*/
export declare function parseSVGFloatAttribute(svg: SVGElement, id: string, defaultValue: number): number;
/**
* Parses an SVG path data string and builds a GraphicsPath object from the commands.
* This function handles all standard SVG path commands including moves, lines, curves and arcs.
* It maintains state for the current position and subpaths to properly handle relative commands
* and path closures.
*
* Supported SVG commands:
* - M/m: Move to absolute/relative
* - L/l: Line to absolute/relative
* - H/h: Horizontal line absolute/relative
* - V/v: Vertical line absolute/relative
* - C/c: Cubic bezier curve absolute/relative
* - S/s: Smooth cubic bezier curve absolute/relative
* - Q/q: Quadratic bezier curve absolute/relative
* - T/t: Smooth quadratic bezier curve absolute/relative
* - A/a: Arc absolute/relative
* - Z/z: Close path
* @param svgPath - The SVG path data string to parse (e.g. "M0,0 L100,100")
* @param path - The GraphicsPath object to build the path into
* @returns The input path object with the SVG commands applied
* @internal
*/
export declare function parseSVGPath(svgPath: string, path: GraphicsPath): GraphicsPath;
/**
* A map of SVG style attributes and their default values.
* Each attribute has a type and default value used for SVG parsing.
* - 'paint' type can be a color or gradient
* - 'number' type is a numeric value
* - 'string' type is a text value
* @category scene
* @advanced
*/
export declare const styleAttributes: {
fill: {
type: string;
default: number;
};
"fill-opacity": {
type: string;
default: number;
};
stroke: {
type: string;
default: number;
};
"stroke-width": {
type: string;
default: number;
};
"stroke-opacity": {
type: string;
default: number;
};
"stroke-linecap": {
type: string;
default: string;
};
"stroke-linejoin": {
type: string;
default: string;
};
"stroke-miterlimit": {
type: string;
default: number;
};
"stroke-dasharray": {
type: string;
default: string;
};
"stroke-dashoffset": {
type: string;
default: number;
};
opacity: {
type: string;
default: number;
};
};
/**
* Represents the result of parsing SVG style attributes
* @internal
*/
export type StyleResult = {
/** The stroke style properties */
strokeStyle: StrokeStyle;
/** The fill style properties */
fillStyle: FillStyle;
/** Whether fill should be applied */
useFill: boolean;
/** Whether stroke should be applied */
useStroke: boolean;
};
/**
* Parses SVG style attributes and inline styles to determine fill and stroke properties.
* Handles both direct attributes and CSS-style declarations in the style attribute.
* @param svg - The SVG element to parse styles from
* @param session - The current SVG parsing session containing definitions
* @returns An object containing the parsed fill and stroke styles
* @internal
*/
export declare function parseSVGStyle(svg: SVGElement, session: Session): StyleResult;
/**
* Extracts the ID from an SVG url() reference.
*
* This function handles all valid SVG url() formats including:
* - url(#id)
* - url('#id')
* - url("#id")
* - url( #id )
* - url( '#id' )
* - url( "#id" )
*
* The regex pattern matches:
* - url followed by optional whitespace
* - opening parenthesis followed by optional whitespace
* - optional single or double quotes with optional whitespace
* - # followed by the ID (any chars except quotes, whitespace, or closing paren)
* - optional single or double quotes with optional whitespace
* - closing parenthesis
* @param url - The SVG url() string to parse
* @returns The extracted ID string, or empty string if no valid ID found
* @internal
*/
export declare function extractSvgUrlId(url: string): string;
/**
* Determines if subpaths represent nested shapes or multiple holes pattern.
* @param subpathsWithArea - Array of subpaths with their calculated areas
* @returns True if nested pattern, false if multiple holes pattern
* @internal
*/
export declare function checkForNestedPattern(subpathsWithArea: Array<{
path: string;
area: number;
}>): boolean;
/**
* Gets fill instruction data from a graphics context.
* @param context - The graphics context
* @param index - Index of the fill instruction (default: 0)
* @returns The fill instruction data
* @throws Error if instruction at index is not a fill instruction
* @internal
*/
export declare function getFillInstructionData(context: GraphicsContext, index?: number): {
style: ConvertedFillStyle;
path: GraphicsPath;
hole?: GraphicsPath;
};
/**
* Extracts individual subpaths from SVG path data by splitting on Move commands.
* @param pathData - The SVG path data string
* @returns Array of subpath strings
* @internal
*/
export declare function extractSubpaths(pathData: string): string[];
/**
* Calculates the area of a path using bounding box estimation.
* @param pathData - The SVG path data string
* @returns The estimated area of the path
* @internal
*/
export declare function calculatePathArea(pathData: string): number;
/**
* Parses SVG path data and appends instructions to a GraphicsPath.
* @param pathData - The SVG path data string
* @param graphicsPath - The GraphicsPath to append instructions to
* @internal
*/
export declare function appendSVGPath(pathData: string, graphicsPath: GraphicsPath): void;
/**
* A record of shape builders, keyed by shape type.
* @category scene
* @advanced
*/
export declare const shapeBuilders: Record<string, ShapeBuildCommand>;
/**
* @param context
* @param gpuContext
* @internal
*/
export declare function buildContextBatches(context: GraphicsContext, gpuContext: GpuGraphicsContext): void;
/**
* Options for building geometry from a graphics path.
* Provides a possibility to specify a transformation Matrix for the texture's UVs and output mesh geometry.
* @example
* ```ts
* const options: GeometryPathOptions = {
* path: new GraphicsPath().rect(0, 0, 64, 64),
* textureMatrix: new Matrix()
* .scale(2, 2)
* .rotate(Math.PI / 4),
* out: meshGeometry
* };
* const geometry:MeshGeometry = buildGeometryFromPath(options);
* const mesh = new Mesh({
* geometry: meshGeometry,
* texture: bunnyTexture
* });
* ```
* @category scene
* @advanced
*/
export interface GeometryPathOptions {
/** the path to build the geometry from */
path: GraphicsPath;
/** a `Matrix` that can be used to modify the texture UVs of the path being built */
textureMatrix?: Matrix;
/** an optional `MeshGeometry` to write too instead of creating a new one*/
out?: MeshGeometry;
}
/**
* When building a mesh, it helps to leverage the simple API we have in `GraphicsPath` as it can often be easier to
* define the geometry in a more human-readable way. This function takes a `GraphicsPath` and returns a `MeshGeometry`.
* @example
* ```ts
*
* const path = new GraphicsPath()
* .drawRect(0, 0, 100, 100)
*
* const geometry:MeshGeometry = buildGeometryFromPath(path);
*
* const mesh = new Mesh({geometry});
*
* ```
* You can also pass in a Matrix to transform the uvs as by default you may want to control how they are set up.
* @param options - either a `GraphicsPath` or `GeometryPathOptions`
* @returns a new `MeshGeometry` instance build from the path
* @category scene
* @advanced
*/
export declare function buildGeometryFromPath(options: GraphicsPath | GeometryPathOptions): MeshGeometry;
/**
* Converts a value to a fill style, we do this as PixiJS has a number of ways to define a fill style
* They can be a direct color, a texture, a gradient, or an object with these values in them
* This function will take any of these input types and convert them into a single object
* that PixiJS can understand and use internally.
* @param value - The value to convert to a fill style
* @param defaultStyle - The default fill style to use
* @private
*/
export declare function toFillStyle<T extends FillInput>(value: T, defaultStyle: ConvertedFillStyle): ConvertedFillStyle;
/**
* Converts a value to a stroke style, similar to `toFillStyle` but for strokes
* @param value - The value to convert to a stroke style
* @param defaultStyle - The default stroke style to use
* @private
*/
export declare function toStrokeStyle(value: StrokeInput, defaultStyle: ConvertedStrokeStyle): ConvertedStrokeStyle;
/**
* Generates a texture matrix for mapping textures onto shapes.
* This function handles both local and global texture space mapping.
*
* In local space, the texture is mapped to fit exactly within the bounds of the shape.
* In global space, the texture is mapped using its own dimensions and position.
* @param out - The matrix to store the result in
* @param style - The fill style containing texture and mapping properties
* @param shape - The shape to map the texture onto
* @param matrix - Optional transform matrix to apply
* @returns The generated texture matrix for UV mapping
* @example
* ```ts
* const matrix = new Matrix();
* const textureMatrix = generateTextureMatrix(matrix, fillStyle, shape);
* // textureMatrix now contains the proper UV mapping for the texture
* ```
* @internal
*/
export declare function generateTextureMatrix(out: Matrix, style: FillStyle | StrokeStyle, shape: ShapePrimitive, matrix?: Matrix): Matrix;
/**
* @param points
* @internal
*/
export declare function getOrientationOfPoints(points: number[]): number;
/**
* @param points
* @param holes
* @param vertices
* @param verticesStride
* @param verticesOffset
* @param indices
* @param indicesOffset
* @internal
*/
export declare function triangulateWithHoles(points: number[], holes: number[], vertices: number[], verticesStride: number, verticesOffset: number, indices: number[], indicesOffset: number): void;
/**
* Constructor options used for `PlaneGeometry` instances.
* ```js
* const planeGeometry = new PlaneGeometry({
* width: 100,
* height: 100,
* verticesX: 10,
* verticesY: 10,
* });
* ```
* @see {@link PlaneGeometry}
* @category scene
* @advanced
*/
export interface PlaneGeometryOptions {
/** Width of plane */
width?: number;
/** Height of plane */
height?: number;
/** Number of vertices on x-axis */
verticesX?: number;
/** Number of vertices on y-axis */
verticesY?: number;
}
/**
* The PlaneGeometry allows you to draw a 2d plane
* @category scene
* @advanced
*/
export declare class PlaneGeometry extends MeshGeometry {
static defaultOptions: PlaneGeometryOptions & MeshGeometryOptions;
/** The number of vertices on x-axis */
verticesX: number;
/** The number of vertices on y-axis */
verticesY: number;
/** The width of plane */
width: number;
/** The height of plane */
height: number;
/**
* @param {PlaneGeometryOptions} options - Options to be applied to plane geometry
*/
constructor(options: PlaneGeometryOptions);
/** @deprecated since 8.0.0 */
constructor(width?: number, height?: number, verticesX?: number, verticesY?: number);
/**
* Refreshes plane coordinates
* @param options - Options to be applied to plane geometry
*/
build(options: PlaneGeometryOptions): void;
}
/**
* Constructor options used for `PerspectivePlaneGeometry` instances.
* @category scene
* @advanced
*/
export interface PerspectivePlaneGeometryOptions extends PlaneGeometryOptions {
/** The width of the plane */
width: number;
/** The height of the plane */
height: number;
}
/**
* A PerspectivePlaneGeometry allows you to draw a 2d plane with perspective. Where ever you move the corners
* the texture will be projected to look like it is in 3d space. Great for mapping a 2D mesh into a 3D scene.
*
* IMPORTANT: This is not a full 3D mesh, it is a 2D mesh with a perspective projection applied to it :)
*
* ```js
* const perspectivePlaneGeometry = new PerspectivePlaneGeometry({
* width: 100,
* height: 100,
* verticesX: 10,
* verticesY: 10,
* });
* ```
* @see {@link PerspectivePlaneGeometry}
* @category scene
* @advanced
*/
export declare class PerspectivePlaneGeometry extends PlaneGeometry {
/** The corner points of the quad you can modify these directly, if you do make sure to call `updateProjection` */
corners: [
number,
number,
number,
number,
number,
number,
number,
number
];
private readonly _projectionMatrix;
/**
* @param options - Options to be applied to MeshPlane
* @param options.width - The width of the plane
* @param options.height - The height of the plane
* @param options.verticesX - The amount of vertices on the x axis
* @param options.verticesY - The amount of vertices on the y axis
*/
constructor(options: PerspectivePlaneGeometryOptions);
/**
* Will set the corners of the quad to the given coordinates
* Calculating the perspective so it looks correct!
* @param x0 - x coordinate of the first corner
* @param y0 - y coordinate of the first corner
* @param x1 - x coordinate of the second corner
* @param y1 - y coordinate of the second corner
* @param x2 - x coordinate of the third corner
* @param y2 - y coordinate of the third corner
* @param x3 - x coordinate of the fourth corner
* @param y3 - y coordinate of the fourth corner
*/
setCorners(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): void;
/** Update the projection matrix based on the corners */
updateProjection(): void;
}
/**
* Constructor options used for `MeshPlane` instances. Defines how a texture is mapped
* onto a plane with configurable vertex density.
* @example
* ```ts
* // Basic plane with default vertex density
* const plane = new MeshPlane({
* texture: Assets.get('background.png')
* });
*
* // High-detail plane for complex deformations
* const detailedPlane = new MeshPlane({
* texture: Assets.get('landscape.jpg'),
* verticesX: 20,
* verticesY: 20
* });
* ```
* @see {@link MeshPlane} For the mesh implementation
* @see {@link PlaneGeometry} For the underlying geometry
* @category scene
* @standard
* @noInheritDoc
*/
export interface MeshPlaneOptions extends Omit<MeshOptions, "geometry"> {
/** The texture to use on the plane. */
texture: Texture;
/**
* Number of vertices along the X axis. More vertices allow for more detailed deformations.
* @default 10
*/
verticesX?: number;
/**
* Number of vertices along the Y axis. More vertices allow for more detailed deformations.
* @default 10
*/
verticesY?: number;
}
/**
* A mesh that renders a texture mapped to a plane with configurable vertex density.
* Useful for creating distortion effects, bent surfaces, and animated deformations.
* @example
* ```ts
* // Create a basic plane
* const plane = new MeshPlane({
* texture: Assets.get('background.png'),
* verticesX: 10,
* verticesY: 10
* });
*
* // Get the buffer for vertex positions.
* const { buffer } = plane.geometry.getAttribute('aPosition');
*
* // Listen for animate update
* let timer = 0;
*
* app.ticker.add(() =>
* {
* // Randomize the vertices positions a bit to create movement.
* for (let i = 0; i < buffer.data.length; i++)
* {
* buffer.data[i] += Math.sin(timer / 10 + i) * 0.5;
* }
* buffer.update();
* timer++;
* });
*
* // Change texture dynamically
* plane.texture = Assets.get('newTexture.png');
* ```
* @category scene
* @standard
*/
export declare class MeshPlane extends Mesh {
/**
* Controls whether the mesh geometry automatically updates when the texture dimensions change.
* When true, the mesh will resize to match any texture updates. When false, the mesh maintains
* its original dimensions regardless of texture changes.
* @example
* ```ts
* // Create a plane that auto-resizes with texture changes
* const plane = new MeshPlane({
* texture: Assets.get('small.png'),
* verticesX: 10,
* verticesY: 10
* });
*
* // Plane will automatically resize to match new texture
* plane.texture = Assets.get('large.png');
*
* // Disable auto-resizing to maintain original dimensions
* plane.autoResize = false;
*
* // Plane keeps its size even with new texture
* plane.texture = Assets.get('different.png');
*
* // Manually update geometry if needed
* const geometry = plane.geometry as PlaneGeometry;
* geometry.width = plane.texture.width;
* geometry.height = plane.texture.height;
* geometry.build();
* ```
* @default true
* @see {@link MeshPlane#texture} For changing the texture
* @see {@link PlaneGeometry} For manual geometry updates
*/
autoResize: boolean;
protected _textureID: number;
/**
* @param options - Options to be applied to MeshPlane
*/
constructor(options: MeshPlaneOptions);
/**
* Method used for overrides, to do something in case texture frame was changed.
* Meshes based on plane can override it and change more details based on texture.
* @internal
*/
textureUpdated(): void;
set texture(value: Texture);
/**
* The texture that the mesh plane uses for rendering. When changed, automatically updates
* geometry dimensions if autoResize is true and manages texture update event listeners.
* @example
* ```ts
* const plane = new MeshPlane({
* texture: Assets.get('initial.png'),
* verticesX: 10,
* verticesY: 10
* });
*
* // Update texture and auto-resize geometry
* plane.texture = Assets.get('larger.png');
* ```
* @see {@link MeshPlane#autoResize} For controlling automatic geometry updates
* @see {@link PlaneGeometry} For manual geometry updates
* @see {@link Texture} For texture creation and management
*/
get texture(): Texture;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* meshPlane.destroy();
* meshPlane.destroy(true);
* meshPlane.destroy({ texture: true, textureSource: true });
*/
destroy(options?: DestroyOptions): void;
}
/**
* Constructor options used for `PerspectiveMesh` instances. Defines the geometry and appearance
* of a 2D mesh with perspective projection.
* @example
* ```ts
* // Create a perspective mesh with a texture
* const mesh = new PerspectiveMesh({
* texture: Texture.from('myImage.png'),
* verticesX: 20,
* verticesY: 20,
* // Define corners clockwise from top-left
* x0: 0, y0: 0, // Top-left
* x1: 100, y1: 20, // Top-right (raised)
* x2: 100, y2: 100, // Bottom-right
* x3: 0, y3: 80 // Bottom-left (raised)
* });
*
* // Create a skewed perspective
* const skewedMesh = new PerspectiveMesh({
* texture: Texture.from('background.jpg'),
* verticesX: 15, // More vertices for smoother perspective
* verticesY: 15,
* x0: 0, y0: 30, // Shifted top-left
* x1: 128, y1: 0, // Raised top-right
* x2: 128, y2: 128, // Normal bottom-right
* x3: 0, y3: 98 // Shifted bottom-left
* });
* ```
* @extends MeshPlaneOptions
* @see {@link PerspectiveMesh} For the mesh implementation
* @see {@link PerspectivePlaneGeometry} For the underlying geometry
* @category scene
* @standard
* @noInheritDoc
*/
export interface PerspectivePlaneOptions extends MeshPlaneOptions {
/** The x-coordinate of the top-left corner */
x0?: number;
/** The y-coordinate of the top-left corner */
y0?: number;
/** The x-coordinate of the top-right corner */
x1?: number;
/** The y-coordinate of the top-right corner */
y1?: number;
/** The x-coordinate of the bottom-right corner */
x2?: number;
/** The y-coordinate of the bottom-right corner */
y2?: number;
/** The x-coordinate of the bottom-left corner */
x3?: number;
/** The y-coordinate of the bottom-left corner */
y3?: number;
}
/**
* A perspective mesh that allows you to draw a 2d plane with perspective. Where ever you move the corners
* the texture will be projected to look like it is in 3d space. Great for mapping a 2D mesh into a 3D scene.
*
* The calculations is done at the uv level. This means that the more vertices you have the more smooth
* the perspective will be. If you have a low amount of vertices you may see the texture stretch. Too many vertices
* could be slower. It is a balance between performance and quality! We leave that to you to decide.
*
* > [!IMPORTANT] This is not a full 3D mesh, it is a 2D mesh with a perspective projection applied to it.
* @category scene
* @standard
* @see {@link PerspectiveMesh}
* @example
* ```ts
* // Create a perspective mesh with a texture
* const mesh = new PerspectiveMesh({
* texture: Texture.from('myImage.png'),
* verticesX: 20,
* verticesY: 20,
* // Define corners clockwise from top-left
* x0: 0, y0: 0, // Top-left
* x1: 100, y1: 20, // Top-right (raised)
* x2: 100, y2: 100, // Bottom-right
* x3: 0, y3: 80 // Bottom-left (raised)
* });
* ```
*/
export declare class PerspectiveMesh extends Mesh<PerspectivePlaneGeometry> {
/**
* Default options for creating a PerspectiveMesh instance.
*
* Creates a 100x100 pixel square mesh
* with a white texture and 10x10 vertex grid for the perspective calculations.
* @example
* ```ts
* // Change defaults globally
* PerspectiveMesh.defaultOptions = {
* ...PerspectiveMesh.defaultOptions,
* verticesX: 15,
* verticesY: 15,
* // Move top edge up for default skew
* y0: -20,
* y1: -20
* };
* ```
* @see {@link PerspectivePlaneOptions} For all available options
* @see {@link PerspectivePlaneGeometry} For how vertices affect perspective quality
*/
static defaultOptions: PerspectivePlaneOptions;
/**
* @param options - Options to be applied to PerspectiveMesh
*/
constructor(options: PerspectivePlaneOptions);
/** Update the geometry when the texture is updated */
protected textureUpdated(): void;
set texture(value: Texture);
/**
* The texture that the mesh uses for rendering. When changed, automatically updates
* the geometry to match the new texture dimensions.
* @example
* ```ts
* const mesh = new PerspectiveMesh({
* texture: Texture.from('initial.png'),
* });
*
* // Update texture and maintain perspective
* mesh.texture = Texture.from('newImage.png');
* ```
* @see {@link Texture} For texture creation and management
* @see {@link PerspectiveMesh#setCorners} For adjusting the mesh perspective
*/
get texture(): Texture;
/**
* Sets the corners of the mesh to create a perspective transformation. The corners should be
* specified in clockwise order starting from the top-left.
*
* The mesh automatically recalculates the UV coordinates to create the perspective effect.
* @example
* ```ts
* const mesh = new PerspectiveMesh({
* texture: Texture.from('myImage.png'),
* });
*
* // Create a basic perspective tilt
* mesh.setCorners(
* 0, 0, // Top-left
* 100, 20, // Top-right (raised)
* 100, 100, // Bottom-right
* 0, 80 // Bottom-left
* );
*
* // Create a skewed billboard effect
* mesh.setCorners(
* 0, 30, // Top-left (shifted down)
* 128, 0, // Top-right (raised)
* 128, 128, // Bottom-right
* 0, 98 // Bottom-left (shifted up)
* );
*
* // Animate perspective
* app.ticker.add((delta) => {
* const time = performance.now() / 1000;
* const wave = Math.sin(time) * 20;
*
* mesh.setCorners(
* 0, wave, // Top-left
* 100, -wave, // Top-right
* 100, 100, // Bottom-right
* 0, 100 // Bottom-left
* );
* });
* ```
* @param x0 - x-coordinate of the top-left corner
* @param y0 - y-coordinate of the top-left corner
* @param x1 - x-coordinate of the top-right corner
* @param y1 - y-coordinate of the top-right corner
* @param x2 - x-coordinate of the bottom-right corner
* @param y2 - y-coordinate of the bottom-right corner
* @param x3 - x-coordinate of the bottom-left corner
* @param y3 - y-coordinate of the bottom-left corner
* @returns The PerspectiveMesh instance for method chaining
* @see {@link PerspectivePlaneGeometry} For the underlying geometry calculations
*/
setCorners(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): void;
}
/**
* Apply a projective transformation to a plane geometry
* @param width - The width of the plane
* @param height - The height of the plane
* @param geometry - The plane geometry to apply the transformation to
* @param transformationMatrix - The transformation matrix to apply
* @internal
*/
export declare function applyProjectiveTransformationToPlane(width: number, height: number, geometry: PlaneGeometry, transformationMatrix: ArrayFixed<number, 9>): void;
type Matrix3x3 = ArrayFixed<number, 9>;
/**
* Compute a 2D projection matrix
* @param out - The matrix to store the result in
* @param x1s - The x coordinate of the first source point
* @param y1s - The y coordinate of the first source point
* @param x1d - The x coordinate of the first destination point
* @param y1d - The y coordinate of the first destination point
* @param x2s - The x coordinate of the second source point
* @param y2s - The y coordinate of the second source point
* @param x2d - The x coordinate of the second destination point
* @param y2d - The y coordinate of the second destination point
* @param x3s - The x coordinate of the third source point
* @param y3s - The y coordinate of the third source point
* @param x3d - The x coordinate of the third destination point
* @param y3d - The y coordinate of the third destination point
* @param x4s - The x coordinate of the fourth source point
* @param y4s - The y coordinate of the fourth source point
* @param x4d - The x coordinate of the fourth destination point
* @param y4d - The y coordinate of the fourth destination point
* @returns - The computed 2D projection matrix
* @private
*/
export declare function compute2DProjection(out: Matrix3x3, x1s: number, y1s: number, x1d: number, y1d: number, x2s: number, y2s: number, x2d: number, y2d: number, x3s: number, y3s: number, x3d: number, y3d: number, x4s: number, y4s: number, x4d: number, y4d: number): Matrix3x3;
/**
* Constructor options used for `MeshRope` instances. Allows configuration of a rope-like mesh
* that follows a series of points with a texture applied.
* @example
* ```ts
* // Create a basic rope with two points
* const rope = new MeshRope({
* texture: Texture.from('snake.png'),
* points: [
* new Point(0, 0),
* new Point(100, 0)
* ]
* });
*
* // Create a rope with high-quality texture scaling
* const highQualityRope = new MeshRope({
* texture: Texture.from('rope-hd.png'),
* points: [
* new Point(0, 0),
* new Point(50, 25),
* new Point(100, 0)
* ],
* textureScale: 0.5 // Downscale HD texture for better quality
* });
* ```
* @see {@link MeshRope} For the rope implementation
* @see {@link RopeGeometry} For the underlying geometry
* @category scene
* @standard
* @noInheritDoc
*/
export interface MeshRopeOptions extends Omit<MeshOptions, "geometry"> {
/** The texture to use on the rope */
texture: Texture;
/** An array of points that determine the rope's shape and path */
points: PointData[];
/**
* Controls how the texture is scaled along the rope.
* - If 0 (default), the texture stretches to fit between points
* - If > 0, texture repeats with preserved aspect ratio
* - Larger textures with textureScale < 1 can reduce artifacts
* @default 0
*/
textureScale?: number;
}
/**
* A specialized mesh that renders a texture along a path defined by points. Perfect for
* creating snake-like animations, chains, ropes, and other flowing objects.
* @example
* ```ts
* // Create a snake with multiple segments
* const points = [];
* for (let i = 0; i < 20; i++) {
* points.push(new Point(i * 50, 0));
* }
*
* const snake = new MeshRope({
* texture: Texture.from('snake.png'),
* points,
* textureScale: 0.5
* });
*
* // Animate the snake
* app.ticker.add((delta) => {
* const time = performance.now() / 1000;
*
* // Update points to create wave motion
* for (let i = 0; i < points.length; i++) {
* points[i].y = Math.sin(i * 0.5 + time) * 30;
* points[i].x = (i * 50) + Math.cos(i * 0.3 + time) * 20;
* }
* });
*
* // Disable auto updates if manually updating
* snake.autoUpdate = false;
* ```
* @category scene
* @standard
*/
export declare class MeshRope extends Mesh {
/**
* Default options for creating a MeshRope instance. These values are used when specific
* options aren't provided in the constructor.
* @example
* ```ts
* // Use default options globally
* MeshRope.defaultOptions = {
* textureScale: 0.5 // Set higher quality texture scaling
* };
*
* // Create rope with modified defaults
* const rope = new MeshRope({
* texture: Texture.from('rope.png'),
* points: [
* new Point(0, 0),
* new Point(100, 0)
* ]
* }); // Will use textureScale: 0.5
* ```
* @property {number} textureScale - Controls texture scaling along the rope (0 = stretch)
* @see {@link MeshRopeOptions} For all available options
*/
static defaultOptions: Partial<MeshRopeOptions>;
/**
* Controls whether the rope's vertices are automatically recalculated each frame based on
* its points. When true, the rope will update to follow point movements. When false,
* manual updates are required.
* @example
* ```ts
* const points = [];
* for (let i = 0; i < 20; i++) {
* points.push(new Point(i * 50, 0));
* }
*
* const rope = new MeshRope({
* texture: Texture.from('rope.png'),
* points
* });
*
* // Auto-update (default)
* app.ticker.add(() => {
* // Points will automatically update the rope
* for (let i = 0; i < points.length; i++) {
* points[i].y = Math.sin(i * 0.5 + performance.now() / 1000) * 30;
* }
* });
*
* // Manual update
* rope.autoUpdate = false;
* app.ticker.add(() => {
* // Update points
* for (let i = 0; i < points.length; i++) {
* points[i].y = Math.sin(i * 0.5 + performance.now() / 1000) * 30;
* }
* // Manually trigger update
* (rope.geometry as RopeGeometry).update();
* });
* ```
* @default true
* @see {@link RopeGeometry#update} For manual geometry updates
*/
autoUpdate: boolean;
/**
* Note: The wrap mode of the texture is set to REPEAT if `textureScale` is positive.
* @param options
* @param options.texture - The texture to use on the rope.
* @param options.points - An array of {@link math.Point} objects to construct this rope.
* @param {number} options.textureScale - Optional. Positive values scale rope texture
* keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture
* and downsampling here. If set to zero, texture will be stretched instead.
*/
constructor(options: MeshRopeOptions);
private _render;
}
/**
* Options for creating a SimpleMesh instance. Defines the texture, geometry data, and rendering topology
* for a basic mesh with direct vertex manipulation capabilities.
* @example
* ```ts
* // Create a basic textured triangle
* const mesh = new MeshSimple({
* texture: Texture.from('sprite.png'),
* vertices: new Float32Array([
* 0, 0, // Vertex 1
* 100, 0, // Vertex 2
* 50, 100 // Vertex 3
* ]),
* uvs: new Float32Array([
* 0, 0, // UV 1
* 1, 0, // UV 2
* 0.5, 1 // UV 3
* ])
* });
*
* // Create an indexed quad with custom topology
* const quadMesh = new MeshSimple({
* texture: Texture.from('square.png'),
* vertices: new Float32Array([
* 0, 0, // Top-left
* 100, 0, // Top-right
* 100, 100, // Bottom-right
* 0, 100 // Bottom-left
* ]),
* uvs: new Float32Array([
* 0, 0, // Top-left
* 1, 0, // Top-right
* 1, 1, // Bottom-right
* 0, 1 // Bottom-left
* ]),
* indices: new Uint32Array([
* 0, 1, 2, // Triangle 1
* 0, 2, 3 // Triangle 2
* ]),
* topology: 'triangle-list'
* });
* ```
* @category scene
* @advanced
* @noInheritDoc
*/
export interface SimpleMeshOptions extends Omit<MeshOptions, "geometry"> {
/** The texture to use */
texture: Texture;
/** Array of vertex positions as x,y pairs. Each vertex is 2 floats - x, y */
vertices?: Float32Array;
/** Array of UV coordinates for texture mapping. Each UV is 2 floats - u, v */
uvs?: Float32Array;
/** Array of indices defining triangles. Each triangle is 3 indices into the vertices array. */
indices?: Uint32Array;
/**
* How vertices are connected to form triangles.
* - 'triangle-list': Individual triangles (default)
* - 'triangle-strip': Connected triangle strip
* - 'line-list': Lines between vertices
* - 'line-strip': Connected line strip
* - 'point-list': Points rendered individually
* @default 'triangle-list'
*/
topology?: Topology;
}
/**
* A simplified mesh class that provides an easy way to create and manipulate textured meshes
* with direct vertex control. Perfect for creating custom shapes, deformable sprites, and
* simple 2D effects.
* @example
* ```ts
* // Create a basic triangle mesh
* const triangleMesh = new MeshSimple({
* texture: Texture.from('sprite.png'),
* vertices: new Float32Array([
* 0, 0, // Top-left
* 100, 0, // Top-right
* 50, 100 // Bottom-center
* ]),
* uvs: new Float32Array([
* 0, 0, // Map top-left of texture
* 1, 0, // Map top-right of texture
* 0.5, 1 // Map bottom-center of texture
* ])
* });
*
* // Animate vertices
* app.ticker.add(() => {
* const time = performance.now() / 1000;
* const vertices = triangleMesh.vertices;
*
* // Move the top vertex up and down
* vertices[1] = Math.sin(time) * 20;
* triangleMesh.vertices = vertices; // Update vertices
*
* // Auto-updates by default
* });
*
* // Create a line strip
* const lineMesh = new MeshSimple({
* texture: Texture.from('line.png'),
* vertices: new Float32Array([
* 0, 0,
* 50, 50,
* 100, 0,
* 150, 50
* ]),
* topology: 'line-strip'
* });
*
* // Manual vertex updates
* lineMesh.autoUpdate = false;
* const vertices = lineMesh.vertices;
* vertices[0] += 10;
* lineMesh.vertices = vertices; // Update vertices manually
* // Update the vertices buffer manually
* lineMesh.geometry.getBuffer('aPosition').update();
* ```
* @category scene
* @advanced
* @see {@link Mesh} For more advanced mesh customization
* @see {@link MeshGeometry} For direct geometry manipulation
*/
export declare class MeshSimple extends Mesh {
/**
* Controls whether the mesh's vertex buffer is automatically updated each frame.
* When true, vertex changes will be reflected immediately. When false, manual updates are required.
* @example
* ```ts
* // Auto-update mode (default)
* mesh.autoUpdate = true;
* app.ticker.add(() => {
* // Vertices update automatically each frame
* const vertices = mesh.vertices;
* vertices[1] = Math.sin(performance.now() / 1000) * 20;
* mesh.vertices = vertices;
* });
*
* // Manual update mode
* mesh.autoUpdate = false;
* app.ticker.add(() => {
* // Update vertices
* const vertices = mesh.vertices;
* vertices[1] = Math.sin(performance.now() / 1000) * 20;
* mesh.vertices = vertices;
*
* // Manually trigger buffer update
* mesh.geometry.getBuffer('aPosition').update();
* });
* ```
* @default true
* @see {@link MeshGeometry#getBuffer} For manual buffer updates
* @see {@link MeshSimple#vertices} For accessing vertex data
*/
autoUpdate: boolean;
/**
* @param options - Options to be used for construction
*/
constructor(options: SimpleMeshOptions);
/**
* The vertex positions of the mesh as a TypedArray. Each vertex is represented by two
* consecutive values (x, y) in the array. Changes to these values will update the mesh's shape.
* @example
* ```ts
* // Read vertex positions
* const vertices = mesh.vertices;
* console.log('First vertex:', vertices[0], vertices[1]);
*
* // Modify vertices directly
* vertices[0] += 10; // Move first vertex right
* vertices[1] -= 20; // Move first vertex up
*
* // Animate vertices
* app.ticker.add(() => {
* const time = performance.now() / 1000;
* const vertices = mesh.vertices;
*
* // Wave motion
* for (let i = 0; i < vertices.length; i += 2) {
* vertices[i + 1] = Math.sin(time + i * 0.5) * 20;
* }
* });
* ```
* @see {@link MeshSimple#autoUpdate} For controlling vertex buffer updates
* @see {@link MeshGeometry#getBuffer} For direct buffer access
*/
get vertices(): TypedArray;
set vertices(value: TypedArray);
private _render;
}
/**
* Constructor options used for `RopeGeometry` instances.
* ```js
* const ropeGeometry = new RopeGeometry({
* points: [new Point(0, 0), new Point(100, 0)],
* width: 10,
* textureScale: 0,
* });
* ```
* @see {@link RopeGeometry}
* @category scene
* @advanced
*/
export interface RopeGeometryOptions {
/** The width (i.e., thickness) of the rope. */
width?: number;
/** An array of points that determine the rope. */
points?: PointData[];
/**
* Rope texture scale, if zero then the rope texture is stretched.
* By default the rope texture will be stretched to match
* rope length. If textureScale is positive this value will be treated as a scaling
* factor and the texture will preserve its aspect ratio instead. To create a tiling rope
* set baseTexture.wrapMode to 'repeat' and use a power of two texture,
* then set textureScale=1 to keep the original texture pixel size.
* In order to reduce alpha channel artifacts provide a larger texture and downsample -
* i.e. set textureScale=0.5 to scale it down twice.
*/
textureScale?: number;
}
/**
* RopeGeometry allows you to draw a geometry across several points and then manipulate these points.
* @example
* import { Point, RopeGeometry } from 'pixi.js';
*
* for (let i = 0; i < 20; i++) {
* points.push(new Point(i * 50, 0));
* };
* const rope = new RopeGeometry(100, points);
* @category scene
* @advanced
*/
export declare class RopeGeometry extends MeshGeometry {
/** Default options for RopeGeometry constructor. */
static defaultOptions: RopeGeometryOptions & MeshGeometryOptions;
/** An array of points that determine the rope. */
points: PointData[];
/** Rope texture scale, if zero then the rope texture is stretched. */
readonly textureScale: number;
/**
* The width (i.e., thickness) of the rope.
* @readonly
* @internal
*/
_width: number;
/**
* @param options - Options to be applied to rope geometry
*/
constructor(options: RopeGeometryOptions);
/**
* The width (i.e., thickness) of the rope.
* @readonly
*/
get width(): number;
/** Refreshes Rope indices and uvs */
private _build;
/** refreshes vertices of Rope mesh */
updateVertices(): void;
/** Refreshes Rope indices and uvs */
update(): void;
}
/**
* A MeshAdaptor that uses the WebGL to render meshes.
* @category rendering
* @ignore
*/
export declare class GlMeshAdaptor implements MeshAdaptor {
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipesAdaptor
];
readonly name: "mesh";
};
private _shader;
init(): void;
execute(meshPipe: MeshPipe, mesh: Mesh): void;
destroy(): void;
}
/**
* The WebGL adaptor for the mesh system. Allows the Mesh System to be used with the WebGl renderer
* @category rendering
* @ignore
*/
export declare class GpuMeshAdapter implements MeshAdaptor {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUPipesAdaptor
];
readonly name: "mesh";
};
private _shader;
init(): void;
execute(meshPipe: MeshPipe, mesh: Mesh): void;
destroy(): void;
}
/**
* @param texture
* @param out
* @internal
*/
export declare function getTextureDefaultMatrix(texture: Texture, out: Matrix): Matrix;
/**
* Represents a particle with properties for position, scale, rotation, color, and texture.
* Particles are lightweight alternatives to sprites, optimized for use in particle systems.
* @example
* ```ts
* // Create a basic particle
* const particle = new Particle({
* texture: Texture.from('particle.png'),
* x: 100,
* y: 100,
* scaleX: 0.5,
* scaleY: 0.5,
* rotation: Math.PI / 4, // 45 degrees
* tint: 0xff0000, // Red tint
* alpha: 0.8 // Slightly transparent
* });
*
* // Modify particle properties
* particle.x += 10; // Move right
* particle.rotation += 0.1; // Rotate slightly
* particle.alpha = 0.5; // Change transparency
*
* // Use anchor points (0-1 range)
* particle.anchorX = 0.5; // Center horizontally
* particle.anchorY = 0.5; // Center vertically
* ```
* @category scene
* @standard
*/
export interface IParticle {
/** The x-coordinate of the particle position */
x: number;
/** The y-coordinate of the particle position */
y: number;
/**
* The horizontal scale factor of the particle
* @default 1
*/
scaleX: number;
/**
* The vertical scale factor of the particle
* @default 1
*/
scaleY: number;
/**
* The x-coordinate of the particle's anchor point (0-1 range)
* @default 0
*/
anchorX: number;
/**
* The y-coordinate of the particle's anchor point (0-1 range)
* @default 0
*/
anchorY: number;
/**
* The rotation of the particle in radians
* @default 0
*/
rotation: number;
/**
* The color of the particle as a 32-bit RGBA value
* @default 0xffffffff
*/
color: number;
/** The texture used to render this particle */
texture: Texture;
}
/**
* Configuration options for creating a new particle. All properties except texture are optional
* and will use default values if not specified.
* @example
* ```ts
* // Create a basic red particle
* const particle = new Particle({
* texture: Texture.from('particle.png'),
* tint: 0xff0000,
* alpha: 0.8
* });
*
* // Create a scaled and rotated particle
* const rotatedParticle = new Particle({
* texture: Texture.from('star.png'),
* x: 100,
* y: 100,
* scaleX: 2,
* scaleY: 2,
* rotation: Math.PI / 4,
* anchorX: 0.5,
* anchorY: 0.5
* });
*
* // Use color strings for tint
* const coloredParticle = new Particle({
* texture: Texture.from('circle.png'),
* tint: '#ff00ff', // Magenta
* alpha: 0.5, // Half transparent
* x: 200,
* y: 200
* });
* ```
* @see {@link Particle} For the particle implementation
* @see {@link IParticle} For the full particle interface
* @category scene
* @standard
* @category scene
* @standard
*/
export type ParticleOptions = Omit<Partial<IParticle>, "color"> & {
/** The texture used to render this particle */
texture: Texture;
/** The tint color as a hex number or CSS color string */
tint?: ColorSource;
/** The alpha transparency (0-1) */
alpha?: number;
};
/**
* Represents a single particle within a particle container. This class implements the IParticle interface,
* providing properties and methods to manage the particle's position, scale, rotation, color, and texture.
*
* The reason we use a particle over a sprite is that these are much lighter weight and we can create a lot of them
* without taking on the overhead of a full sprite.
* @example
* ```javascript
* const particle = new Particle({
* texture,
* x: 100,
* y: 100,
* scaleX: 0.5,
* scaleY: 0.5,
* rotation: Math.PI / 2,
* color: 0xff0000,
* });
* ```
* @category scene
* @standard
*/
export declare class Particle implements IParticle {
/**
* Default options used when creating new particles. These values are applied when specific
* options aren't provided in the constructor.
* @example
* ```ts
* // Override defaults globally
* Particle.defaultOptions = {
* ...Particle.defaultOptions,
* anchorX: 0.5,
* anchorY: 0.5,
* alpha: 0.8
* };
*
* // New particles use modified defaults
* const centeredParticle = new Particle(texture);
* console.log(centeredParticle.anchorX); // 0.5
* console.log(centeredParticle.alpha); // 0.8
* ```
* @see {@link ParticleOptions} For all available options
* @see {@link Particle} For the particle implementation
*/
static defaultOptions: Partial<ParticleOptions>;
/**
* The x-coordinate of the anchor point (0-1).
* Controls the origin point for rotation and scaling.
* @example
* ```ts
* particle.anchorX = 0.5; // Center horizontally
* ```
* @default 0
*/
anchorX: number;
/**
* The y-coordinate of the anchor point (0-1).
* Controls the origin point for rotation and scaling.
* @example
* ```ts
* particle.anchorY = 0.5; // Center vertically
* ```
* @default 0
*/
anchorY: number;
/**
* The x-coordinate of the particle in world space.
* @example
* ```ts
* particle.x = 100; // Move right
* particle.x += Math.sin(time) * 10; // Oscillate horizontally
* ```
* @default 0
*/
x: number;
/**
* The y-coordinate of the particle in world space.
* @example
* ```ts
* particle.y = 100; // Move down
* particle.y += Math.cos(time) * 10; // Oscillate vertically
* ```
* @default 0
*/
y: number;
/**
* The horizontal scale factor of the particle.
* Values greater than 1 increase size, less than 1 decrease size.
* @example
* ```ts
* particle.scaleX = 2; // Double width
* particle.scaleX *= 0.9; // Shrink over time
* ```
* @default 1
*/
scaleX: number;
/**
* The vertical scale factor of the particle.
* Values greater than 1 increase size, less than 1 decrease size.
* @example
* ```ts
* particle.scaleY = 2; // Double height
* particle.scaleY *= 0.9; // Shrink over time
* ```
* @default 1
*/
scaleY: number;
/**
* The rotation of the particle in radians.
* Positive values rotate clockwise.
* @example
* ```ts
* particle.rotation = Math.PI; // 180 degrees
* particle.rotation += 0.1; // Rotate slowly clockwise
* ```
* @default 0
*/
rotation: number;
/**
* The color of the particle as a 32-bit RGBA value.
* Combines tint and alpha into a single value.
* @example
* ```ts
* // Usually set via tint and alpha properties
* particle.tint = 0xff0000; // Red
* particle.alpha = 0.5; // Half transparent
* console.log(particle.color); // Combined RGBA value
* ```
* @default 0xffffffff
*/
color: number;
/**
* The texture used to render this particle.
* All particles in a container should share the same base texture.
* @example
* ```ts
* particle.texture = Texture.from('particle.png');
* ```
*/
texture: Texture;
private _alpha;
private _tint;
constructor(options: Texture | ParticleOptions);
/**
* The transparency of the particle. Values range from 0 (fully transparent)
* to 1 (fully opaque). Values outside this range are clamped.
* @example
* ```ts
* // Create a semi-transparent particle
* const particle = new Particle({
* texture: Texture.from('particle.png'),
* alpha: 0.5
* });
*
* // Fade out
* particle.alpha *= 0.9;
*
* // Fade in
* particle.alpha = Math.min(particle.alpha + 0.1, 1);
*
* // Values are clamped to valid range
* particle.alpha = 1.5; // Becomes 1.0
* particle.alpha = -0.5; // Becomes 0.0
*
* // Animate transparency
* app.ticker.add((delta) => {
* const time = performance.now() / 1000;
* particle.alpha = 0.5 + Math.sin(time) * 0.5; // Pulse between 0-1
* });
* ```
* @default 1
* @see {@link Particle#tint} For controlling particle color
* @see {@link Particle#color} For the combined color and alpha value
*/
get alpha(): number;
set alpha(value: number);
/**
* The tint color of the particle. Can be set using hex numbers or CSS color strings.
* The tint is multiplied with the texture color to create the final particle color.
* @example
* ```ts
* // Create a red particle
* const particle = new Particle({
* texture: Texture.from('particle.png'),
* tint: 0xff0000
* });
*
* // Use CSS color strings
* particle.tint = '#00ff00'; // Green
* particle.tint = 'blue'; // Blue
*
* // Animate tint color
* app.ticker.add(() => {
* const time = performance.now() / 1000;
*
* // Cycle through hues
* const hue = (time * 50) % 360;
* particle.tint = `hsl(${hue}, 100%, 50%)`;
* });
*
* // Reset to white (no tint)
* particle.tint = 0xffffff;
* ```
* @type {ColorSource} Hex number or CSS color string
* @default 0xffffff
* @see {@link Particle#alpha} For controlling transparency
* @see {@link Particle#color} For the combined color and alpha value
* @see {@link Color} For supported color formats
*/
get tint(): number;
set tint(value: ColorSource);
private _updateColor;
}
/** @internal */
export interface ParticleRendererProperty {
attributeName: string;
format: VertexFormat;
code: string;
dynamic: boolean;
updateFunction?: (ps: IParticle[], f32v: Float32Array, u32v: Uint32Array, offset: number, stride: number) => void;
}
/** @internal */
export declare const particleData: Record<string, ParticleRendererProperty>;
/** @internal */
export type ParticleUpdateFunction = (ps: IParticle[], f32v: Float32Array, u32v: Uint32Array) => void;
/**
* @param properties
* @internal
*/
export declare function generateParticleUpdateFunction(properties: Record<string, ParticleRendererProperty>): {
dynamicUpdate: ParticleUpdateFunction;
staticUpdate: ParticleUpdateFunction;
};
/**
* Options for creating a ParticleBuffer.
* @internal
*/
export interface ParticleBufferOptions {
/** The size of the particle buffer, defaults to 1000. */
size: number;
/** A record of attributes that the particle container uses. */
properties: Record<string, ParticleRendererProperty>;
}
/**
* The ParticleBuffer holds the buffers and geometry for a particle container.
* It also contains the upload functions for the static and dynamic properties.
* @internal
*/
export declare class ParticleBuffer implements GPUData {
/** The buffer containing static attribute data for all elements in the batch. */
staticAttributeBuffer: ViewableBuffer;
/** The buffer containing dynamic attribute data for all elements in the batch. */
dynamicAttributeBuffer: ViewableBuffer;
private readonly _staticBuffer;
private readonly _dynamicBuffer;
/** The buffer containing index data for all elements in the batch. */
indexBuffer: IndexBufferArray;
private readonly _dynamicStride;
private readonly _staticStride;
/** The geometry of the particle buffer. */
readonly geometry: Geometry;
private _size;
private readonly _dynamicUpload;
private readonly _staticUpload;
private readonly _generateParticleUpdateCache;
constructor(options: ParticleBufferOptions);
getParticleUpdate(properties: Record<string, ParticleRendererProperty>): {
dynamicUpdate: ParticleUpdateFunction;
staticUpdate: ParticleUpdateFunction;
};
generateParticleUpdate(properties: Record<string, ParticleRendererProperty>): {
dynamicUpdate: ParticleUpdateFunction;
staticUpdate: ParticleUpdateFunction;
};
update(particles: IParticle[], uploadStatic: boolean): void;
destroy(): void;
}
/**
* Represents the properties of a particle that can be dynamically updated each frame.
* These properties control which aspects of particles are recalculated during rendering.
* Setting a property to true enables per-frame updates, while false only updates when manually triggered.
* @example
* ```ts
* // Create a particle container with dynamic position and rotation
* const container = new ParticleContainer({
* dynamicProperties: {
* position: true, // Update positions each frame
* rotation: true, // Update rotations each frame
* vertex: false, // Static vertices
* uvs: false, // Static texture coordinates
* color: false // Static colors
* }
* });
*
* // Create a fully dynamic particle container
* const dynamicContainer = new ParticleContainer({
* dynamicProperties: {
* vertex: true, // Dynamic mesh deformation
* position: true, // Dynamic movement
* rotation: true, // Dynamic spinning
* uvs: true, // Dynamic texture animation
* color: true // Dynamic coloring
* }
* });
* ```
* @see {@link ParticleContainer} For the main particle container class
* @see {@link ParticleContainerOptions} For all container configuration options
* @category scene
* @standard
*/
export interface ParticleProperties {
/**
* When true, vertex positions are updated each frame.
* Useful for mesh deformation effects.
* @default false
*/
vertex?: boolean;
/**
* When true, particle positions are updated each frame.
* Essential for moving particles.
* @default true
*/
position?: boolean;
/**
* When true, rotation values are updated each frame.
* Needed for spinning particles.
* @default false
*/
rotation?: boolean;
/**
* When true, texture coordinates are updated each frame.
* Required for texture animation.
* @default false
*/
uvs?: boolean;
/**
* When true, color values are updated each frame.
* Enables color transitions and alpha changes.
* @default false
*/
color?: boolean;
}
/**
* Options for configuring a ParticleContainer. Controls how particles are rendered, updated, and managed.
* @example
* ```ts
* // Create a basic particle container
* const container = new ParticleContainer({
* texture: Texture.from('particle.png'),
* particles: [
* new Particle(texture),
* new Particle(texture)
* ],
* dynamicProperties: {
* position: true, // Update positions each frame
* rotation: true // Update rotations each frame
* }
* });
* ```
* @see {@link ParticleContainer} For the main particle container class
* @see {@link ParticleProperties} For dynamic property configuration
* @template T The type of particles in the container. Must implement {@link IParticle}. * @category scene
* @standard
* @noInheritDoc
*/
export interface ParticleContainerOptions<T extends IParticle = IParticle> extends PixiMixins.ParticleContainerOptions, Omit<ViewContainerOptions, "children"> {
/**
* Specifies which particle properties should update each frame.
* Set properties to true for per-frame updates, false for static values.
* @default { position: true, rotation: false, vertex: false, uvs: false, color: false }
*/
dynamicProperties?: ParticleProperties & Record<string, boolean>;
/**
* Custom shader for rendering particles. Allows for custom visual effects.
* @advanced
*/
shader?: Shader;
/**
* When true, particle positions are rounded to the nearest pixel.
* Helps achieve crisp rendering at the cost of smooth motion.
* @default false
*/
roundPixels?: boolean;
/**
* The texture used for all particles in this container.
* If not provided, uses the texture of the first particle added.
*/
texture?: Texture;
/** Initial array of particles to add to the container. All particles must share the same base texture. */
particles?: T[];
}
export interface ParticleContainer extends PixiMixins.ParticleContainer, ViewContainer<ParticleBuffer> {
}
/**
* The ParticleContainer class is a highly optimized container that can render 1000s or particles at great speed.
*
* A ParticleContainer is specialized in that it can only contain and render particles. Particles are
* lightweight objects that use minimal memory, which helps boost performance.
*
* It can render particles EXTREMELY fast!
*
* The tradeoff of using a ParticleContainer is that most advanced functionality is unavailable. Particles are simple
* and cannot have children, filters, masks, etc. They possess only the basic properties: position, scale, rotation,
* and color.
*
* All particles must share the same texture source (using something like a sprite sheet works well here).
*
* When creating a ParticleContainer, a developer can specify which of these properties are static and which are dynamic.
* - Static properties are only updated when you add or remove a child, or when the `update` function is called.
* - Dynamic properties are updated every frame.
*
* It is up to the developer to specify which properties are static and which are dynamic. Generally, the more static
* properties you have (i.e., those that do not change per frame), the faster the rendering.
*
* If the developer modifies the children order or any static properties of the particle, they must call the `update` method.
*
* By default, only the `position` property is set to dynamic, which makes rendering very fast!
*
* Developers can also provide a custom shader to the particle container, allowing them to render particles in a custom way.
*
* To help with performance, the particle containers bounds are not calculated.
* It's up to the developer to set the boundsArea property.
*
* It's extremely easy to use. Below is an example of rendering thousands of sprites at lightning speed.
*
* --------- EXPERIMENTAL ---------
*
* This is a new API, things may change and it may not work as expected.
* We want to hear your feedback as we go!
*
* --------------------------------
* @example
* ```ts
* import { ParticleContainer, Particle } from 'pixi.js';
*
* const container = new ParticleContainer();
*
* for (let i = 0; i < 100; ++i)
* {
* let particle = new Particle(texture);
* container.addParticle(particle);
* }
* ```
* @template T The type of particles in the container. Must implement {@link IParticle}.
* @category scene
* @standard
*/
export declare class ParticleContainer<T extends IParticle = IParticle> extends ViewContainer<ParticleBuffer> implements Instruction {
/**
* Defines the default options for creating a ParticleContainer.
* @example
* ```ts
* // Change defaults globally
* ParticleContainer.defaultOptions = {
* dynamicProperties: {
* position: true, // Update positions each frame
* rotation: true, // Update rotations each frame
* vertex: false, // Static vertices
* uvs: false, // Static texture coordinates
* color: false // Static colors
* },
* roundPixels: true // Enable pixel rounding for crisp rendering
* };
* ```
* @property {Record<string, boolean>} dynamicProperties - Specifies which properties are dynamic.
* @property {boolean} roundPixels - Indicates if pixels should be rounded.
*/
static defaultOptions: Pick<ParticleContainerOptions, "dynamicProperties" | "roundPixels">;
/**
* The unique identifier for the render pipe of this ParticleContainer.
* @internal
*/
readonly renderPipeId: string;
/** @internal */
batched: boolean;
/**
* A record of properties and their corresponding ParticleRendererProperty.
* @internal
*/
_properties: Record<string, ParticleRendererProperty>;
/**
* Indicates if the children of this ParticleContainer have changed and need to be updated.
* @internal
*/
_childrenDirty: boolean;
/**
* An array of particles that are children of this ParticleContainer.
* This array can be modified directly for performance, but the 'update' method
* must be called afterwards to ensure the container is rendered correctly.
* @example
* ```ts
* const container = new ParticleContainer();
*
* // Add particles directly to the array
* container.particleChildren.push(
* new Particle(texture),
* new Particle(texture)
* );
* container.update(); // Required after direct modification
*
* // Modify existing particles
* container.particleChildren.forEach(particle => {
* particle.position.x += 10;
* });
*
* // Remove particles
* container.particleChildren.length = 0; // Clear all
* container.update();
* ```
* @see {@link ParticleContainer#update} For updating after modifications
* @see {@link ParticleContainer#addParticle} For a safer way to add particles
* @see {@link ParticleContainer#removeParticle} For a safer way to remove particles
*/
particleChildren: T[];
/**
* The shader used for rendering particles in this ParticleContainer.
* @advanced
*/
shader: Shader;
/**
* The texture used for rendering particles in this ParticleContainer. All particles
* must share the same base texture for optimal performance.
*
* > [!NOTE]
* > If not set, the texture of the first particle added to this container will be used.
* @example
* ```ts
* const container = new ParticleContainer();
* // Set texture for all particles
* container.texture = Texture.from('particle.png');
*
* // Create particles using container's texture
* for (let i = 0; i < 100; i++) {
* const particle = new Particle(container.texture);
* container.addParticle(particle); // Will use the particles texture if not set
* }
* ```
* @default null
* @see {@link ParticleContainerOptions#texture} For setting texture via constructor
* @see {@link Particle} For creating particles with textures
*/
texture: Texture;
/**
* @param options - The options for creating the sprite.
*/
constructor(options?: ParticleContainerOptions<T>);
/**
* Adds one or more particles to the container. The particles will be rendered using the container's shared texture
* and properties. When adding multiple particles, they must all share the same base texture.
* @example
* ```ts
* const container = new ParticleContainer();
*
* // Add a single particle
* const particle = new Particle(Assets.get('particleTexture'));
* container.addParticle(particle);
*
* // Add multiple particles at once
* const particles = [
* new Particle(Assets.get('particleTexture')),
* new Particle(Assets.get('particleTexture')),
* new Particle(Assets.get('particleTexture'))
* ];
*
* container.addParticle(...particles);
* ```
* @param children - The Particle(s) to add to the container
* @returns The first particle that was added, for method chaining
* @see {@link ParticleContainer#texture} For setting the shared texture
* @see {@link ParticleContainer#update} For updating after modifications
*/
addParticle(...children: T[]): T;
/**
* Removes one or more particles from the container. The particles must already be children
* of this container to be removed.
* @example
* ```ts
* // Remove a single particle
* container.removeParticle(particle1);
*
* // Remove multiple particles at once
* container.removeParticle(particle2, particle3);
* ```
* @param children - The Particle(s) to remove from the container
* @returns The first particle that was removed, for method chaining
* @see {@link ParticleContainer#particleChildren} For accessing all particles
* @see {@link ParticleContainer#removeParticles} For removing particles by index
* @see {@link ParticleContainer#removeParticleAt} For removing a particle at a specific index
*/
removeParticle(...children: T[]): T;
/**
* Updates the particle container's internal state. Call this method after manually modifying
* the particleChildren array or when changing static properties of particles.
* @example
* ```ts
* // Batch modify particles
* container.particleChildren.push(...particles);
* container.update(); // Required after direct array modification
*
* // Update static properties
* container.particleChildren.forEach(particle => {
* particle.position.set(
* Math.random() * 800,
* Math.random() * 600
* );
* });
* container.update(); // Required after changing static positions
* ```
* @see {@link ParticleProperties} For configuring dynamic vs static properties
* @see {@link ParticleContainer#particleChildren} For direct array access
*/
update(): void;
protected onViewUpdate(): void;
/**
* Returns a static empty bounds object since ParticleContainer does not calculate bounds automatically
* for performance reasons. Use the `boundsArea` property to manually set container bounds.
* @example
* ```ts
* const container = new ParticleContainer({
* texture: Texture.from('particle.png')
* });
*
* // Default bounds are empty
* console.log(container.bounds); // Bounds(0, 0, 0, 0)
*
* // Set manual bounds for the particle area
* container.boundsArea = {
* minX: 0,
* minY: 0,
* maxX: 800,
* maxY: 600
* };
* ```
* @readonly
* @returns {Bounds} An empty bounds object (0,0,0,0)
* @see {@link Container#boundsArea} For manually setting container bounds
* @see {@link Bounds} For bounds object structure
*/
get bounds(): Bounds;
/** @private */
protected updateBounds(): void;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* particleContainer.destroy();
* particleContainer.destroy(true);
* particleContainer.destroy({ texture: true, textureSource: true, children: true });
*/
destroy(options?: DestroyOptions): void;
/**
* Removes all particles from this container that are within the begin and end indexes.
* @param beginIndex - The beginning position.
* @param endIndex - The ending position. Default value is size of the container.
* @returns - List of removed particles
*/
removeParticles(beginIndex?: number, endIndex?: number): T[];
/**
* Removes a particle from the specified index position.
* @param index - The index to get the particle from
* @returns The particle that was removed.
*/
removeParticleAt<U extends T = T>(index: number): U;
/**
* Adds a particle to the container at a specified index. If the index is out of bounds an error will be thrown.
* If the particle is already in this container, it will be moved to the specified index.
* @param {Container} child - The particle to add.
* @param {number} index - The absolute index where the particle will be positioned at the end of the operation.
* @returns {Container} The particle that was added.
*/
addParticleAt<U extends T = T>(child: U, index: number): U;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.addParticle()` instead.
* @param {...any} _children
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
addChild<U extends ContainerChild[]>(..._children: U): U[0];
/**
* This method is not available in ParticleContainer.
* Calling this method will throw an error. Please use `ParticleContainer.removeParticle()` instead.
* @param {...any} _children
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChild<U extends ContainerChild[]>(..._children: U): U[0];
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.removeParticles()` instead.
* @param {number} [_beginIndex]
* @param {number} [_endIndex]
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChildren(_beginIndex?: number, _endIndex?: number): ContainerChild[];
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.removeParticleAt()` instead.
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
removeChildAt<U extends ContainerChild>(_index: number): U;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.getParticleAt()` instead.
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
getChildAt<U extends ContainerChild>(_index: number): U;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.setParticleIndex()` instead.
* @param {ContainerChild} _child
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
setChildIndex(_child: ContainerChild, _index: number): void;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.getParticleIndex()` instead.
* @param {ContainerChild} _child
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
getChildIndex(_child: ContainerChild): number;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.addParticleAt()` instead.
* @param {ContainerChild} _child
* @param {number} _index
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
addChildAt<U extends ContainerChild>(_child: U, _index: number): U;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error. Please use `ParticleContainer.swapParticles()` instead.
* @param {ContainerChild} _child
* @param {ContainerChild} _child2
* @ignore
*/
swapChildren<U extends ContainerChild>(_child: U, _child2: U): void;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error.
* @param _child - The child to reparent
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
reparentChild(..._child: ContainerChild[]): any;
/**
* This method is not available in ParticleContainer.
*
* Calling this method will throw an error.
* @param _child - The child to reparent
* @param _index - The index to reparent the child to
* @throws {Error} Always throws an error as this method is not available.
* @ignore
*/
reparentChildAt(_child: ContainerChild, _index: number): any;
}
/** @internal */
export interface ParticleContainerAdaptor {
execute(particleContainerPop: ParticleContainerPipe, container: ParticleContainer): void;
}
/**
* Renderer for Particles that is designer for speed over feature set.
* @category scene
* @internal
*/
export declare class ParticleContainerPipe implements RenderPipe<ParticleContainer> {
/** The default shader that is used if a sprite doesn't have a more specific one. */
defaultShader: Shader;
/** @internal */
adaptor: ParticleContainerAdaptor;
/** @internal */
readonly state: State;
/** @internal */
readonly renderer: Renderer;
private readonly _managedContainers;
/** Local uniforms that are used for rendering particles. */
readonly localUniforms: UniformGroup<{
uTranslationMatrix: {
value: Matrix;
type: "mat3x3<f32>";
};
uColor: {
value: Float32Array;
type: "vec4<f32>";
};
uRound: {
value: number;
type: "f32";
};
uResolution: {
value: number[];
type: "vec2<f32>";
};
}>;
/**
* @param renderer - The renderer this sprite batch works for.
* @param adaptor
*/
constructor(renderer: Renderer, adaptor: ParticleContainerAdaptor);
validateRenderable(_renderable: ParticleContainer): boolean;
addRenderable(renderable: ParticleContainer, instructionSet: InstructionSet): void;
getBuffers(renderable: ParticleContainer): ParticleBuffer;
private _initBuffer;
updateRenderable(_renderable: ParticleContainer): void;
execute(container: ParticleContainer): void;
/** Destroys the ParticleRenderer. */
destroy(): void;
}
/** @internal */
export declare class GlParticleContainerAdaptor implements ParticleContainerAdaptor {
execute(particleContainerPipe: ParticleContainerPipe, container: ParticleContainer): void;
}
/** @internal */
export declare class GpuParticleContainerAdaptor implements ParticleContainerAdaptor {
execute(particleContainerPipe: ParticleContainerPipe, container: ParticleContainer): void;
}
/**
* WebGL renderer for Particles that is designed for speed over feature set.
* @category scene
* @internal
*/
export declare class GlParticleContainerPipe extends ParticleContainerPipe {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes
];
readonly name: "particle";
};
constructor(renderer: WebGLRenderer);
}
/**
* WebGPU renderer for Particles that is designed for speed over feature set.
* @category scene
* @internal
*/
export declare class GpuParticleContainerPipe extends ParticleContainerPipe {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGPUPipes
];
readonly name: "particle";
};
constructor(renderer: WebGPURenderer);
}
/** @internal */
export declare class ParticleShader extends Shader {
constructor();
}
/**
* Generic Mask Stack data structure
* @function createIndicesForQuads
* @param {number} size - Number of quads
* @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size`
* @returns {Uint16Array|Uint32Array} - Resulting index buffer
* @internal
*/
export declare function createIndicesForQuads(size: number, outBuffer?: Uint16Array | Uint32Array | null): Uint16Array | Uint32Array;
/**
* A collection of textures or frame objects that can be used to create an `AnimatedSprite`.
* @see {@link AnimatedSprite}
* @category scene
* @standard
*/
export type AnimatedSpriteFrames = Texture[] | FrameObject[];
/**
* Constructor options used for `AnimatedSprite` instances. Allows configuration of animation
* playback, speed, and texture frames.
* @example
* ```ts
* // Create a basic animated sprite
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png')
* ],
* animationSpeed: 0.1,
* loop: true
* });
*
* // Create with spritesheet frames and callbacks
* const sheet = await Assets.load('character.json');
* const animatedSprite = new AnimatedSprite({
* textures: sheet.animations['walk'],
* autoPlay: true,
* updateAnchor: true,
* onComplete: () => console.log('Animation complete'),
* onFrameChange: (frame) => console.log('Current frame:', frame),
* onLoop: () => console.log('Animation looped')
* });
*
* // Create with custom timing for each frame
* const customTimingSprite = new AnimatedSprite({
* textures: [
* { texture: Texture.from('frame1.png'), time: 100 },
* { texture: Texture.from('frame2.png'), time: 200 },
* { texture: Texture.from('frame3.png'), time: 300 }
* ],
* autoUpdate: true
* });
* ```
* @see {@link AnimatedSprite} For the main sprite class
* @see {@link Spritesheet} For loading animations from spritesheets
* @category scene
* @standard
* @noInheritDoc
*/
export interface AnimatedSpriteOptions extends PixiMixins.AnimatedSpriteOptions, Omit<SpriteOptions, "texture"> {
/**
* The speed that the AnimatedSprite will play at. Higher is faster, lower is slower.
* @example
* ```ts
* // Create an AnimatedSprite with a slower animation speed
* const animation = new AnimatedSprite({
* textures: [Texture.from('frame1.png'), Texture.from('frame2.png')],
* animationSpeed: 0.5 // Slower animation
* });
*
* // Update the animation speed to make it faster
* animation.animationSpeed = 2; // Faster animation
* ```
* @default 1
*/
animationSpeed?: number;
/**
* Whether to start the animation immediately on creation.
* If set to `true`, the animation will start playing as soon as the
* `AnimatedSprite` is created.
* If set to `false`, you will need to call the `play` method to start the animation.
* @example
* ```ts
* // Create an AnimatedSprite that starts playing immediately
* const animation = new AnimatedSprite({
* textures: [Texture.from('frame1.png'), Texture.from('frame2.png')],
* autoPlay: true
* });
*
* // Create an AnimatedSprite that does not start playing immediately
* const animation = new AnimatedSprite({
* textures: [Texture.from('frame1.png'), Texture.from('frame2.png')],
* autoPlay: false
* });
* animation.play(); // Start the animation manually
* ```
* @default false
*/
autoPlay?: boolean;
/**
* Whether to use Ticker.shared to auto update animation time.
* This is useful for animations that need to be updated every frame.
* If set to `false`, you will need to manually call the `update` method
* to update the animation.
* @example
* ```ts
* // Create an AnimatedSprite that does not auto update
* const animation = new AnimatedSprite({
* textures: [Texture.from('frame1.png'), Texture.from('frame2.png')],
* autoUpdate: false
* });
*
* // Manually update the animation in your game loop
* ticker.add((ticker) => {
* animation.update(ticker);
* }
* ```
* @default true
*/
autoUpdate?: boolean;
/**
* Whether or not the animation repeats after playing.
* @default true
*/
loop?: boolean;
/**
* User-assigned function to call when an AnimatedSprite finishes playing.
* @example
* ```ts
* animation.onComplete = () => {
* // Finished!
* console.log('Animation complete');
* };
* ```
* @default null
* @see {@link AnimatedSprite#onFrameChange} For the callback when the frame changes
* @see {@link AnimatedSprite#onLoop} For the callback when the animation loops
* @see {@link AnimatedSprite#loop} For the loop behavior of the animation
*/
onComplete?: () => void;
/**
* User-assigned function to call when an AnimatedSprite changes which texture is being rendered.
* @example
* ```ts
* animation.onFrameChange = (currentFrame) => {
* // Updated!
* console.log('Current frame:', currentFrame);
* };
* ```
* @see {@link AnimatedSprite#onComplete} For the callback when the animation finishes
* @see {@link AnimatedSprite#onLoop} For the callback when the animation loops
* @default null
*/
onFrameChange?: (currentFrame: number) => void;
/**
* User-assigned function to call when `loop` is true,
* and an AnimatedSprite is played and loops around to start again.
* @example
* ```ts
* animation.onLoop = () => {
* // Looped!
* };
* ```
* @see {@link AnimatedSprite#onComplete} For the callback when the animation finishes
* @see {@link AnimatedSprite#onFrameChange} For the callback when the frame changes
* @see {@link AnimatedSprite#loop} For the loop behavior of the animation
* @default null
*/
onLoop?: () => void;
/**
* An array of {@link Texture} or frame objects that make up the animation.
* @example
* ```ts
* // Create an AnimatedSprite with an array of textures
* const animation = new AnimatedSprite({
* textures: [
* Texture.from('frame1.png'),
* Texture.from('frame2.png'),
* Texture.from('frame3.png')
* ]
* });
* * // Create an AnimatedSprite with an array of frame objects
* const animation = new AnimatedSprite({
* textures: [
* { texture: Texture.from('frame1.png'), time: 100 },
* { texture: Texture.from('frame2.png'), time: 200 },
* { texture: Texture.from('frame3.png'), time: 300 }
* ]
* });
* ```
* @see {@link AnimatedSpriteFrames} For the type of the textures array
*/
textures: AnimatedSpriteFrames;
/**
* Update anchor to [Texture's defaultAnchor]{@link Texture#defaultAnchor} when frame changes.
*
* Useful with [sprite sheet animations]{@link Spritesheet#animations} created with tools.
* Changing anchor for each frame allows to pin sprite origin to certain moving feature
* of the frame (e.g. left foot).
* > [!NOTE] Enabling this will override any previously set `anchor` on each frame change.
* @example
* ```ts
* // Create an AnimatedSprite with updateAnchor enabled
* const animation = new AnimatedSprite({
* textures: [Texture.from('frame1.png'), Texture.from('frame2.png')],
* updateAnchor: true
* });
* ```
* @see {@link Texture#defaultAnchor} For the default anchor of the texture
* @default false
*/
updateAnchor?: boolean;
}
export interface AnimatedSprite extends PixiMixins.AnimatedSprite, Sprite {
}
/**
* An AnimatedSprite is a simple way to display an animation depicted by a list of textures.
* @example
* ```js
* import { AnimatedSprite, Texture } from 'pixi.js';
*
* const alienImages = [
* 'image_sequence_01.png',
* 'image_sequence_02.png',
* 'image_sequence_03.png',
* 'image_sequence_04.png',
* ];
* const textureArray = [];
*
* for (let i = 0; i < 4; i++)
* {
* const texture = Texture.from(alienImages[i]);
* textureArray.push(texture);
* }
*
* const animatedSprite = new AnimatedSprite(textureArray);
* ```
*
* The more efficient and simpler way to create an animated sprite is using a {@link Spritesheet}
* containing the animation definitions:
* @example
* ```js
* import { AnimatedSprite, Assets } from 'pixi.js';
*
* const sheet = await Assets.load('assets/spritesheet.json');
* animatedSprite = new AnimatedSprite(sheet.animations['image_sequence']);
* ```
* @category scene
* @standard
*/
export declare class AnimatedSprite extends Sprite {
/**
* The speed that the AnimatedSprite will play at. Higher is faster, lower is slower.
* @example
* ```ts
* // Create a sprite with normal speed animation
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png')
* ],
* animationSpeed: 1 // Default speed
* });
*
* // Slow down the animation
* sprite.animationSpeed = 0.5;
*
* // Speed up the animation
* sprite.animationSpeed = 2;
*
* // Reverse the animation
* sprite.animationSpeed = -1;
*
* // Stop the animation
* sprite.animationSpeed = 0;
* ```
* @default 1
* @see {@link AnimatedSprite#currentFrame} For the current frame index
* @see {@link AnimatedSprite#totalFrames} For total number of frames
*/
animationSpeed: number;
/**
* Whether or not the animation repeats after playing.
* When true, the animation will restart from the beginning after reaching the last frame.
* When false, the animation will stop on the last frame.
* @example
* ```ts
* // Create a looping animation
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png')
* ],
* loop: true // Will repeat
* });
*
* // Play animation once
* sprite.loop = false;
* sprite.onComplete = () => console.log('Animation finished!');
* sprite.play();
*
* // Toggle looping at runtime
* sprite.loop = !sprite.loop;
* ```
* @default true
* @see {@link AnimatedSprite#onComplete} Callback when non-looping animation completes
* @see {@link AnimatedSprite#onLoop} Callback when animation loops
*/
loop: boolean;
/**
* Update anchor to [Texture's defaultAnchor]{@link Texture#defaultAnchor} when frame changes.
*
* Useful with [sprite sheet animations]{@link Spritesheet#animations} created with tools.
* Changing anchor for each frame allows to pin sprite origin to certain moving feature
* of the frame (e.g. left foot).
*
* > [!NOTE] Enabling this will override any previously set `anchor` on each frame change.
* @default false
*/
updateAnchor: boolean;
/**
* User-assigned function to call when an AnimatedSprite finishes playing.
*
* This function is called when the animation reaches the end and stops playing.
* If the animation is set to loop, this function will not be called.
* @example
* ```ts
* animation.onComplete = () => {
* // Finished!
* };
* ```
*/
onComplete?: () => void;
/**
* User-assigned function to call when an AnimatedSprite changes which texture is being rendered.
*
* This function is called every time the current frame changes during playback.
* It receives the current frame index as an argument.
* @example
* animation.onFrameChange = () => {
* // Updated!
* };
*/
onFrameChange?: (currentFrame: number) => void;
/**
* User-assigned function to call when `loop` is true, and an AnimatedSprite is played and
* loops around to start again.
* @example
* animation.onLoop = () => {
* // Looped!
* };
*/
onLoop?: () => void;
private _playing;
private _textures;
private _durations;
/**
* `true` uses Ticker.shared to auto update animation time.
* @default true
*/
private _autoUpdate;
/**
* `true` if the instance is currently connected to Ticker.shared to auto update animation time.
* @default false
*/
private _isConnectedToTicker;
/** Elapsed time since animation has been started, used internally to display current texture. */
private _currentTime;
/** The texture index that was displayed last time. */
private _previousFrame;
/**
* @param frames - Collection of textures or frames to use.
* @param autoUpdate - Whether to use Ticker.shared to auto update animation time.
*/
constructor(frames: AnimatedSpriteFrames, autoUpdate?: boolean);
/**
* @param options - The options for the AnimatedSprite.
*/
constructor(options: AnimatedSpriteOptions);
/**
* Stops the animation playback and freezes the current frame.
* Does not reset the current frame or animation progress.
* @example
* ```ts
* // Create an animated sprite
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png')
* ],
* autoPlay: true
* });
*
* // Stop at current frame
* sprite.stop();
*
* // Stop at specific frame
* sprite.gotoAndStop(1); // Stops at second frame
*
* // Stop and reset
* sprite.stop();
* sprite.currentFrame = 0;
*
* // Stop with completion check
* if (sprite.playing) {
* sprite.stop();
* sprite.onComplete?.();
* }
* ```
* @see {@link AnimatedSprite#play} For starting playback
* @see {@link AnimatedSprite#gotoAndStop} For stopping at a specific frame
* @see {@link AnimatedSprite#playing} For checking play state
*/
stop(): void;
/**
* Starts or resumes the animation playback.
* If the animation was previously stopped, it will continue from where it left off.
* @example
* ```ts
* // Basic playback
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* ],
* autoPlay: false
* });
* sprite.play();
*
* // Play after stopping
* sprite.stop();
* sprite.currentFrame = 0; // Reset to start
* sprite.play(); // Play from beginning
*
* // Play with auto-update disabled
* sprite.autoUpdate = false;
* sprite.play();
* app.ticker.add(() => {
* sprite.update(app.ticker); // Manual updates
* });
* ```
* @see {@link AnimatedSprite#stop} For stopping playback
* @see {@link AnimatedSprite#gotoAndPlay} For playing from a specific frame
* @see {@link AnimatedSprite#playing} For checking play state
*/
play(): void;
/**
* Stops the AnimatedSprite and sets it to a specific frame.
* @example
* ```ts
* // Create an animated sprite
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png'),
* ]
* });
*
* // Go to specific frames
* sprite.gotoAndStop(0); // First frame
* sprite.gotoAndStop(2); // Third frame
*
* // Jump to last frame
* sprite.gotoAndStop(sprite.totalFrames - 1);
* ```
* @param frameNumber - Frame index to stop at (0-based)
* @throws {Error} If frameNumber is out of bounds
* @see {@link AnimatedSprite#gotoAndPlay} For going to a frame and playing
* @see {@link AnimatedSprite#currentFrame} For getting/setting current frame
* @see {@link AnimatedSprite#totalFrames} For total number of frames
*/
gotoAndStop(frameNumber: number): void;
/**
* Goes to a specific frame and begins playing the AnimatedSprite from that point.
* Combines frame navigation and playback start in one operation.
* @example
* ```ts
* // Start from specific frame
* sprite.gotoAndPlay(1); // Starts playing from second frame
* ```
* @param frameNumber - Frame index to start playing from (0-based)
* @throws {Error} If frameNumber is out of bounds
* @see {@link AnimatedSprite#gotoAndStop} For going to a frame without playing
* @see {@link AnimatedSprite#play} For playing from current frame
* @see {@link AnimatedSprite#currentFrame} For getting/setting current frame
*/
gotoAndPlay(frameNumber: number): void;
/**
* Updates the object transform for rendering. This method handles animation timing, frame updates,
* and manages looping behavior.
* @example
* ```ts
* // Create an animated sprite with manual updates
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('frame1.png'),
* Texture.from('frame2.png'),
* Texture.from('frame3.png')
* ],
* autoUpdate: false // Disable automatic updates
* });
*
* // Manual update with app ticker
* app.ticker.add((ticker) => {
* sprite.update(ticker);
* });
* ```
* @param ticker - The ticker to use for updating the animation timing
* @see {@link AnimatedSprite#autoUpdate} For controlling automatic updates
* @see {@link AnimatedSprite#animationSpeed} For controlling animation speed
* @see {@link Ticker} For timing system details
*/
update(ticker: Ticker): void;
/** Updates the displayed texture to match the current frame index. */
private _updateTexture;
/**
* Stops the AnimatedSprite and destroys it.
* This method stops the animation playback, removes it from the ticker,
* and cleans up any resources associated with the sprite.
* @param options - Options for destroying the sprite, such as whether to remove from parent
* @example
* ```ts
* // Destroy the sprite when done
* sprite.destroy();
* // Or with options
* sprite.destroy({ children: true, texture: true, textureSource: true });
* ```
*/
destroy(options?: DestroyOptions): void;
/**
* A short hand way of creating an AnimatedSprite from an array of frame ids.
* Uses texture frames from the cache to create an animation sequence.
* @example
* ```ts
* // Create from frame IDs
* const frameIds = [
* 'walk_001.png',
* 'walk_002.png',
* 'walk_003.png'
* ];
*
* const walkingAnimation = AnimatedSprite.fromFrames(frameIds);
* walkingAnimation.play();
* ```
* @param frames - The array of frame ids to use for the animation
* @returns A new animated sprite using the frames
* @see {@link Texture.from} For texture creation from frames
* @see {@link Spritesheet} For loading spritesheets
*/
static fromFrames(frames: string[]): AnimatedSprite;
/**
* A short hand way of creating an AnimatedSprite from an array of image urls.
* Each image will be used as a frame in the animation.
* @example
* ```ts
* // Create from image URLs
* const images = [
* 'assets/walk1.png',
* 'assets/walk2.png',
* 'assets/walk3.png'
* ];
*
* const walkingSprite = AnimatedSprite.fromImages(images);
* walkingSprite.play();
* ```
* @param images - The array of image urls to use as frames
* @returns A new animated sprite using the images as frames
* @see {@link Assets} For asset loading and management
* @see {@link Texture.from} For texture creation from images
*/
static fromImages(images: string[]): AnimatedSprite;
/**
* The total number of frames in the AnimatedSprite. This is the same as number of textures
* assigned to the AnimatedSprite.
* @example
* ```ts
* // Create an animated sprite
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('frame1.png'),
* Texture.from('frame2.png'),
* Texture.from('frame3.png')
* ]
* });
*
* // Get total frames
* console.log(sprite.totalFrames); // Outputs: 3
*
* // Use with frame navigation
* sprite.gotoAndStop(sprite.totalFrames - 1); // Go to last frame
* ```
* @readonly
* @see {@link AnimatedSprite#currentFrame} For the current frame index
* @see {@link AnimatedSprite#textures} For the array of textures
* @returns {number} The total number of frames
*/
get totalFrames(): number;
/**
* The array of textures or frame objects used for the animation sequence.
* Can be set to either an array of Textures or an array of FrameObjects with custom timing.
* @example
* ```ts
* // Update textures at runtime
* sprite.textures = [
* Texture.from('run1.png'),
* Texture.from('run2.png')
* ];
*
* // Use custom frame timing
* sprite.textures = [
* { texture: Texture.from('explosion1.png'), time: 100 },
* { texture: Texture.from('explosion2.png'), time: 200 },
* { texture: Texture.from('explosion3.png'), time: 300 }
* ];
*
* // Use with spritesheet
* const sheet = await Assets.load('animations.json');
* sprite.textures = sheet.animations['walk'];
* ```
* @type {AnimatedSpriteFrames}
* @see {@link FrameObject} For frame timing options
* @see {@link Spritesheet} For loading from spritesheets
*/
get textures(): AnimatedSpriteFrames;
set textures(value: AnimatedSpriteFrames);
/**
* Gets or sets the current frame index of the animation.
* When setting, the value will be clamped between 0 and totalFrames - 1.
* @example
* ```ts
* // Create an animated sprite
* const sprite = new AnimatedSprite({
* textures: [
* Texture.from('walk1.png'),
* Texture.from('walk2.png'),
* Texture.from('walk3.png')
* ]
* });
*
* // Get current frame
* console.log(sprite.currentFrame); // 0
*
* // Set specific frame
* sprite.currentFrame = 1; // Show second frame
*
* // Use with frame callbacks
* sprite.onFrameChange = (frame) => {
* console.log(`Now showing frame: ${frame}`);
* };
* sprite.currentFrame = 2;
* ```
* @throws {Error} If attempting to set a frame index out of bounds
* @see {@link AnimatedSprite#totalFrames} For the total number of frames
* @see {@link AnimatedSprite#gotoAndPlay} For playing from a specific frame
* @see {@link AnimatedSprite#gotoAndStop} For stopping at a specific frame
*/
get currentFrame(): number;
set currentFrame(value: number);
/**
* Indicates if the AnimatedSprite is currently playing.
* This is a read-only property that reflects the current playback state.
* @example
* ```ts
* // Check if animation is playing
* console.log('Playing:', sprite.playing); // true
*
* // Use with play control
* if (!sprite.playing) {
* sprite.play();
* }
* ```
* @readonly
* @returns {boolean} True if the animation is currently playing
* @see {@link AnimatedSprite#play} For starting playback
* @see {@link AnimatedSprite#stop} For stopping playback
* @see {@link AnimatedSprite#loop} For controlling looping behavior
*/
get playing(): boolean;
/**
* Controls whether the animation automatically updates using the shared ticker.
* When enabled, the animation will update on each frame. When disabled, you must
* manually call update() to advance the animation.
* @example
* ```ts
* // Create sprite with auto-update disabled
* const sprite = new AnimatedSprite({
* textures: [],
* autoUpdate: false
* });
*
* // Manual update with app ticker
* app.ticker.add((ticker) => {
* sprite.update(ticker);
* });
*
* // Enable auto-update later
* sprite.autoUpdate = true;
* ```
* @default true
* @see {@link AnimatedSprite#update} For manual animation updates
* @see {@link Ticker} For the timing system
*/
get autoUpdate(): boolean;
set autoUpdate(value: boolean);
}
/**
* A reference to a frame in an {@link AnimatedSprite}
* @category scene
* @advanced
*/
export interface FrameObject {
/** The {@link Texture} of the frame. */
texture: Texture;
/** The duration of the frame, in milliseconds. */
time: number;
}
/**
* Options for the NineSliceGeometry.
* @category scene
* @advanced
*/
export interface NineSliceGeometryOptions {
/** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
width?: number;
/** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
height?: number;
/** The original width of the texture */
originalWidth?: number;
/** The original height of the texture */
originalHeight?: number;
/** The width of the left column. */
leftWidth?: number;
/** The height of the top row. */
topHeight?: number;
/** The width of the right column. */
rightWidth?: number;
/** The height of the bottom row. */
bottomHeight?: number;
/** The anchor point of the NineSliceSprite. */
anchor?: PointData;
}
/**
* The NineSliceGeometry class allows you to create a NineSlicePlane object.
* @category scene
* @advanced
*/
export declare class NineSliceGeometry extends PlaneGeometry {
/** The default options for the NineSliceGeometry. */
static defaultOptions: NineSliceGeometryOptions;
/** @internal */
_leftWidth: number;
/** @internal */
_rightWidth: number;
/** @internal */
_topHeight: number;
/** @internal */
_bottomHeight: number;
private _originalWidth;
private _originalHeight;
private _anchorX;
private _anchorY;
constructor(options?: NineSliceGeometryOptions);
/**
* Updates the NineSliceGeometry with the options.
* @param options - The options of the NineSliceGeometry.
*/
update(options: NineSliceGeometryOptions): void;
/** Updates the positions of the vertices. */
updatePositions(): void;
/** Updates the UVs of the vertices. */
updateUvs(): void;
}
/**
* GPU data for NineSliceSprite.
* @internal
*/
export declare class NineSliceSpriteGpuData extends BatchableMesh implements GPUData {
constructor();
destroy(): void;
}
/**
* The NineSliceSpritePipe is a render pipe for rendering NineSliceSprites.
* @internal
*/
export declare class NineSliceSpritePipe implements RenderPipe<NineSliceSprite> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "nineSliceSprite";
};
private readonly _renderer;
private readonly _managedSprites;
constructor(renderer: Renderer);
addRenderable(sprite: NineSliceSprite, instructionSet: InstructionSet): void;
updateRenderable(sprite: NineSliceSprite): void;
validateRenderable(sprite: NineSliceSprite): boolean;
private _updateBatchableSprite;
private _getGpuSprite;
private _initGPUSprite;
destroy(): void;
}
/**
* Constructor options used for `NineSliceSprite` instances.
* Defines how the sprite's texture is divided and scaled in nine sections.
* <pre>
* A B
* +---+----------------------+---+
* C | 1 | 2 | 3 |
* +---+----------------------+---+
* | | | |
* | 4 | 5 | 6 |
* | | | |
* +---+----------------------+---+
* D | 7 | 8 | 9 |
* +---+----------------------+---+
* When changing this objects width and/or height:
* areas 1 3 7 and 9 will remain unscaled.
* areas 2 and 8 will be stretched horizontally
* areas 4 and 6 will be stretched vertically
* area 5 will be stretched both horizontally and vertically
* </pre>
* @example
* ```ts
* // Create a basic nine-slice sprite
* const button = new NineSliceSprite({
* texture: Texture.from('button.png'),
* leftWidth: 20, // Left border (A)
* rightWidth: 20, // Right border (B)
* topHeight: 20, // Top border (C)
* bottomHeight: 20, // Bottom border (D)
* width: 100, // Initial width
* height: 50, // Initial height
* anchor: 0.5, // Center anchor point
* });
* ```
* @see {@link NineSliceSprite} For the main sprite class
* @see {@link Texture#defaultBorders} For texture-level border settings
* @category scene
* @standard
*/
export interface NineSliceSpriteOptions extends PixiMixins.NineSliceSpriteOptions, ViewContainerOptions {
/**
* The texture to use on the NineSliceSprite.
* ```ts
* // Create a sprite with a texture
* const sprite = new NineSliceSprite({
* texture: Texture.from('path/to/image.png')
* });
* // Update the texture later
* sprite.texture = Texture.from('path/to/another-image.png');
* ```
* @default Texture.EMPTY
*/
texture: Texture;
/**
* Width of the left vertical bar (A).
* Controls the size of the left edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., leftWidth: 20 });
* sprite.leftWidth = 20; // Set left border width
* ```
* @default 10
*/
leftWidth?: number;
/**
* Height of the top horizontal bar (C).
* Controls the size of the top edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., topHeight: 20 });
* sprite.topHeight = 20; // Set top border height
* ```
* @default 10
*/
topHeight?: number;
/**
* Width of the right vertical bar (B).
* Controls the size of the right edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., rightWidth: 20 });
* sprite.rightWidth = 20; // Set right border width
* ```
* @default 10
*/
rightWidth?: number;
/**
* Height of the bottom horizontal bar (D).
* Controls the size of the bottom edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., bottomHeight: 20 });
* sprite.bottomHeight = 20; // Set bottom border height
* ```
* @default 10
*/
bottomHeight?: number;
/**
* Width of the NineSliceSprite.
* Modifies the vertices directly rather than UV coordinates
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., width: 200 });
* sprite.width = 200; // Set the width of the sprite
* ```
* @default 100
*/
width?: number;
/**
* Height of the NineSliceSprite.
* Modifies the vertices directly rather than UV coordinates
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., height: 100 });
* sprite.height = 100; // Set the height of the sprite
* ```
* @default 100
*/
height?: number;
/**
* Whether to round the x/y position to whole pixels
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., roundPixels: true });
* ```
* @default false
*/
roundPixels?: boolean;
/**
* The anchor point of the NineSliceSprite (0-1 range)
*
* Controls the origin point for rotation, scaling, and positioning.
* Can be a number for uniform anchor or a PointData for separate x/y values.
* @default 0
* @example
* ```ts
* // Centered anchor
* const sprite = new NineSliceSprite({ ..., anchor: 0.5 });
* sprite.anchor = 0.5;
* // Separate x/y anchor
* sprite.anchor = { x: 0.5, y: 0.5 };
* // Right-aligned anchor
* sprite.anchor = { x: 1, y: 0 };
* // Update anchor directly
* sprite.anchor.set(0.5, 0.5);
* ```
*/
anchor?: PointData | number;
}
export interface NineSliceSprite extends PixiMixins.NineSliceSprite, ViewContainer<NineSliceSpriteGpuData> {
}
/**
* The NineSliceSprite allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
* for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
*
* <pre>
* A B
* +---+----------------------+---+
* C | 1 | 2 | 3 |
* +---+----------------------+---+
* | | | |
* | 4 | 5 | 6 |
* | | | |
* +---+----------------------+---+
* D | 7 | 8 | 9 |
* +---+----------------------+---+
* When changing this objects width and/or height:
* areas 1 3 7 and 9 will remain unscaled.
* areas 2 and 8 will be stretched horizontally
* areas 4 and 6 will be stretched vertically
* area 5 will be stretched both horizontally and vertically
* </pre>
* @example
* ```ts
* import { NineSliceSprite, Texture } from 'pixi.js';
*
* const plane9 = new NineSliceSprite({
* texture: Texture.from('BoxWithRoundedCorners.png'),
* leftWidth: 15,
* topHeight: 15,
* rightWidth: 15,
* bottomHeight: 15,
* width: 200,
* height: 100,
* });
* ```
* @category scene
* @standard
*/
export declare class NineSliceSprite extends ViewContainer<NineSliceSpriteGpuData> implements View {
/**
* The default options used to override initial values of any options passed in the constructor.
* These values are used as fallbacks when specific options are not provided.
* @example
* ```ts
* // Override default options globally
* NineSliceSprite.defaultOptions.texture = Texture.from('defaultButton.png');
* // Create sprite with default texture
* const sprite = new NineSliceSprite({...});
* // sprite will use 'defaultButton.png' as its texture
*
* // Reset to empty texture
* NineSliceSprite.defaultOptions.texture = Texture.EMPTY;
* ```
* @type {NineSliceSpriteOptions}
* @see {@link NineSliceSpriteOptions} For all available options
* @see {@link Texture#defaultBorders} For texture-level border settings
*/
static defaultOptions: NineSliceSpriteOptions;
/** @internal */
readonly renderPipeId: string;
/** @internal */
_texture: Texture;
/** @internal */
_anchor: ObservablePoint;
/** @internal */
batched: boolean;
private _leftWidth;
private _topHeight;
private _rightWidth;
private _bottomHeight;
private _width;
private _height;
constructor(options: NineSliceSpriteOptions | Texture);
/**
* The anchor sets the origin point of the sprite. The default value is taken from the {@link Texture}
* and passed to the constructor.
*
* - The default is `(0,0)`, this means the sprite's origin is the top left.
* - Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered.
* - Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner.
*
* If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
* @example
* ```ts
* // Center the anchor point
* sprite.anchor = 0.5; // Sets both x and y to 0.5
* sprite.position.set(400, 300); // Sprite will be centered at this position
*
* // Set specific x/y anchor points
* sprite.anchor = {
* x: 1, // Right edge
* y: 0 // Top edge
* };
*
* // Using individual coordinates
* sprite.anchor.set(0.5, 1); // Center-bottom
*
* // For rotation around center
* sprite.anchor.set(0.5);
* sprite.rotation = Math.PI / 4; // 45 degrees around center
*
* // For scaling from center
* sprite.anchor.set(0.5);
* sprite.scale.set(2); // Scales from center point
* ```
*/
get anchor(): ObservablePoint;
set anchor(value: PointData | number);
/**
* The width of the NineSliceSprite, setting this will actually modify the vertices and UV's of this plane.
* The width affects how the middle sections are scaled.
* @example
* ```ts
* // Create a nine-slice sprite with fixed width
* const panel = new NineSliceSprite({
* texture: Texture.from('panel.png'),
* width: 200 // Sets initial width
* });
*
* // Adjust width dynamically
* panel.width = 300; // Stretches middle sections
* ```
* @see {@link NineSliceSprite#setSize} For setting both width and height efficiently
* @see {@link NineSliceSprite#height} For setting height
*/
get width(): number;
set width(value: number);
/**
* The height of the NineSliceSprite, setting this will actually modify the vertices and UV's of this plane.
* The height affects how the middle sections are scaled.
* @example
* ```ts
* // Create a nine-slice sprite with fixed height
* const panel = new NineSliceSprite({
* texture: Texture.from('panel.png'),
* height: 150 // Sets initial height
* });
*
* // Adjust height dynamically
* panel.height = 200; // Stretches middle sections
*
* // Create responsive UI element
* const dialog = new NineSliceSprite({
* texture: Texture.from('dialog.png'),
* topHeight: 30,
* bottomHeight: 30,
* height: parent.height * 0.5 // 50% of parent height
* });
* ```
* @see {@link NineSliceSprite#setSize} For setting both width and height efficiently
* @see {@link NineSliceSprite#width} For setting width
*/
get height(): number;
set height(value: number);
/**
* Sets the size of the NineSliceSprite to the specified width and height.
* This method directly modifies the vertices and UV coordinates of the sprite.
*
* Using this is more efficient than setting width and height separately as it only triggers one update.
* @example
* ```ts
* // Set to specific dimensions
* panel.setSize(300, 200); // Width: 300, Height: 200
*
* // Set uniform size
* panel.setSize(200); // Makes a square 200x200
*
* // Set size using object
* panel.setSize({
* width: 400,
* height: 300
* });
* ```
* @param value - This can be either a number or a Size object with width/height properties
* @param height - The height to set. Defaults to the value of `width` if not provided
* @see {@link NineSliceSprite#width} For setting width only
* @see {@link NineSliceSprite#height} For setting height only
*/
setSize(value: number | Optional<Size, "height">, height?: number): void;
/**
* Retrieves the size of the NineSliceSprite as a [Size]{@link Size} object.
* This method is more efficient than getting width and height separately.
* @example
* ```ts
* // Get basic size
* const size = panel.getSize();
* console.log(`Size: ${size.width}x${size.height}`);
*
* // Reuse existing size object
* const reuseSize = { width: 0, height: 0 };
* panel.getSize(reuseSize);
* ```
* @param out - Optional object to store the size in, to avoid allocating a new object
* @returns The size of the NineSliceSprite
* @see {@link NineSliceSprite#width} For getting just the width
* @see {@link NineSliceSprite#height} For getting just the height
* @see {@link NineSliceSprite#setSize} For setting both width and height efficiently
*/
getSize(out?: Size): Size;
/**
* Width of the left vertical bar (A).
* Controls the size of the left edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., leftWidth: 20 });
* sprite.leftWidth = 20; // Set left border width
* ```
* @default 10
*/
get leftWidth(): number;
set leftWidth(value: number);
/**
* Height of the top horizontal bar (C).
* Controls the size of the top edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., topHeight: 20 });
* sprite.topHeight = 20; // Set top border height
* ```
* @default 10
*/
get topHeight(): number;
set topHeight(value: number);
/**
* Width of the right vertical bar (B).
* Controls the size of the right edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., rightWidth: 20 });
* sprite.rightWidth = 20; // Set right border width
* ```
* @default 10
*/
get rightWidth(): number;
set rightWidth(value: number);
/**
* Height of the bottom horizontal bar (D).
* Controls the size of the bottom edge that remains unscaled
* @example
* ```ts
* const sprite = new NineSliceSprite({ ..., bottomHeight: 20 });
* sprite.bottomHeight = 20; // Set bottom border height
* ```
* @default 10
*/
get bottomHeight(): number;
set bottomHeight(value: number);
/**
* The texture to use on the NineSliceSprite.
* ```ts
* // Create a sprite with a texture
* const sprite = new NineSliceSprite({
* texture: Texture.from('path/to/image.png')
* });
* // Update the texture later
* sprite.texture = Texture.from('path/to/another-image.png');
* ```
* @default Texture.EMPTY
*/
get texture(): Texture;
set texture(value: Texture);
/**
* The original width of the texture before any nine-slice scaling.
* This is the width of the source texture used to create the nine-slice sprite.
* @example
* ```ts
* // Get original dimensions
* console.log(`Original size: ${sprite.originalWidth}x${sprite.originalHeight}`);
*
* // Use for relative scaling
* sprite.width = sprite.originalWidth * 2; // Double the original width
*
* // Reset to original size
* sprite.setSize(sprite.originalWidth, sprite.originalHeight);
* ```
* @readonly
* @see {@link NineSliceSprite#width} For the current displayed width
* @see {@link Texture#width} For direct texture width access
* @returns The original width of the texture
*/
get originalWidth(): number;
/**
* The original height of the texture before any nine-slice scaling.
* This is the height of the source texture used to create the nine-slice sprite.
* @example
* ```ts
* // Get original dimensions
* console.log(`Original size: ${sprite.originalWidth}x${sprite.originalHeight}`);
*
* // Use for relative scaling
* sprite.height = sprite.originalHeight * 2; // Double the original height
*
* // Reset to original size
* sprite.setSize(sprite.originalWidth, sprite.originalHeight);
* ```
* @readonly
* @see {@link NineSliceSprite#height} For the current displayed height
* @see {@link Texture#height} For direct texture height access
* @returns The original height of the texture
*/
get originalHeight(): number;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* nineSliceSprite.destroy();
* nineSliceSprite.destroy(true);
* nineSliceSprite.destroy({ texture: true, textureSource: true });
*/
destroy(options?: DestroyOptions): void;
/** @private */
protected updateBounds(): void;
}
/**
* Please use the {@link NineSliceSprite} class instead.
* The NineSlicePlane is deprecated and will be removed in future versions.
* @deprecated since 8.0.0
* @category scene
*/
export declare class NineSlicePlane extends NineSliceSprite {
constructor(options: NineSliceSpriteOptions | Texture);
/** @deprecated since 8.0.0 */
constructor(texture: Texture, leftWidth: number, topHeight: number, rightWidth: number, bottomHeight: number);
}
/** @internal */
export declare const tilingBit: {
name: string;
vertex: {
header: string;
main: string;
};
fragment: {
header: string;
main: string;
};
};
/** @internal */
export declare const tilingBitGl: {
name: string;
vertex: {
header: string;
main: string;
};
fragment: {
header: string;
main: string;
};
};
/**
* The shader used by the TilingSprite.
* @internal
*/
export declare class TilingSpriteShader extends Shader {
constructor();
updateUniforms(width: number, height: number, matrix: Matrix, anchorX: number, anchorY: number, texture: Texture): void;
}
/**
* Options for the {@link Transform} constructor.
* @category utils
* @advanced
*/
export interface TransformOptions {
/** The matrix to use. */
matrix?: Matrix;
/**
* The observer to use.
* @advanced
*/
observer?: {
_onUpdate: (transform: Transform) => void;
};
}
/**
* The Transform class facilitates the manipulation of a 2D transformation matrix through
* user-friendly properties: position, scale, rotation, skew, and pivot.
* @example
* ```ts
* // Basic transform usage
* const transform = new Transform();
* transform.position.set(100, 100);
* transform.rotation = Math.PI / 4; // 45 degrees
* transform.scale.set(2, 2);
*
* // With pivot point
* transform.pivot.set(50, 50);
* transform.rotation = Math.PI; // Rotate around pivot
*
* // Matrix manipulation
* const matrix = transform.matrix;
* const position = { x: 0, y: 0 };
* matrix.apply(position); // Transform point
* ```
* @remarks
* - Manages 2D transformation properties
* - Auto-updates matrix on changes
* - Supports observable changes
* - Common in display objects
* @category utils
* @standard
* @see {@link Matrix} For direct matrix operations
* @see {@link ObservablePoint} For point properties
*/
export declare class Transform {
/**
* The local transformation matrix.
* @internal
*/
_matrix: Matrix;
/**
* The coordinate of the object relative to the local coordinates of the parent.
* @example
* ```ts
* // Basic position setting
* transform.position.set(100, 100);
*
* // Individual coordinate access
* transform.position.x = 50;
* transform.position.y = 75;
* ```
*/
position: ObservablePoint;
/**
* The scale factor of the object.
* @example
* ```ts
* // Uniform scaling
* transform.scale.set(2, 2);
*
* // Non-uniform scaling
* transform.scale.x = 2; // Stretch horizontally
* transform.scale.y = 0.5; // Compress vertically
* ```
*/
scale: ObservablePoint;
/**
* The pivot point of the container that it rotates around.
* @example
* ```ts
* // Center pivot
* transform.pivot.set(sprite.width / 2, sprite.height / 2);
*
* // Corner rotation
* transform.pivot.set(0, 0);
* transform.rotation = Math.PI / 4; // 45 degrees
* ```
*/
pivot: ObservablePoint;
/**
* The skew amount, on the x and y axis.
* @example
* ```ts
* // Apply horizontal skew
* transform.skew.x = Math.PI / 6; // 30 degrees
*
* // Apply both skews
* transform.skew.set(Math.PI / 6, Math.PI / 8);
* ```
*/
skew: ObservablePoint;
/** The rotation amount. */
protected _rotation: number;
/**
* The X-coordinate value of the normalized local X axis,
* the first column of the local transformation matrix without a scale.
*/
protected _cx: number;
/**
* The Y-coordinate value of the normalized local X axis,
* the first column of the local transformation matrix without a scale.
*/
protected _sx: number;
/**
* The X-coordinate value of the normalized local Y axis,
* the second column of the local transformation matrix without a scale.
*/
protected _cy: number;
/**
* The Y-coordinate value of the normalized local Y axis,
* the second column of the local transformation matrix without a scale.
*/
protected _sy: number;
protected dirty: boolean;
protected observer: Observer<Transform>;
/**
* @param options - Options for the transform.
* @param options.matrix - The matrix to use.
* @param options.observer - The observer to use.
*/
constructor({ matrix, observer }?: TransformOptions);
/**
* The transformation matrix computed from the transform's properties.
* Combines position, scale, rotation, skew, and pivot into a single matrix.
* @example
* ```ts
* // Get current matrix
* const matrix = transform.matrix;
* console.log(matrix.toString());
* ```
* @readonly
* @see {@link Matrix} For matrix operations
* @see {@link Transform.setFromMatrix} For setting transform from matrix
*/
get matrix(): Matrix;
/**
* Called when a value changes.
* @param point
* @internal
*/
_onUpdate(point?: ObservablePoint): void;
/** Called when the skew or the rotation changes. */
protected updateSkew(): void;
toString(): string;
/**
* Decomposes a matrix and sets the transforms properties based on it.
* @example
* ```ts
* // Basic matrix decomposition
* const transform = new Transform();
* const matrix = new Matrix()
* .translate(100, 100)
* .rotate(Math.PI / 4)
* .scale(2, 2);
*
* transform.setFromMatrix(matrix);
* console.log(transform.position.x); // 100
* console.log(transform.rotation); // ~0.785 (π/4)
* ```
* @param matrix - The matrix to decompose
* @see {@link Matrix#decompose} For the decomposition logic
* @see {@link Transform#matrix} For getting the current matrix
*/
setFromMatrix(matrix: Matrix): void;
/**
* The rotation of the object in radians.
* @example
* ```ts
* // Basic rotation
* transform.rotation = Math.PI / 4; // 45 degrees
*
* // Rotate around pivot point
* transform.pivot.set(50, 50);
* transform.rotation = Math.PI; // 180 degrees around pivot
*
* // Animate rotation
* app.ticker.add(() => {
* transform.rotation += 0.1;
* });
* ```
* @see {@link Transform#pivot} For rotation point
* @see {@link Transform#skew} For skew effects
*/
get rotation(): number;
set rotation(value: number);
}
/** @internal */
export declare class TilingSpriteGpuData implements GPUData {
canBatch: boolean;
renderable: TilingSprite;
batchableMesh?: BatchableMesh;
geometry?: MeshGeometry;
shader?: TilingSpriteShader;
constructor();
destroy(): void;
}
/**
* The TilingSpritePipe is a render pipe for rendering TilingSprites.
* It handles the batching and rendering of TilingSprites using a shader.
* @internal
*/
export declare class TilingSpritePipe implements RenderPipe<TilingSprite> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "tilingSprite";
};
private _renderer;
private readonly _state;
private readonly _managedTilingSprites;
constructor(renderer: Renderer);
validateRenderable(renderable: TilingSprite): boolean;
addRenderable(tilingSprite: TilingSprite, instructionSet: InstructionSet): void;
execute(tilingSprite: TilingSprite): void;
updateRenderable(tilingSprite: TilingSprite): void;
private _getTilingSpriteData;
private _initTilingSpriteData;
private _updateBatchableMesh;
destroy(): void;
private _updateCanBatch;
}
/**
* Constructor options used for creating a TilingSprite instance.
* Defines the texture, tiling behavior, and rendering properties of the sprite.
* @example
* ```ts
* // Create a basic tiling sprite with repeating texture
* const tilingSprite = new TilingSprite({
* texture: Texture.from('pattern.png'),
* width: 800, // Width of the tiling area
* height: 600 // Height of the tiling area
* });
*
* const background = new TilingSprite({
* texture: Texture.from('background.png'),
* width: app.screen.width,
* height: app.screen.height,
* tilePosition: { x: 0, y: 0 },
* tileScale: { x: 1.5, y: 1.5 } // Scale up the texture
* anchor: 0.5, // Center anchor point
* roundPixels: true, // Crisp pixel rendering
* });
* ```
* @see {@link TilingSprite} For the main sprite class
* @see {@link Texture} For texture management
* @category scene
* @standard
* @noInheritDoc
*/
export interface TilingSpriteOptions extends PixiMixins.TilingSpriteOptions, ViewContainerOptions {
/**
* The anchor point of the TilingSprite (0-1 range)
*
* Controls the origin point for rotation, scaling, and positioning.
* Can be a number for uniform anchor or a PointData for separate x/y values.
* @example
* ```ts
* // Centered anchor
* const sprite = new TilingSprite({ ..., anchor: 0.5 });
* sprite.anchor = 0.5;
* // Separate x/y anchor
* sprite.anchor = { x: 0.5, y: 0.5 };
* // Right-aligned anchor
* sprite.anchor = { x: 1, y: 0 };
* // Update anchor directly
* sprite.anchor.set(0.5, 0.5);
* ```
* @default 0
*/
anchor?: PointData | number;
/**
* The offset of the tiling texture.
* Used to scroll or position the repeated pattern.
* @example
* ```ts
* // Offset the tiling pattern by 100 pixels in both x and y directions
* tilingSprite.tilePosition = { x: 100, y: 100 };
* ```
* @default {x: 0, y: 0}
*/
tilePosition?: PointData;
/**
* Scale of the tiling texture.
* Affects the size of each repeated instance of the texture.
* @example
* ```ts
* // Scale the texture by 1.5 in both x and y directions
* tilingSprite.tileScale = { x: 1.5, y: 1.5 };
* ```
* @default {x: 1, y: 1}
*/
tileScale?: PointData;
/**
* Rotation of the tiling texture in radians.
* This controls the rotation applied to the texture before tiling.
* @example
* ```ts
* // Rotate the texture by 45 degrees (in radians)
* tilingSprite.tileRotation = Math.PI / 4; // 45 degrees
* ```
* @default 0
*/
tileRotation?: number;
/**
* The texture to use for tiling.
* This is the image that will be repeated across the sprite.
* @example
* ```ts
* // Use a texture from the asset cache
* tilingSprite.texture = Texture.from('assets/pattern.png');
* ```
* @default Texture.WHITE
*/
texture?: Texture;
/**
* The width of the tiling area.
* This defines how wide the tiling sprite will be.
* @example
* ```ts
* // Set the width of the tiling sprite to 800 pixels
* tilingSprite.width = 800;
* ```
* @default 256
*/
width?: number;
/**
* The height of the tiling area.
* This defines how tall the tiling sprite will be.
* @example
* ```ts
* // Set the height of the tiling sprite to 600 pixels
* tilingSprite.height = 600;
* ```
* @default 256
*/
height?: number;
/**
* Whether the tiling pattern should originate from the anchor point.
* When true, tiling starts from the origin instead of top-left.
*
* This will make the texture coordinates assigned to each vertex dependent on the value of the anchor. Without
* this, the top-left corner always gets the (0, 0) texture coordinate.
* @example
* ```ts
* // Enable anchor-based tiling
* tilingSprite.applyAnchorToTexture = true;
* ```
* @default false
*/
applyAnchorToTexture?: boolean;
/**
* Whether to round the sprite's position to whole pixels.
* This can help with crisp rendering, especially for pixel art.
* When true, the sprite's position will be rounded to the nearest pixel.
* @example
* ```ts
* // Enable pixel rounding for crisp rendering
* tilingSprite.roundPixels = true;
* ```
* @default false
*/
roundPixels?: boolean;
}
export interface TilingSprite extends PixiMixins.TilingSprite, ViewContainer<TilingSpriteGpuData> {
}
/**
* A TilingSprite is a fast and efficient way to render a repeating texture across a given area.
* The texture can be scrolled, scaled, and rotated independently of the sprite itself.
* @example
* ```ts
* // Create a simple tiling background
* const background = new TilingSprite({
* texture: Texture.from('background.png'),
* width: app.screen.width,
* height: app.screen.height,
* });
* app.stage.addChild(background);
*
* // Create a scrolling parallax background
* const parallax = new TilingSprite({
* texture: Texture.from('clouds.png'),
* width: app.screen.width,
* height: app.screen.height,
* tileScale: { x: 0.5, y: 0.5 }
* });
*
* // Animate the tiling position
* app.ticker.add(() => {
* parallax.tilePosition.x -= 1; // Scroll left
* parallax.tilePosition.y -= 0.5; // Scroll up slowly
* });
*
* // Create a repeating pattern with rotation
* const pattern = new TilingSprite({
* texture: Texture.from('pattern.png'),
* width: 300,
* height: 200,
* tileRotation: Math.PI / 4, // 45 degree rotation
* anchor: 0.5 // Center anchor point
* });
* ```
* @category scene
* @standard
* @see {@link TilingSpriteOptions} For configuration options
* @see {@link Texture} For texture management
* @see {@link Assets} For asset loading
*/
export declare class TilingSprite extends ViewContainer<TilingSpriteGpuData> implements View, Instruction {
/**
* Creates a new tiling sprite based on a source texture or image path.
* This is a convenience method that automatically creates and manages textures.
* @example
* ```ts
* // Create a new tiling sprite from an image path
* const pattern = TilingSprite.from('pattern.png');
* pattern.width = 300; // Set the width of the tiling area
* pattern.height = 200; // Set the height of the tiling area
*
* // Create from options
* const texture = Texture.from('pattern.png');
* const pattern = TilingSprite.from(texture, {
* width: 300,
* height: 200,
* tileScale: { x: 0.5, y: 0.5 }
* });
* ```
* @param source - The source to create the sprite from. Can be a path to an image or a texture
* @param options - Additional options for the tiling sprite
* @returns A new tiling sprite based on the source
* @see {@link Texture.from} For texture creation details
* @see {@link Assets} For asset loading and management
*/
static from(source: Texture | string, options?: TilingSpriteOptions): TilingSprite;
/**
* Default options used when creating a TilingSprite instance.
* These values are used as fallbacks when specific options are not provided.
* @example
* ```ts
* // Override default options globally
* TilingSprite.defaultOptions.texture = Texture.from('defaultPattern.png');
* TilingSprite.defaultOptions.tileScale = { x: 2, y: 2 };
*
* // Create sprite using default options
* const sprite = new TilingSprite();
* // Will use defaultPattern.png and scale 2x
* ```
* @type {TilingSpriteOptions}
* @see {@link TilingSpriteOptions} For all available options
* @see {@link TilingSprite.from} For creating sprites with custom options
* @see {@link Texture.EMPTY} For the default empty texture
*/
static defaultOptions: TilingSpriteOptions;
/** @internal */
readonly renderPipeId: string;
/** @advanced */
readonly batched = true;
/**
* Flags whether the tiling pattern should originate from the origin instead of the top-left corner in
* local space.
*
* This will make the texture coordinates assigned to each vertex dependent on the value of the anchor. Without
* this, the top-left corner always gets the (0, 0) texture coordinate.
* @example
* ```ts
* // Enable anchor-based tiling
* tilingSprite.applyAnchorToTexture = true;
* ```
* @default false
*/
applyAnchorToTexture: boolean;
/**
* @see {@link TilingSpriteOptions.applyAnchorToTexture}
* @deprecated since 8.0.0
* @advanced
*/
get uvRespectAnchor(): boolean;
/** @advanced */
set uvRespectAnchor(value: boolean);
/** @internal */
_anchor: ObservablePoint;
/** @internal */
_tileTransform: Transform;
/** @internal */
_texture: Texture;
private _width;
private _height;
/**
* @param {Texture | TilingSpriteOptions} options - The options for creating the tiling sprite.
*/
constructor(options?: Texture | TilingSpriteOptions);
/** @deprecated since 8.0.0 */
constructor(texture: Texture, width: number, height: number);
/**
* Changes frame clamping in corresponding textureMatrix
* Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
* @default 0.5
* @type {number}
* @advanced
*/
get clampMargin(): number;
/** @advanced */
set clampMargin(value: number);
/**
* The anchor sets the origin point of the sprite. The default value is taken from the {@link Texture}
* and passed to the constructor.
*
* - The default is `(0,0)`, this means the sprite's origin is the top left.
* - Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered.
* - Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner.
*
* If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
* @example
* ```ts
* // Center the anchor point
* sprite.anchor = 0.5; // Sets both x and y to 0.5
* sprite.position.set(400, 300); // Sprite will be centered at this position
*
* // Set specific x/y anchor points
* sprite.anchor = {
* x: 1, // Right edge
* y: 0 // Top edge
* };
*
* // Using individual coordinates
* sprite.anchor.set(0.5, 1); // Center-bottom
*
* // For rotation around center
* sprite.anchor.set(0.5);
* sprite.rotation = Math.PI / 4; // 45 degrees around center
*
* // For scaling from center
* sprite.anchor.set(0.5);
* sprite.scale.set(2); // Scales from center point
* ```
*/
get anchor(): ObservablePoint;
set anchor(value: PointData | number);
/**
* The offset of the tiling texture.
* Used to scroll or position the repeated pattern.
* @example
* ```ts
* // Offset the tiling pattern by 100 pixels in both x and y directions
* tilingSprite.tilePosition = { x: 100, y: 100 };
* ```
* @default {x: 0, y: 0}
*/
get tilePosition(): ObservablePoint;
set tilePosition(value: PointData);
/**
* Scale of the tiling texture.
* Affects the size of each repeated instance of the texture.
* @example
* ```ts
* // Scale the texture by 1.5 in both x and y directions
* tilingSprite.tileScale = { x: 1.5, y: 1.5 };
* ```
* @default {x: 1, y: 1}
*/
get tileScale(): ObservablePoint;
set tileScale(value: PointData | number);
set tileRotation(value: number);
/**
* Rotation of the tiling texture in radians.
* This controls the rotation applied to the texture before tiling.
* @example
* ```ts
* // Rotate the texture by 45 degrees (in radians)
* tilingSprite.tileRotation = Math.PI / 4; // 45 degrees
* ```
* @default 0
*/
get tileRotation(): number;
/**
* The transform object that controls the tiling texture's position, scale, and rotation.
* This transform is independent of the sprite's own transform properties.
* @example
* ```ts
* // Access transform properties directly
* sprite.tileTransform.position.set(100, 50);
* sprite.tileTransform.scale.set(2);
* sprite.tileTransform.rotation = Math.PI / 4;
*
* // Create smooth scrolling animation
* app.ticker.add(() => {
* sprite.tileTransform.position.x += 1;
* sprite.tileTransform.rotation += 0.01;
* });
*
* // Reset transform
* sprite.tileTransform.position.set(0);
* sprite.tileTransform.scale.set(1);
* sprite.tileTransform.rotation = 0;
* ```
* @returns {Transform} The transform object for the tiling texture
* @see {@link Transform} For transform operations
* @see {@link TilingSprite#tilePosition} For position control
* @see {@link TilingSprite#tileScale} For scale control
* @see {@link TilingSprite#tileRotation} For rotation control
* @advanced
*/
get tileTransform(): Transform;
set texture(value: Texture);
/**
* The texture to use for tiling.
* This is the image that will be repeated across the sprite.
* @example
* ```ts
* // Use a texture from the asset cache
* tilingSprite.texture = Texture.from('assets/pattern.png');
* ```
* @default Texture.WHITE
*/
get texture(): Texture;
/**
* The width of the tiling area. This defines how wide the area is that the texture will be tiled across.
* @example
* ```ts
* // Create a tiling sprite
* const sprite = new TilingSprite({
* texture: Texture.from('pattern.png'),
* width: 500,
* height: 300
* });
*
* // Adjust width dynamically
* sprite.width = 800; // Expands tiling area
*
* // Update on resize
* window.addEventListener('resize', () => {
* sprite.width = app.screen.width;
* });
* ```
* @see {@link TilingSprite#setSize} For setting both width and height efficiently
* @see {@link TilingSprite#height} For setting height
*/
set width(value: number);
get width(): number;
set height(value: number);
/**
* The height of the tiling area. This defines how tall the area is that the texture will be tiled across.
* @example
* ```ts
* // Create a tiling sprite
* const sprite = new TilingSprite({
* texture: Texture.from('pattern.png'),
* width: 500,
* height: 300
* });
*
* // Adjust width dynamically
* sprite.height = 800; // Expands tiling area
*
* // Update on resize
* window.addEventListener('resize', () => {
* sprite.height = app.screen.height;
* });
* ```
* @see {@link TilingSprite#setSize} For setting both width and height efficiently
* @see {@link TilingSprite#width} For setting width
*/
get height(): number;
/**
* Sets the size of the TilingSprite to the specified width and height.
* This is faster than setting width and height separately as it only triggers one update.
* @example
* ```ts
* // Set specific dimensions
* sprite.setSize(300, 200); // Width: 300, Height: 200
*
* // Set uniform size (square)
* sprite.setSize(400); // Width: 400, Height: 400
*
* // Set size using object
* sprite.setSize({
* width: 500,
* height: 300
* });
* ```
* @param value - This can be either a number for uniform sizing or a Size object with width/height properties
* @param height - The height to set. Defaults to the value of `width` if not provided
* @see {@link TilingSprite#width} For setting width only
* @see {@link TilingSprite#height} For setting height only
*/
setSize(value: number | Optional<Size, "height">, height?: number): void;
/**
* Retrieves the size of the TilingSprite as a {@link Size} object.
* This method is more efficient than getting width and height separately as it only allocates one object.
* @example
* ```ts
* // Get basic size
* const size = sprite.getSize();
* console.log(`Size: ${size.width}x${size.height}`);
*
* // Reuse existing size object
* const reuseSize = { width: 0, height: 0 };
* sprite.getSize(reuseSize);
* ```
* @param out - Optional object to store the size in, to avoid allocating a new object
* @returns The size of the TilingSprite
* @see {@link TilingSprite#width} For getting just the width
* @see {@link TilingSprite#height} For getting just the height
* @see {@link TilingSprite#setSize} For setting both width and height efficiently
*/
getSize(out?: Size): Size;
/** @private */
protected updateBounds(): void;
/**
* Checks if the object contains the given point in local coordinates.
* Takes into account the anchor offset when determining boundaries.
* @example
* ```ts
* // Create a tiling sprite
* const sprite = new TilingSprite({
* texture: Texture.from('pattern.png'),
* width: 200,
* height: 100,
* anchor: 0.5 // Center anchor
* });
*
* // Basic point check
* const contains = sprite.containsPoint({ x: 50, y: 25 });
* console.log('Point is inside:', contains);
*
* // Check with different anchors
* sprite.anchor.set(0); // Top-left anchor
* console.log('Contains point:', sprite.containsPoint({ x: 150, y: 75 }));
* ```
* @param point - The point to check in local coordinates
* @returns True if the point is within the sprite's bounds
* @see {@link TilingSprite#toLocal} For converting global coordinates to local
* @see {@link TilingSprite#anchor} For understanding boundary calculations
*/
containsPoint(point: PointData): boolean;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* tilingSprite.destroy();
* tilingSprite.destroy(true);
* tilingSprite.destroy({ texture: true, textureSource: true });
*/
destroy(options?: DestroyOptions): void;
}
/**
* @param array
* @param stride
* @param offset
* @param matrix
* @internal
*/
export declare function applyMatrix(array: TypedArray, stride: number, offset: number, matrix: Matrix): void;
/** @internal */
export declare class QuadGeometry extends MeshGeometry {
constructor();
}
/**
* @param tilingSprite
* @param positions
* @internal
*/
export declare function setPositions(tilingSprite: TilingSprite, positions: Float32Array): void;
/**
* @param tilingSprite
* @param uvs
* @internal
*/
export declare function setUvs(tilingSprite: TilingSprite, uvs: Float32Array): void;
/**
* A number, or a string containing a number.
* @category text
* @typedef {object} FontMetrics
* @property {number} ascent - Font ascent
* @property {number} descent - Font descent
* @property {number} fontSize - Font size
* @advanced
*/
export interface FontMetrics {
ascent: number;
descent: number;
fontSize: number;
}
/**
* The TextMetrics object represents the measurement of a block of text with a specified style.
* @example
* import { CanvasTextMetrics, TextStyle } from 'pixi.js';
*
* const style = new TextStyle({
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* });
* const textMetrics = CanvasTextMetrics.measureText('Your text', style);
* @category text
* @advanced
*/
export declare class CanvasTextMetrics {
/** The text that was measured. */
text: string;
/** The style that was measured. */
style: TextStyle;
/** The measured width of the text. */
width: number;
/** The measured height of the text. */
height: number;
/** An array of lines of the text broken by new lines and wrapping is specified in style. */
lines: string[];
/** An array of the line widths for each line matched to `lines`. */
lineWidths: number[];
/** The measured line height for this style. */
lineHeight: number;
/** The maximum line width for all measured lines. */
maxLineWidth: number;
/** The font properties object from TextMetrics.measureFont. */
fontProperties: FontMetrics;
/**
* String used for calculate font metrics.
* These characters are all tall to help calculate the height required for text.
*/
static METRICS_STRING: string;
/** Baseline symbol for calculate font metrics. */
static BASELINE_SYMBOL: string;
/** Baseline multiplier for calculate font metrics. */
static BASELINE_MULTIPLIER: number;
/** Height multiplier for setting height of canvas to calculate font metrics. */
static HEIGHT_MULTIPLIER: number;
/**
* A Unicode "character", or "grapheme cluster", can be composed of multiple Unicode code points,
* such as letters with diacritical marks (e.g. `'\u0065\u0301'`, letter e with acute)
* or emojis with modifiers (e.g. `'\uD83E\uDDD1\u200D\uD83D\uDCBB'`, technologist).
* The new `Intl.Segmenter` API in ES2022 can split the string into grapheme clusters correctly. If it is not available,
* PixiJS will fallback to use the iterator of String, which can only spilt the string into code points.
* If you want to get full functionality in environments that don't support `Intl.Segmenter` (such as Firefox),
* you can use other libraries such as [grapheme-splitter]{@link https://www.npmjs.com/package/grapheme-splitter}
* or [graphemer]{@link https://www.npmjs.com/package/graphemer} to create a polyfill. Since these libraries can be
* relatively large in size to handle various Unicode grapheme clusters properly, PixiJS won't use them directly.
*/
static graphemeSegmenter: (s: string) => string[];
static _experimentalLetterSpacingSupported?: boolean;
/**
* Checking that we can use modern canvas 2D API.
*
* Note: This is an unstable API, Chrome < 94 use `textLetterSpacing`, later versions use `letterSpacing`.
* @see TextMetrics.experimentalLetterSpacing
* @see https://developer.mozilla.org/en-US/docs/Web/API/ICanvasRenderingContext2D/letterSpacing
* @see https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441
*/
static get experimentalLetterSpacingSupported(): boolean;
/**
* New rendering behavior for letter-spacing which uses Chrome's new native API. This will
* lead to more accurate letter-spacing results because it does not try to manually draw
* each character. However, this Chrome API is experimental and may not serve all cases yet.
* @see TextMetrics.experimentalLetterSpacingSupported
*/
static experimentalLetterSpacing: boolean;
/** Cache of {@link TextMetrics.FontMetrics} objects. */
private static _fonts;
/** Cache of new line chars. */
private static readonly _newlines;
/** Cache of breaking spaces. */
private static readonly _breakingSpaces;
private static __canvas;
private static __context;
/** Cache for measured text metrics */
private static readonly _measurementCache;
/**
* @param text - the text that was measured
* @param style - the style that was measured
* @param width - the measured width of the text
* @param height - the measured height of the text
* @param lines - an array of the lines of text broken by new lines and wrapping if specified in style
* @param lineWidths - an array of the line widths for each line matched to `lines`
* @param lineHeight - the measured line height for this style
* @param maxLineWidth - the maximum line width for all measured lines
* @param {FontMetrics} fontProperties - the font properties object from TextMetrics.measureFont
*/
constructor(text: string, style: TextStyle, width: number, height: number, lines: string[], lineWidths: number[], lineHeight: number, maxLineWidth: number, fontProperties: FontMetrics);
/**
* Measures the supplied string of text and returns a Rectangle.
* @param text - The text to measure.
* @param style - The text style to use for measuring
* @param canvas - optional specification of the canvas to use for measuring.
* @param wordWrap
* @returns Measured width and height of the text.
*/
static measureText(text: string, style: TextStyle, canvas?: ICanvas, wordWrap?: boolean): CanvasTextMetrics;
private static _measureText;
/**
* Applies newlines to a string to have it optimally fit into the horizontal
* bounds set by the Text object's wordWrapWidth property.
* @param text - String to apply word wrapping to
* @param style - the style to use when wrapping
* @param canvas - optional specification of the canvas to use for measuring.
* @returns New string with new lines applied where required
*/
private static _wordWrap;
/**
* Convenience function for logging each line added during the wordWrap method.
* @param line - The line of text to add
* @param newLine - Add new line character to end
* @returns A formatted line
*/
private static _addLine;
/**
* Gets & sets the widths of calculated characters in a cache object
* @param key - The key
* @param letterSpacing - The letter spacing
* @param cache - The cache
* @param context - The canvas context
* @returns The from cache.
*/
private static _getFromCache;
/**
* Determines whether we should collapse breaking spaces.
* @param whiteSpace - The TextStyle property whiteSpace
* @returns Should collapse
*/
private static _collapseSpaces;
/**
* Determines whether we should collapse newLine chars.
* @param whiteSpace - The white space
* @returns should collapse
*/
private static _collapseNewlines;
/**
* Trims breaking whitespaces from string.
* @param text - The text
* @returns Trimmed string
*/
private static _trimRight;
/**
* Determines if char is a newline.
* @param char - The character
* @returns True if newline, False otherwise.
*/
private static _isNewline;
/**
* Determines if char is a breaking whitespace.
*
* It allows one to determine whether char should be a breaking whitespace
* For example certain characters in CJK langs or numbers.
* It must return a boolean.
* @param char - The character
* @param [_nextChar] - The next character
* @returns True if whitespace, False otherwise.
*/
static isBreakingSpace(char: string, _nextChar?: string): boolean;
/**
* Splits a string into words, breaking-spaces and newLine characters
* @param text - The text
* @returns A tokenized array
*/
private static _tokenize;
/**
* Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
*
* It allows one to customise which words should break
* Examples are if the token is CJK or numbers.
* It must return a boolean.
* @param _token - The token
* @param breakWords - The style attr break words
* @returns Whether to break word or not
*/
static canBreakWords(_token: string, breakWords: boolean): boolean;
/**
* Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
*
* It allows one to determine whether a pair of characters
* should be broken by newlines
* For example certain characters in CJK langs or numbers.
* It must return a boolean.
* @param _char - The character
* @param _nextChar - The next character
* @param _token - The token/word the characters are from
* @param _index - The index in the token of the char
* @param _breakWords - The style attr break words
* @returns whether to break word or not
*/
static canBreakChars(_char: string, _nextChar: string, _token: string, _index: number, _breakWords: boolean): boolean;
/**
* Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
*
* It is called when a token (usually a word) has to be split into separate pieces
* in order to determine the point to break a word.
* It must return an array of characters.
* @param token - The token to split
* @returns The characters of the token
* @see CanvasTextMetrics.graphemeSegmenter
*/
static wordWrapSplit(token: string): string[];
/**
* Calculates the ascent, descent and fontSize of a given font-style
* @param font - String representing the style of the font
* @returns Font properties object
*/
static measureFont(font: string): FontMetrics;
/**
* Clear font metrics in metrics cache.
* @param {string} [font] - font name. If font name not set then clear cache for all fonts.
*/
static clearMetrics(font?: string): void;
/**
* Cached canvas element for measuring text
* TODO: this should be private, but isn't because of backward compat, will fix later.
* @ignore
*/
static get _canvas(): ICanvas;
/**
* TODO: this should be private, but isn't because of backward compat, will fix later.
* @ignore
*/
static get _context(): ICanvasRenderingContext2D;
}
/**
* @category text
* @advanced
*/
export interface CharData {
/** Unique id of character */
id: number;
/** x-offset to apply when rendering character */
xOffset: number;
/** y-offset to apply when rendering character. */
yOffset: number;
/** Advancement to apply to next character. */
xAdvance: number;
/** The kerning values for this character. */
kerning: Record<string, number>;
/** The texture of the character. */
texture?: Texture;
}
/**
* The raw data of a character in a bitmap font.
* @category text
* @advanced
*/
export interface RawCharData extends Omit<CharData, "texture"> {
/** The page of the font texture that the character is on. */
page: number;
/** The x position of the character in the page. */
x: number;
/** The y position of the character in the page. */
y: number;
/** The width of the character in the page. */
width: number;
/** The height of the character in the page. */
height: number;
/** The letter of the character. */
letter: string;
}
/**
* The raw data of a bitmap font.
* @category text
* @advanced
*/
export interface BitmapFontData {
/** The offset of the font face from the baseline. */
baseLineOffset: number;
/** The map of characters by character code. */
chars: Record<string, RawCharData>;
/** The map of base page textures (i.e., sheets of glyphs). */
pages: {
/** Unique id for bitmap texture */
id: number;
/** File name */
file: string;
}[];
/** The line-height of the font face in pixels. */
lineHeight: number;
/** The size of the font face in pixels. */
fontSize: number;
/** The name of the font face. */
fontFamily: string;
/** The range and type of the distance field for this font. */
distanceField?: {
/** Type of distance field */
type: "sdf" | "msdf" | "none";
/** Range of the distance field in pixels */
range: number;
};
}
interface BitmapFontEvents<Type> {
destroy: [
Type
];
}
/**
* An abstract representation of a bitmap font.
* @category text
* @advanced
*/
export declare abstract class AbstractBitmapFont<FontType> extends EventEmitter<BitmapFontEvents<FontType>> implements Omit<BitmapFontData, "chars" | "pages" | "fontSize"> {
/** The map of characters by character code. */
readonly chars: Record<string, CharData>;
/**
* The line-height of the font face in pixels.
* @type {number}
*/
readonly lineHeight: BitmapFontData["lineHeight"];
/**
* The name of the font face
* @type {string}
*/
readonly fontFamily: BitmapFontData["fontFamily"];
/** The metrics of the font face. */
readonly fontMetrics: FontMetrics;
/**
* The offset of the font face from the baseline.
* @type {number}
*/
readonly baseLineOffset: BitmapFontData["baseLineOffset"];
/** The range and type of the distance field for this font. */
readonly distanceField: BitmapFontData["distanceField"];
/** The map of base page textures (i.e., sheets of glyphs). */
readonly pages: {
texture: Texture;
}[];
/** should the fill for this font be applied as a tint to the text. */
applyFillAsTint: boolean;
/** The size of the font face in pixels. */
readonly baseMeasurementFontSize: number;
protected baseRenderedFontSize: number;
/**
* The name of the font face.
* @deprecated since 8.0.0 Use `fontFamily` instead.
*/
get font(): BitmapFontData["fontFamily"];
/**
* The map of base page textures (i.e., sheets of glyphs).
* @deprecated since 8.0.0 Use `pages` instead.
*/
get pageTextures(): AbstractBitmapFont<FontType>["pages"];
/**
* The size of the font face in pixels.
* @deprecated since 8.0.0 Use `fontMetrics.fontSize` instead.
*/
get size(): BitmapFontData["fontSize"];
/**
* The kind of distance field for this font or "none".
* @deprecated since 8.0.0 Use `distanceField.type` instead.
*/
get distanceFieldRange(): NonNullable<BitmapFontData["distanceField"]>["range"];
/**
* The range of the distance field in pixels.
* @deprecated since 8.0.0 Use `distanceField.range` instead.
*/
get distanceFieldType(): NonNullable<BitmapFontData["distanceField"]>["type"];
destroy(destroyTextures?: boolean): void;
}
/**
* Internal data format used to convert to BitmapFontData.
* @private
*/
export interface BitmapFontRawData {
info: {
face: string;
size: string;
}[];
common: {
lineHeight: string;
base: string;
}[];
page: {
id: string;
file: string;
}[];
chars: {
count: number;
}[];
char: {
id: string;
page: string;
xoffset: string;
yoffset: string;
xadvance: string;
x: string;
y: string;
width: string;
height: string;
letter?: string;
char?: string;
}[];
kernings?: {
count: number;
}[];
kerning?: {
first: string;
second: string;
amount: string;
}[];
distanceField?: {
fieldType: "sdf" | "msdf" | "none";
distanceRange: string;
}[];
}
/** @internal */
export declare const bitmapFontTextParser: {
test(data: string | XMLDocument | BitmapFontData): boolean;
parse(txt: string): BitmapFontData;
};
/** @internal */
export declare const bitmapFontXMLParser: {
test(data: string | XMLDocument | BitmapFontData): boolean;
parse(xml: Document): BitmapFontData;
};
/** @internal */
export declare const bitmapFontXMLStringParser: {
test(data: string | XMLDocument | BitmapFontData): boolean;
parse(data: string): BitmapFontData;
};
/**
* A utility type that allows a value to be either a single item of type T or an array of items of type T.
* @category utils
* @advanced
*/
export type ArrayOr<T> = T | T[];
/**
* @deprecated Use {@link AssetParser} instead.
* @category assets
* @advanced
*/
export type LoadParserName = "loadJson" | "loadSvg" | "loadTextures" | "loadTxt" | "loadVideo" | "loadWebFont" | (string & {});
/**
* Names of the parsers that are built into PixiJS.
* @example
* ```ts
* Assets.load({
* src: assetToLoad,
* parser: 'json' // Use the built-in JSON parser
* });
* ```
* @category assets
* @advanced
*/
export type AssetParser = "json" | "svg" | "text" | "video" | "web-font" | "bitmap-font" | "spritesheet" | "texture" | "basis" | "dds" | "ktx2" | "ktx" | (string & {});
/**
* A fully resolved asset, with all the information needed to load it.
* This represents an asset that has been processed by the resolver and is ready to be loaded.
* @example
* ```ts
* // Basic resolved asset
* const asset: ResolvedAsset = {
* alias: ['hero'],
* src: 'hero.png',
* format: 'png'
* };
*
* // Resolved asset with multiple aliases
* const asset: ResolvedAsset = {
* alias: ['character', 'player'],
* src: 'character@2x.webp',
* format: 'webp',
* };
*
* // Resolved asset with specific parser
* const asset: ResolvedAsset = {
* alias: ['config'],
* src: 'data.txt',
* format: 'txt',
* parser: 'text'
* };
* ```
* @category assets
* @standard
*/
export interface ResolvedAsset<T = any> {
/** Array of alternative names for this asset. Used for looking up the same asset by different keys. */
alias?: string[];
/** The URL or relative path to the asset. This is the final, resolved path that will be used for loading. */
src?: string;
/**
* Optional data passed to the asset loader.
* Can include texture settings, parser options, or other asset-specific data.
*/
data?: T;
/** File format of the asset, usually the file extension. Used to determine which loader parser to use. */
format?: string;
/**
* @deprecated Use `parser` instead.
*/
loadParser?: LoadParserName;
/** Override to specify which parser should load this asset. Useful when file extensions don't match the content type. */
parser?: AssetParser;
/**
* The amount of progress an asset will contribute to the onProgress event when loading.
* This can be any arbitrary value but typically represents the file size.
* @default 1
*/
progressSize?: number;
}
/**
* A fully resolved src specification after pattern resolution and format detection.
* Unlike raw asset sources, this type represents the final, concrete source path and format.
* @example
* ```ts
* // Basic resolved source
* const src: ResolvedSrc = {
* src: 'images/sprite.png',
* format: 'png'
* };
*
* // With resolution and format preferences
* const src: ResolvedSrc = {
* src: 'images/sprite@2x.webp',
* format: 'webp',
* data: { resolution: 2 }
* };
*
* // With specific loader
* const src: ResolvedSrc = {
* src: 'data/config.txt',
* format: 'txt',
* parser: 'text',
* };
* ```
* @remarks
* - Pattern strings like `{png,webp}` are resolved to specific formats
* - Resolution and format are determined based on browser support
* - Used internally by the Assets system after resolution
* - Data property can contain format-specific options
* @see {@link AssetSrc} For unresolved source format
* @see {@link ResolvedAsset} For complete resolved asset specification
* @category assets
* @advanced
* @interface
*/
export type ResolvedSrc = Pick<ResolvedAsset, "src" | "format" | "loadParser" | "parser" | "data">;
/**
* A valid asset source specification. This can be a URL string, a {@link ResolvedSrc},
* or an array of either. The source defines where and how to load an asset.
* @example
* ```ts
* // Single URL string
* const src: AssetSrc = 'images/sprite.png';
*
* // Multiple format options
* const src: AssetSrc = ['sprite.webp', 'sprite.png'];
*
* // With format pattern
* const src: AssetSrc = 'sprite.{webp,png}';
*
* // Resolved source with options
* const src: AssetSrc = {
* src: 'sprite.png',
* format: 'png',
* parser: 'texture',
* data: {
* scaleMode: 'nearest',
* }
* };
*
* // Array of resolved sources
* const src: AssetSrc = [
* {
* src: 'sprite@2x.webp',
* format: 'webp',
* },
* {
* src: 'sprite.png',
* format: 'png',
* }
* ];
* ```
* @remarks
* When specifying multiple formats:
* - The format that is selected will depend on {@link AssetInitOptions.texturePreference}
* - Resolution is parsed from file names
* - Custom data can be passed to loaders
* @see {@link ResolvedSrc} For resolved source format
* @see {@link Assets.add} For adding assets with sources
* @category assets
* @standard
*/
export type AssetSrc = ArrayOr<string> | (ArrayOr<ResolvedSrc> & {
[key: string]: any;
});
/**
* An asset that has not been resolved yet. This is the initial format used when adding assets
* to the Assets system before they are processed into a {@link ResolvedAsset}.
* @example
* ```ts
* // Basic unresolved asset
* const asset: UnresolvedAsset = {
* alias: 'hero',
* src: 'hero.png'
* };
*
* // Multiple aliases and formats
* const asset: UnresolvedAsset = {
* alias: ['hero', 'player'],
* src: 'hero.{webp,png}',
* data: {
* scaleMode: 'nearest',
* }
* };
*
* // Asset with multiple sources and formats
* const asset: UnresolvedAsset = {
* alias: 'background',
* src: [
* 'bg@2x.webp',
* 'bg@1x.webp',
* 'bg@2x.png',
* 'bg@1x.png',
* ]
* };
*
* // With specific loader
* const asset: UnresolvedAsset = {
* alias: 'config',
* src: 'data.txt',
* parser: 'text'
* };
* ```
* @remarks
* - Used as input format when adding assets to the system
* - Can specify multiple aliases for the same asset
* - Supports format patterns for browser compatibility
* - Can include loader-specific data and options
* @see {@link ResolvedAsset} For the resolved asset format
* @see {@link Assets.add} For adding unresolved assets
* @category assets
* @standard
* @interface
*/
export type UnresolvedAsset<T = any> = Pick<ResolvedAsset<T>, "data" | "format" | "loadParser" | "parser"> & {
/** Aliases associated with asset */
alias?: ArrayOr<string>;
/** The URL or relative path to the asset */
src?: AssetSrc;
[key: string]: any;
};
/**
* Structure of a bundle found in a {@link AssetsManifest} file. Bundles allow you to
* group related assets together for easier management and loading.
* @example
* ```ts
* // Basic bundle structure
* const bundle: AssetsBundle = {
* name: 'level-1',
* assets: [
* {
* alias: 'background',
* src: 'level1/bg.{webp,png}'
* },
* {
* alias: 'sprites',
* src: 'level1/sprites.json'
* }
* ]
* };
*
* // Using object format for assets
* const bundle: AssetsBundle = {
* name: 'ui',
* assets: {
* button: 'ui/button.png',
* panel: 'ui/panel.png',
* icons: ['ui/icons.webp', 'ui/icons.png']
* }
* };
* ```
* @see {@link Assets.addBundle} For adding bundles programmatically
* @see {@link Assets.loadBundle} For loading bundles
* @category assets
* @standard
*/
export interface AssetsBundle {
/** Unique identifier for the bundle */
name: string;
/** Assets contained in the bundle. Can be an array of assets or a record mapping aliases to sources. */
assets: UnresolvedAsset[] | Record<string, ArrayOr<string> | UnresolvedAsset>;
}
/**
* The manifest format for defining all assets in your application. Manifests provide a
* structured way to organize and manage your assets through bundles.
* @example
* ```ts
* const manifest: AssetsManifest = {
* bundles: [
* {
* name: 'loading',
* assets: [
* {
* alias: 'logo',
* src: 'logo.{webp,png}',
* data: { scaleMode: 'nearest' }
* },
* {
* alias: 'progress-bar',
* src: 'progress.png'
* }
* ]
* },
* {
* name: 'game',
* assets: {
* background: ['bg.webp', 'bg.png'],
* character: 'hero.json',
* music: 'theme.mp3'
* }
* }
* ]
* };
*
* // Initialize with manifest
* await Assets.init({ manifest });
*
* // Load bundles as needed
* await Assets.loadBundle('loading');
* await Assets.loadBundle('game');
* ```
* @see {@link Assets.init} For initializing with a manifest
* @see {@link AssetsBundle} For bundle structure details
* @category assets
* @standard
*/
export interface AssetsManifest {
/** Array of asset bundles that make up the manifest */
bundles: AssetsBundle[];
}
/**
* 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)
* @category assets
* @advanced
*/
export interface CacheParser<T = any> {
/** The extension type of this cache parser */
extension?: ExtensionMetadata;
/** A config to adjust the parser */
config?: Record<string, any>;
/**
* Gets called by the cache when a dev caches an asset
* @param asset - the asset to test
*/
test: (asset: T) => boolean;
/**
* 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.
* @param keys - The keys to cache the assets under
* @param asset - The asset to get the cacheable assets from
* @returns A key-value pair of cacheable assets
*/
getCacheableAssets: (keys: string[], asset: T) => Record<string, any>;
}
declare class CacheClass {
private readonly _parsers;
private readonly _cache;
private readonly _cacheMap;
/** Clear all entries. */
reset(): void;
/**
* Check if the key exists
* @param key - The key to check
*/
has(key: any): boolean;
/**
* Fetch entry by key
* @param key - The key of the entry to get
*/
get<T = any>(key: any): T;
/**
* Set a value by key or keys name
* @param key - The key or keys to set
* @param value - The value to store in the cache or from which cacheable assets will be derived.
*/
set<T = any>(key: any | any[], value: T): void;
/**
* Remove entry by key
*
* This function will also remove any associated alias from the cache also.
* @param key - The key of the entry to remove
*/
remove(key: any): void;
/**
* All loader parsers registered
* @advanced
*/
get parsers(): CacheParser[];
}
/**
* A global cache for all assets in your PixiJS application. The cache system provides fast
* access to loaded assets and prevents duplicate loading.
*
* Key Features:
* - Automatic caching of loaded assets
* - Support for custom cache parsers
* - Automatic parsing of complex assets (e.g., spritesheets)
* - Memory management utilities
* > [!IMPORTANT] You typically do not need to use this class directly.
* > Use the main {@link Assets} class for high-level asset management.
* > `Assets.get(key)` will automatically use the cache.
* @example
* ```ts
* import { Cache } from 'pixi.js';
*
* // Store an asset in the cache
* Cache.set('myTexture', texture);
*
* // Retrieve an asset
* const texture = Cache.get('myTexture');
*
* // Check if an asset exists
* if (Cache.has('myTexture')) {
* // Use the cached asset
* const sprite = new Sprite(Cache.get('myTexture'));
* }
*
* // Remove an asset from cache
* Cache.remove('myTexture');
*
* // Clear all cached assets
* Cache.reset();
* ```
* @remarks
* The Cache is a core component of PixiJS' asset management system:
* - Used internally by the {@link Assets} class
* - Supports automatic parsing via {@link CacheParser}
* - Handles complex asset types like spritesheets
* - Manages memory through asset removal
*
* > [!IMPORTANT]
* > This is a singleton class and should not be instantiated directly.
* > Use the exported `Cache` instance instead.
* @see {@link Assets} For high-level asset management
* @see {@link CacheParser} For custom cache parsing
* @category assets
* @class
* @advanced
*/
declare const Cache$1: CacheClass;
/**
* Configuration for the [loadTextures]{@link loadTextures} plugin.
* @see loadTextures
* @category assets
* @advanced
*/
export interface LoadTextureConfig {
/**
* 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`.
* @default true
*/
preferWorkers: boolean;
/**
* When set to `true`, loading and decoding images will happen with `createImageBitmap`,
* otherwise it will use `new Image()`.
* @default true
*/
preferCreateImageBitmap: boolean;
/**
* The crossOrigin value to use for images when `preferCreateImageBitmap` is `false`.
* @default 'anonymous'
*/
crossOrigin: ImageLike["crossOrigin"];
}
/**
* Returns a promise that resolves an ImageBitmaps.
* This function is designed to be used by a worker.
* Part of WorkerManager!
* @param url - The image to load an image bitmap for
* @ignore
*/
export declare function loadImageBitmap(url: string, asset?: ResolvedAsset<TextureSourceOptions<any>>): Promise<ImageBitmap>;
/**
* 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]{@link LoadTextureConfig}
* ```js
* // 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',
* };
* ```
* @category assets
* @advanced
*/
export declare const loadTextures: LoaderParser<Texture, TextureSourceOptions, LoadTextureConfig>;
/**
* A prefer order lets the resolver know which assets to prefer depending on the various parameters passed to it.
* @category assets
* @standard
*/
export interface PreferOrder {
/** the importance order of the params */
priority?: string[];
params: {
[key: string]: any;
};
}
/**
* Format for url parser, will test a string and if it pass will then parse it, turning it into an ResolvedAsset
* @category assets
* @advanced
*/
export interface ResolveURLParser {
extension?: ExtensionMetadata;
/** A config to adjust the parser */
config?: Record<string, any>;
/** the test to perform on the url to determine if it should be parsed */
test: (url: string) => boolean;
/** the function that will convert the url into an object */
parse: (value: string) => ResolvedAsset & {
[key: string]: any;
};
}
/**
* Options for how the resolver deals with generating bundle ids
* @category assets
* @advanced
*/
export interface BundleIdentifierOptions {
/** The character that is used to connect the bundleId and the assetId when generating a bundle asset id key */
connector?: string;
/**
* A function that generates a bundle asset id key from a bundleId and an assetId
* @param bundleId - the bundleId
* @param assetId - the assetId
* @returns the bundle asset id key
*/
createBundleAssetId?: (bundleId: string, assetId: string) => string;
/**
* A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId
* @param bundleId - the bundleId
* @param assetBundleId - the bundle asset id key
* @returns the assetId
*/
extractAssetIdFromBundle?: (bundleId: string, assetBundleId: string) => string;
}
/**
* A class that is responsible for resolving mapping asset URLs to keys.
* At its most basic it can be used for Aliases:
*
* ```js
* resolver.add('foo', 'bar');
* resolver.resolveUrl('foo') // => 'bar'
* ```
*
* It can also be used to resolve the most appropriate asset for a given URL:
*
* ```js
* resolver.prefer({
* params: {
* format: 'webp',
* resolution: 2,
* }
* });
*
* resolver.add('foo', ['bar@2x.webp', 'bar@2x.png', 'bar.webp', 'bar.png']);
*
* resolver.resolveUrl('foo') // => 'bar@2x.webp'
* ```
* Other features include:
* - Ability to process a manifest file to get the correct understanding of how to resolve all assets
* - Ability to add custom parsers for specific file types
* - Ability to add custom prefer rules
*
* This class only cares about the URL, not the loading of the asset itself.
*
* It is not intended that this class is created by developers - its part of the Asset class
* This is the third major system of PixiJS' main Assets class
* @category assets
* @advanced
*/
export declare class Resolver {
/**
* The prefix that denotes a URL is for a retina asset.
* @default /@([0-9\.]+)x/
* @example `@2x`
*/
static RETINA_PREFIX: RegExp;
private readonly _defaultBundleIdentifierOptions;
/** The character that is used to connect the bundleId and the assetId when generating a bundle asset id key */
private _bundleIdConnector;
/**
* A function that generates a bundle asset id key from a bundleId and an assetId
* @param bundleId - the bundleId
* @param assetId - the assetId
* @returns the bundle asset id key
*/
private _createBundleAssetId;
/**
* A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId
* @param bundleId - the bundleId
* @param assetBundleId - the bundle asset id key
* @returns the assetId
*/
private _extractAssetIdFromBundle;
private _assetMap;
private _preferredOrder;
private readonly _parsers;
private _resolverHash;
private _rootPath;
private _basePath;
private _manifest;
private _bundles;
private _defaultSearchParams;
/**
* Override how the resolver deals with generating bundle ids.
* must be called before any bundles are added
* @param bundleIdentifier - the bundle identifier options
*/
setBundleIdentifier(bundleIdentifier: BundleIdentifierOptions): void;
/**
* Let the resolver know which assets you prefer to use when resolving assets.
* Multiple prefer user defined rules can be added.
* @example
* resolver.prefer({
* // first look for something with the correct format, and then then correct resolution
* priority: ['format', 'resolution'],
* params:{
* format:'webp', // prefer webp images
* resolution: 2, // prefer a resolution of 2
* }
* })
* resolver.add('foo', ['bar@2x.webp', 'bar@2x.png', 'bar.webp', 'bar.png']);
* resolver.resolveUrl('foo') // => 'bar@2x.webp'
* @param preferOrders - the prefer options
*/
prefer(...preferOrders: PreferOrder[]): void;
/**
* Set the base path to prepend to all urls when resolving
* @example
* resolver.basePath = 'https://home.com/';
* resolver.add('foo', 'bar.ong');
* resolver.resolveUrl('foo', 'bar.png'); // => 'https://home.com/bar.png'
* @param basePath - the base path to use
*/
set basePath(basePath: string);
get basePath(): string;
/**
* Set the root path for root-relative URLs. By default the `basePath`'s root is used. If no `basePath` is set, then the
* default value for browsers is `window.location.origin`
* @example
* // Application hosted on https://home.com/some-path/index.html
* resolver.basePath = 'https://home.com/some-path/';
* resolver.rootPath = 'https://home.com/';
* resolver.add('foo', '/bar.png');
* resolver.resolveUrl('foo', '/bar.png'); // => 'https://home.com/bar.png'
* @param rootPath - the root path to use
*/
set rootPath(rootPath: string);
get rootPath(): string;
/**
* All the active URL parsers that help the parser to extract information and create
* an asset object-based on parsing the URL itself.
*
* Can be added using the extensions API
* @example
* resolver.add('foo', [
* {
* resolution: 2,
* format: 'png',
* src: 'image@2x.png',
* },
* {
* resolution:1,
* format:'png',
* src: 'image.png',
* },
* ]);
*
* // With a url parser the information such as resolution and file format could extracted from the url itself:
* extensions.add({
* extension: ExtensionType.ResolveParser,
* test: loadTextures.test, // test if url ends in an image
* parse: (value: string) =>
* ({
* resolution: parseFloat(Resolver.RETINA_PREFIX.exec(value)?.[1] ?? '1'),
* format: value.split('.').pop(),
* src: value,
* }),
* });
*
* // Now resolution and format can be extracted from the url
* resolver.add('foo', [
* 'image@2x.png',
* 'image.png',
* ]);
*/
get parsers(): ResolveURLParser[];
/** Used for testing, this resets the resolver to its initial state */
reset(): void;
/**
* Sets the default URL search parameters for the URL resolver. The urls can be specified as a string or an object.
* @param searchParams - the default url parameters to append when resolving urls
*/
setDefaultSearchParams(searchParams: string | Record<string, unknown>): void;
/**
* Returns the aliases for a given asset
* @param asset - the asset to get the aliases for
*/
getAlias(asset: UnresolvedAsset): string[];
/**
* Add a manifest to the asset resolver. This is a nice way to add all the asset information in one go.
* generally a manifest would be built using a tool.
* @param manifest - the manifest to add to the resolver
*/
addManifest(manifest: AssetsManifest): void;
/**
* This adds a bundle of assets in one go so that you can resolve them as a group.
* For example you could add a bundle for each screen in you pixi app
* @example
* resolver.addBundle('animals', [
* { alias: 'bunny', src: 'bunny.png' },
* { alias: 'chicken', src: 'chicken.png' },
* { alias: 'thumper', src: 'thumper.png' },
* ]);
* // or
* resolver.addBundle('animals', {
* bunny: 'bunny.png',
* chicken: 'chicken.png',
* thumper: 'thumper.png',
* });
*
* const resolvedAssets = await resolver.resolveBundle('animals');
* @param bundleId - The id of the bundle to add
* @param assets - A record of the asset or assets that will be chosen from when loading via the specified key
*/
addBundle(bundleId: string, assets: AssetsBundle["assets"]): void;
/**
* Tells the resolver what keys are associated with witch asset.
* The most important thing the resolver does
* @example
* // Single key, single asset:
* resolver.add({alias: 'foo', src: 'bar.png');
* resolver.resolveUrl('foo') // => 'bar.png'
*
* // Multiple keys, single asset:
* resolver.add({alias: ['foo', 'boo'], src: 'bar.png'});
* resolver.resolveUrl('foo') // => 'bar.png'
* resolver.resolveUrl('boo') // => 'bar.png'
*
* // Multiple keys, multiple assets:
* resolver.add({alias: ['foo', 'boo'], src: ['bar.png', 'bar.webp']});
* resolver.resolveUrl('foo') // => 'bar.png'
*
* // Add custom data attached to the resolver
* Resolver.add({
* alias: 'bunnyBooBooSmooth',
* src: 'bunny{png,webp}',
* data: { scaleMode:SCALE_MODES.NEAREST }, // Base texture options
* });
*
* resolver.resolve('bunnyBooBooSmooth') // => { src: 'bunny.png', data: { scaleMode: SCALE_MODES.NEAREST } }
* @param aliases - the UnresolvedAsset or array of UnresolvedAssets to add to the resolver
*/
add(aliases: ArrayOr<UnresolvedAsset>): void;
/**
* If the resolver has had a manifest set via setManifest, this will return the assets urls for
* a given bundleId or bundleIds.
* @example
* // 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',
* },
* ],
* },
* ]
* };
*
* resolver.setManifest(manifest);
* const resolved = resolver.resolveBundle('load-screen');
* @param bundleIds - The bundle ids to resolve
* @returns All the bundles assets or a hash of assets for each bundle specified
*/
resolveBundle(bundleIds: ArrayOr<string>): Record<string, ResolvedAsset> | Record<string, Record<string, ResolvedAsset>>;
/**
* Does exactly what resolve does, but returns just the URL rather than the whole asset object
* @param key - The key or keys to resolve
* @returns - The URLs associated with the key(s)
*/
resolveUrl(key: ArrayOr<string>): string | Record<string, string>;
/**
* Resolves each key in the list to an asset object.
* Another key function of the resolver! After adding all the various key/asset pairs. this will run the logic
* of finding which asset to return based on any preferences set using the `prefer` function
* by default the same key passed in will be returned if nothing is matched by the resolver.
* @example
* resolver.add('boo', 'bunny.png');
*
* resolver.resolve('boo') // => { src: 'bunny.png' }
*
* // Will return the same string as no key was added for this value..
* resolver.resolve('another-thing.png') // => { src: 'another-thing.png' }
* @param keys - key or keys to resolve
* @returns - the resolve asset or a hash of resolve assets for each key specified
*/
resolve(keys: string): ResolvedAsset;
resolve(keys: string[]): Record<string, ResolvedAsset>;
/**
* Checks if an asset with a given key exists in the resolver
* @param key - The key of the asset
*/
hasKey(key: string): boolean;
/**
* Checks if a bundle with the given key exists in the resolver
* @param key - The key of the bundle
*/
hasBundle(key: string): boolean;
/**
* Internal function for figuring out what prefer criteria an asset should use.
* @param assets
*/
private _getPreferredOrder;
/**
* Appends the default url parameters to the url
* @param url - The url to append the default parameters to
* @returns - The url with the default parameters appended
*/
private _appendDefaultSearchParams;
private _buildResolvedAsset;
}
/**
* @param url
* @internal
*/
export declare function getUrlExtension(url: string): string;
/**
* Format detection is useful for detecting feature support on the current platform.
* @category assets
* @advanced
*/
export interface FormatDetectionParser {
/** Should be ExtensionType.DetectionParser */
extension?: ExtensionMetadata;
/** Browser/platform feature detection supported if return true */
test: () => Promise<boolean>;
/**
* Add formats (file extensions) to the existing list of formats.
* Return an new array with added formats, do not mutate the formats argument.
* @returns {Promise<string[]>} - Promise that resolves to the new formats array.
*/
add: (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.
* @returns {Promise<string[]>} - Promise that resolves to the new formats array.
*/
remove: (formats: string[]) => Promise<string[]>;
}
/**
* Configuration for the {@link loadSvg} plugin.
* @see loadSvg
* @category assets
* @advanced
*/
export interface LoadSVGConfig {
/**
* The crossOrigin value to use for loading the SVG as an image.
* @default 'anonymous'
*/
crossOrigin: ImageLike["crossOrigin"];
/**
* When set to `true`, loading and decoding images will happen with `new Image()`,
* @default false
*/
parseAsGraphicsContext: boolean;
}
/**
* A simple loader plugin for loading json data
* @category assets
* @advanced
*/
export declare const loadSvg: LoaderParser<Texture | GraphicsContext, TextureSourceOptions & LoadSVGConfig, LoadSVGConfig>;
/**
* Callback function for tracking asset loading progress. The function is called repeatedly
* during the loading process with a progress value between 0.0 and 1.0.
* @param progress - The loading progress from 0.0 (started) to 1.0 (complete)
* @returns void
* @example
* ```ts
* // Basic progress logging
* const onProgress = (progress: number) => {
* console.log(`Loading: ${Math.round(progress * 100)}%`);
* };
*
* // Update loading bar
* const onProgress = (progress: number) => {
* loadingBar.width = progress * 100;
* loadingText.text = `${Math.round(progress * 100)}%`;
* };
*
* // Load assets with progress tracking
* await Assets.load(['sprite1.png', 'sprite2.png'], onProgress);
*
* // Load bundle with progress tracking
* await Assets.loadBundle('levelAssets', (progress) => {
* // Progress is normalized (0.0 - 1.0)
* updateLoadingScreen(progress);
* });
* ```
* > [!IMPORTANT] Do not rely on the progress callback to determine when all assets are loaded.
* > Use the returned promise from `Assets.load()` or `Assets.loadBundle()` to know when loading is complete.
* @category assets
* @standard
*/
export type ProgressCallback = (progress: number) => void;
/**
* Extensible preferences that can be used, for instance, when configuring loaders.
* @since 7.2.0
* @advanced
* @category assets
*/
export interface AssetsPreferences extends LoadTextureConfig, LoadSVGConfig, PixiMixins.AssetsPreferences {
}
/**
* Options for initializing the Assets class. These options configure how assets are loaded,
* resolved, and managed in your PixiJS application.
* @category assets
* @standard
*/
export interface AssetInitOptions {
/**
* Base path prepended to all asset URLs. Useful for CDN hosting.
* @example
* ```ts
* await Assets.init({
* basePath: 'https://my-cdn.com/assets/'
* });
*
* // Now you can load assets like this:
* // Will load from: https://my-cdn.com/assets/images/sprite.png
* const texture = await Assets.load('images/sprite.png');
* ```
*/
basePath?: string;
/**
* URL parameters to append to all asset URLs.
* Useful for cache-busting or version control.
* @example
* ```ts
* // As a string
* await Assets.init({
* defaultSearchParams: 'version=1.0.0'
* });
*
* // As an object
* await Assets.init({
* defaultSearchParams: {
* version: '1.0.0',
* t: Date.now()
* }
* });
* ```
* @advanced
*/
defaultSearchParams?: string | Record<string, any>;
/**
* A manifest defining all your application's assets.
* Can be a URL to a JSON file or a manifest object.
* @example
* ```ts
* // Using a manifest object
* await Assets.init({
* manifest: {
* bundles: [{
* name: 'game-screen',
* assets: [
* {
* alias: 'hero',
* src: 'hero.{png,webp}'
* },
* {
* alias: 'map',
* src: 'map.json'
* }
* ]
* }]
* }
* });
*
* // Using a URL to manifest
* await Assets.init({
* manifest: 'assets/manifest.json'
* });
*
* // loading a bundle from the manifest
* await Assets.loadBundle('game-screen');
*
* // load individual assets from the manifest
* const heroTexture = await Assets.load('hero');
* ```
*/
manifest?: string | AssetsManifest;
/**
* Configure texture loading preferences.
* Useful for optimizing asset delivery based on device capabilities.
* @example
* ```ts
* await Assets.init({
* texturePreference: {
* // Prefer high-res textures on retina displays
* resolution: window.devicePixelRatio,
*
* // Prefer modern formats, fallback to traditional
* format: ['avif', 'webp', 'png']
* }
* });
* ```
*/
texturePreference?: {
/** Preferred texture resolution(s). Can be a single number or array of resolutions in order of preference. */
resolution?: number | number[];
/** Preferred texture formats in order of preference. Default: ['avif', 'webp', 'png', 'jpg', 'jpeg'] */
format?: ArrayOr<string>;
};
/**
* Skip browser format detection for faster initialization.
* Only use if you know exactly what formats your target browsers support.
* @example
* ```ts
* await Assets.init({
* skipDetections: true,
* texturePreference: {
* format: ['webp', 'png'] // Must explicitly set formats
* }
* });
* ```
* @advanced
*/
skipDetections?: boolean;
/**
* Override how bundle IDs are generated and resolved.
*
* This allows you to customize how assets are grouped and accessed via bundles and allow for
* multiple bundles to share the same asset keys.
* @advanced
* @example
* ```ts
* const manifest = {
* bundles: [
* {
* name: 'bunny1',
* assets: [
* {
* alias: ['character', 'character2'],
* src: 'textures/bunny.png',
* },
* ],
* },
* {
* name: 'bunny2',
* assets: [
* {
* alias: ['character', 'character2'],
* src: 'textures/bunny-2.png',
* },
* ],
* },
* ]
* };
*
* const bundleIdentifier: BundleIdentifierOptions = {
* connector: ':',
* };
*
* await Assets.init({ manifest, basePath, bundleIdentifier });
*
* const resources = await Assets.loadBundle('bunny1');
* const resources2 = await Assets.loadBundle('bunny2');
*
* console.log(resources.character === resources2.character); // false
* ```
*/
bundleIdentifier?: BundleIdentifierOptions;
/**
* Optional preferences for asset loading behavior.
* @example
* ```ts
* await Assets.init({
* preferences: {
* crossOrigin: 'anonymous',
* parseAsGraphicsContext: false
* }
* });
* ```
*/
preferences?: Partial<AssetsPreferences>;
/**
* Options for defining the loading behavior of assets.
* @example
* ```ts
* await Assets.init({
* loadOptions: {
* onProgress: (progress) => console.log(`Loading: ${Math.round(progress * 100)}%`),
* onError: (error, asset) => console.error(`Error loading ${asset.src}: ${error.message}`),
* strategy: 'retry',
* retryCount: 5,
* retryDelay: 500,
* }
* });
* ```
* @remarks
* - `onProgress` callback receives values from 0.0 to 1.0
* - `onError` callback is invoked for individual asset load failures
* - `strategy` can be 'throw' (default), 'retry', or 'skip'
* - `retryCount` sets how many times to retry failed assets (default 3)
* - `retryDelay` sets the delay between retries in milliseconds (default 250ms)
* @see {@link LoadOptions} For all available load options
*/
loadOptions?: Partial<LoadOptions>;
}
/** @internal */
export declare class AssetsClass {
/**
* The URL resolver for assets. Maps various asset keys and URLs to their final loadable form.
* @advanced
*/
resolver: Resolver;
/**
* The loader responsible for loading all assets. Handles different file types
* and transformations.
* @advanced
*/
loader: Loader;
/**
* The global cache for all loaded assets. Manages storage and retrieval of
* processed assets.
* @example
* ```ts
* // Check if an asset is cached
* if (Assets.cache.has('myTexture')) {
* const texture = Assets.cache.get('myTexture');
* }
* ```
* @see {@link Cache} For detailed cache documentation
*/
cache: typeof Cache$1;
/** takes care of loading assets in the background */
private readonly _backgroundLoader;
private readonly _detections;
private _initialized;
constructor();
/**
* Initializes the Assets class with configuration options. While not required,
* calling this before loading assets is recommended to set up default behaviors.
* @param options - Configuration options for the Assets system
* @example
* ```ts
* // Basic initialization (optional as Assets.load will call this automatically)
* await Assets.init();
*
* // With CDN configuration
* await Assets.init({
* basePath: 'https://my-cdn.com/assets/',
* defaultSearchParams: { version: '1.0.0' }
* });
*
* // With manifest and preferences
* await Assets.init({
* manifest: {
* bundles: [{
* name: 'game-screen',
* assets: [
* {
* alias: 'hero',
* src: 'hero.{png,webp}',
* data: { scaleMode: SCALE_MODES.NEAREST }
* },
* {
* alias: 'map',
* src: 'map.json'
* }
* ]
* }]
* },
* // Optimize for device capabilities
* texturePreference: {
* resolution: window.devicePixelRatio,
* format: ['webp', 'png']
* },
* // Set global preferences
* preferences: {
* crossOrigin: 'anonymous',
* }
* });
*
* // Load assets after initialization
* const heroTexture = await Assets.load('hero');
* ```
* @remarks
* - Can be called only once; subsequent calls will be ignored with a warning
* - Format detection runs automatically unless `skipDetections` is true
* - The manifest can be a URL to a JSON file or an inline object
* @see {@link AssetInitOptions} For all available initialization options
* @see {@link AssetsManifest} For manifest format details
*/
init(options?: AssetInitOptions): Promise<void>;
/**
* Registers assets with the Assets resolver. This method maps keys (aliases) to asset sources,
* allowing you to load assets using friendly names instead of direct URLs.
* @param assets - The unresolved assets to add to the resolver
* @example
* ```ts
* // Basic usage - single asset
* Assets.add({
* alias: 'myTexture',
* src: 'assets/texture.png'
* });
* const texture = await Assets.load('myTexture');
*
* // Multiple aliases for the same asset
* Assets.add({
* alias: ['hero', 'player'],
* src: 'hero.png'
* });
* const hero1 = await Assets.load('hero');
* const hero2 = await Assets.load('player'); // Same texture
*
* // Multiple format support
* Assets.add({
* alias: 'character',
* src: 'character.{webp,png}' // Will choose best format
* });
* Assets.add({
* alias: 'character',
* src: ['character.webp', 'character.png'], // Explicitly specify formats
* });
*
* // With texture options
* Assets.add({
* alias: 'sprite',
* src: 'sprite.png',
* data: { scaleMode: 'nearest' }
* });
*
* // Multiple assets at once
* Assets.add([
* { alias: 'bg', src: 'background.png' },
* { alias: 'music', src: 'music.mp3' },
* { alias: 'spritesheet', src: 'sheet.json', data: { ignoreMultiPack: false } }
* ]);
* ```
* @remarks
* - Assets are resolved when loaded, not when added
* - Multiple formats use the best available format for the browser
* - Adding with same alias overwrites previous definition
* - The `data` property is passed to the asset loader
* @see {@link Resolver} For details on asset resolution
* @see {@link LoaderParser} For asset-specific data options
* @advanced
*/
add(assets: (ArrayOr<UnresolvedAsset>)): void;
/**
* Loads one or more assets and returns a promise that resolves with the loaded content.
* Assets are cached, so subsequent loads will return the same instance of the asset without re-fetching.
* @param urls - Single URL/alias or array of URLs/aliases to load
* @param onProgress - Optional callback for load progress (0.0 to 1.0)
* @returns Promise that resolves with loaded asset(s)
* @example
* ```ts
* // Load a single asset
* const texture = await Assets.load('images/sprite.png');
*
* // Load using an alias
* const heroTexture = await Assets.load({ alias: 'hero', src: 'images/hero.png' });
*
* // Load multiple assets
* const assets = await Assets.load([
* 'images/background.png',
* 'images/character.png',
* 'fonts/game.fnt'
* ]);
* console.log(assets['images/background.png']); // Access by URL
*
* // Load with progress tracking
* const textures = await Assets.load(['sprite1.png', 'sprite2.png'],
* (progress) => console.log(`Loading: ${Math.round(progress * 100)}%`)
* );
*
* // Load with format preference
* const characterTexture = await Assets.load({
* alias: 'character',
* src: 'character.{webp,png}' // Will choose best format
* });
*
* // Load with custom options
* const spriteTexture = await Assets.load({
* alias: 'sprite',
* src: 'sprite.png',
* data: {
* scaleMode: SCALE_MODES.NEAREST,
* mipmap: MIPMAP_MODES.ON
* }
* });
*
* // Load with a specific loader, can be useful if your asset does not have an extension
* const image = await Assets.load({
* alias: 'imageWithoutExtension',
* src: 'images/imageWithoutExtension',
* parser: 'texture' // Use the JSON loader
* });
* ```
* @remarks
* - Assets are cached automatically to prevent duplicate loading
* - URLs are resolved to the best format for the current browser
* - Asset types are detected automatically based on file extension
* - Progress callback receives values from 0.0 to 1.0
* - You can define with loader to use for an asset by specifying the `parser` property, which is useful for assets that do not have a file extension.
* @throws {Error} If the asset cannot be loaded or parsed
* @see {@link Assets.add} For registering assets with aliases
* @see {@link Assets.backgroundLoad} For loading assets in the background
* @see {@link Assets.unload} For releasing loaded assets
*/
load<T = any>(urls: string | UnresolvedAsset, onProgress?: ProgressCallback | LoadOptions): Promise<T>;
load<T = any>(urls: string[] | UnresolvedAsset[], onProgress?: ProgressCallback | LoadOptions): Promise<Record<string, T>>;
/**
* Registers a bundle of assets that can be loaded as a group. Bundles are useful for organizing
* assets into logical groups, such as game levels or UI screens.
* @param bundleId - Unique identifier for the bundle
* @param assets - Assets to include in the bundle
* @example
* ```ts
* // Add a bundle using array format
* Assets.addBundle('animals', [
* { alias: 'bunny', src: 'bunny.png' },
* { alias: 'chicken', src: 'chicken.png' },
* { alias: 'thumper', src: 'thumper.png' },
* ]);
*
* // Add a bundle using object format
* Assets.addBundle('animals', {
* bunny: 'bunny.png',
* chicken: 'chicken.png',
* thumper: 'thumper.png',
* });
*
* // Add a bundle with advanced options
* Assets.addBundle('ui', [
* {
* alias: 'button',
* src: 'button.{webp,png}',
* data: { scaleMode: 'nearest' }
* },
* {
* alias: ['logo', 'brand'], // Multiple aliases
* src: 'logo.svg',
* data: { resolution: 2 }
* }
* ]);
*
* // Load the bundle
* await Assets.loadBundle('animals');
*
* // Use the loaded assets
* const bunny = Sprite.from('bunny');
* const chicken = Sprite.from('chicken');
* ```
* @remarks
* - Bundle IDs must be unique
* - Assets in bundles are not loaded until `loadBundle` is called
* - Bundles can be background loaded using `backgroundLoadBundle`
* - Assets in bundles can be loaded individually using their aliases
* @see {@link Assets.loadBundle} For loading bundles
* @see {@link Assets.backgroundLoadBundle} For background loading bundles
* @see {@link Assets.unloadBundle} For unloading bundles
* @see {@link AssetsManifest} For manifest format details
*/
addBundle(bundleId: string, assets: AssetsBundle["assets"]): void;
/**
* Loads a bundle or multiple bundles of assets. Bundles are collections of related assets
* that can be loaded together.
* @param bundleIds - Single bundle ID or array of bundle IDs to load
* @param onProgress - Optional callback for load progress (0.0 to 1.0)
* @returns Promise that resolves with the loaded bundle assets
* @example
* ```ts
* // Define bundles in your manifest
* const manifest = {
* bundles: [
* {
* name: 'load-screen',
* assets: [
* {
* alias: 'background',
* src: 'sunset.png',
* },
* {
* alias: 'bar',
* src: 'load-bar.{png,webp}', // use an array of individual assets
* },
* ],
* },
* {
* name: 'game-screen',
* assets: [
* {
* alias: 'character',
* src: 'robot.png',
* },
* {
* alias: 'enemy',
* src: 'bad-guy.png',
* },
* ],
* },
* ]
* };
*
* // Initialize with manifest
* await Assets.init({ manifest });
*
* // Or add bundles programmatically
* Assets.addBundle('load-screen', [...]);
* Assets.loadBundle('load-screen');
*
* // Load a single bundle
* await Assets.loadBundle('load-screen');
* const bg = Sprite.from('background'); // Uses alias from bundle
*
* // Load multiple bundles
* await Assets.loadBundle([
* 'load-screen',
* 'game-screen'
* ]);
*
* // Load with progress tracking
* await Assets.loadBundle('game-screen', (progress) => {
* console.log(`Loading: ${Math.round(progress * 100)}%`);
* });
* ```
* @remarks
* - Bundle assets are cached automatically
* - Bundles can be pre-loaded using `backgroundLoadBundle`
* - Assets in bundles can be accessed by their aliases
* - Progress callback receives values from 0.0 to 1.0
* @throws {Error} If the bundle ID doesn't exist in the manifest
* @see {@link Assets.addBundle} For adding bundles programmatically
* @see {@link Assets.backgroundLoadBundle} For background loading bundles
* @see {@link Assets.unloadBundle} For unloading bundles
* @see {@link AssetsManifest} For manifest format details
*/
loadBundle(bundleIds: ArrayOr<string>, onProgress?: ProgressCallback): Promise<any>;
/**
* Initiates background loading of assets. This allows assets to be loaded passively while other operations
* continue, making them instantly available when needed later.
*
* Background loading is useful for:
* - Preloading game levels while in a menu
* - Loading non-critical assets during gameplay
* - Reducing visible loading screens
* @param urls - Single URL/alias or array of URLs/aliases to load in the background
* @example
* ```ts
* // Basic background loading
* Assets.backgroundLoad('images/level2-assets.png');
*
* // Background load multiple assets
* Assets.backgroundLoad([
* 'images/sprite1.png',
* 'images/sprite2.png',
* 'images/background.png'
* ]);
*
* // Later, when you need the assets
* const textures = await Assets.load([
* 'images/sprite1.png',
* 'images/sprite2.png'
* ]); // Resolves immediately if background loading completed
* ```
* @remarks
* - Background loading happens one asset at a time to avoid blocking the main thread
* - Loading can be interrupted safely by calling `Assets.load()`
* - Assets are cached as they complete loading
* - No progress tracking is available for background loading
*/
backgroundLoad(urls: ArrayOr<string>): Promise<void>;
/**
* Initiates background loading of asset bundles. Similar to backgroundLoad but works with
* predefined bundles of assets.
*
* Perfect for:
* - Preloading level bundles during gameplay
* - Loading UI assets during splash screens
* - Preparing assets for upcoming game states
* @param bundleIds - Single bundle ID or array of bundle IDs to load in the background
* @example
* ```ts
* // Define bundles in your manifest
* await Assets.init({
* manifest: {
* bundles: [
* {
* name: 'home',
* assets: [
* {
* alias: 'background',
* src: 'images/home-bg.png',
* },
* {
* alias: 'logo',
* src: 'images/logo.png',
* }
* ]
* },
* {
* name: 'level-1',
* assets: [
* {
* alias: 'background',
* src: 'images/level1/bg.png',
* },
* {
* alias: 'sprites',
* src: 'images/level1/sprites.json'
* }
* ]
* }]
* }
* });
*
* // Load the home screen assets right away
* await Assets.loadBundle('home');
* showHomeScreen();
*
* // Start background loading while showing home screen
* Assets.backgroundLoadBundle('level-1');
*
* // When player starts level, load completes faster
* await Assets.loadBundle('level-1');
* hideHomeScreen();
* startLevel();
* ```
* @remarks
* - Bundle assets are loaded one at a time
* - Loading can be interrupted safely by calling `Assets.loadBundle()`
* - Assets are cached as they complete loading
* - Requires bundles to be registered via manifest or `addBundle`
* @see {@link Assets.addBundle} For adding bundles programmatically
* @see {@link Assets.loadBundle} For immediate bundle loading
* @see {@link AssetsManifest} For manifest format details
*/
backgroundLoadBundle(bundleIds: ArrayOr<string>): Promise<void>;
/**
* Only intended for development purposes.
* This will wipe the resolver and caches.
* You will need to reinitialize the Asset
* @internal
*/
reset(): void;
/**
* Instantly gets an asset already loaded from the cache. Returns undefined if the asset hasn't been loaded yet.
* @param keys - The key or keys for the assets to retrieve
* @returns The cached asset(s) or undefined if not loaded
* @example
* ```ts
* // Get a single cached asset
* const texture = Assets.get('hero');
* if (texture) {
* const sprite = new Sprite(texture);
* }
*
* // Get multiple cached assets
* const textures = Assets.get([
* 'hero',
* 'background',
* 'enemy'
* ]);
*
* // Safe pattern with loading fallback
* let texture = Assets.get('hero');
* if (!texture) {
* texture = await Assets.load('hero');
* }
*
* // Working with bundles
* await Assets.loadBundle('game-ui');
* const uiAssets = Assets.get([
* 'button',
* 'panel',
* 'icons'
* ]);
* ```
* @remarks
* - Returns undefined if asset isn't loaded
* - No automatic loading - use `Assets.load()` for that
* - Cached assets are shared instances
* - Faster than `load()` for already cached assets
*
* > [!TIP]
* > When in doubt, use `Assets.load()` instead. It will return cached
* > assets instantly if they're already loaded.
* @see {@link Assets.load} For loading assets that aren't cached
* @see {@link Assets.cache} For direct cache access
*/
get<T = any>(keys: string): T;
get<T = any>(keys: string[]): Record<string, T>;
/**
* helper function to map resolved assets back to loaded assets
* @param resolveResults - the resolve results from the resolver
* @param progressOrLoadOptions - the progress callback or load options
*/
private _mapLoadToResolve;
/**
* Unloads assets and releases them from memory. This method ensures proper cleanup of
* loaded assets when they're no longer needed.
* @param urls - Single URL/alias or array of URLs/aliases to unload
* @example
* ```ts
* // Unload a single asset
* await Assets.unload('images/sprite.png');
*
* // Unload using an alias
* await Assets.unload('hero'); // Unloads the asset registered with 'hero' alias
*
* // Unload multiple assets
* await Assets.unload([
* 'images/background.png',
* 'images/character.png',
* 'hero'
* ]);
*
* // Unload and handle creation of new instances
* await Assets.unload('hero');
* const newHero = await Assets.load('hero'); // Will load fresh from source
* ```
* @remarks
* > [!WARNING]
* > Make sure assets aren't being used before unloading:
* > - Remove sprites using the texture
* > - Clear any references to the asset
* > - Textures will be destroyed and can't be used after unloading
* @throws {Error} If the asset is not found in cache
*/
unload(urls: ArrayOr<string> | ResolvedAsset | ResolvedAsset[]): Promise<void>;
/**
* Unloads all assets in a bundle. Use this to free memory when a bundle's assets
* are no longer needed, such as when switching game levels.
* @param bundleIds - Single bundle ID or array of bundle IDs to unload
* @example
* ```ts
* // Define and load a bundle
* Assets.addBundle('level-1', {
* background: 'level1/bg.png',
* sprites: 'level1/sprites.json',
* music: 'level1/music.mp3'
* });
*
* // Load the bundle
* const level1 = await Assets.loadBundle('level-1');
*
* // Use the assets
* const background = Sprite.from(level1.background);
*
* // When done with the level, unload everything
* await Assets.unloadBundle('level-1');
* // background sprite is now invalid!
*
* // Unload multiple bundles
* await Assets.unloadBundle([
* 'level-1',
* 'level-2',
* 'ui-elements'
* ]);
* ```
* @remarks
* > [!WARNING]
* > - All assets in the bundle will be destroyed
* > - Bundle needs to be reloaded to use assets again
* > - Make sure no sprites or other objects are using the assets
* @throws {Error} If the bundle is not found
* @see {@link Assets.addBundle} For adding bundles
* @see {@link Assets.loadBundle} For loading bundles
*/
unloadBundle(bundleIds: ArrayOr<string>): Promise<void>;
private _unloadFromResolved;
/**
* Detects the supported formats for the browser, and returns an array of supported formats, respecting
* the users preferred formats order.
* @param options - the options to use when detecting formats
* @param options.preferredFormats - the preferred formats to use
* @param options.skipDetections - if we should skip the detections altogether
* @param options.detections - the detections to use
* @returns - the detected formats
*/
private _detectFormats;
/**
* All the detection parsers currently added to the Assets class.
* @advanced
*/
get detections(): FormatDetectionParser[];
/**
* Sets global preferences for asset loading behavior. This method configures how assets
* are loaded and processed across all parsers.
* @param preferences - Asset loading preferences
* @example
* ```ts
* // Basic preferences
* Assets.setPreferences({
* crossOrigin: 'anonymous',
* parseAsGraphicsContext: false
* });
* ```
* @remarks
* Preferences are applied to all compatible parsers and affect future asset loading.
* Common preferences include:
* - `crossOrigin`: CORS setting for loaded assets
* - `preferWorkers`: Whether to use web workers for loading textures
* - `preferCreateImageBitmap`: Use `createImageBitmap` for texture creation. Turning this off will use the `Image` constructor instead.
* @see {@link AssetsPreferences} For all available preferences
*/
setPreferences(preferences: Partial<AssetsPreferences>): void;
}
/**
* The global Assets class is a singleton that manages loading, caching, and unloading of all resources
* in your PixiJS application.
*
* Key responsibilities:
* - **URL Resolution**: Maps URLs/keys to browser-compatible resources
* - **Resource Loading**: Handles loading and transformation of assets
* - **Asset Caching**: Manages a global cache to prevent duplicate loads
* - **Memory Management**: Provides unloading capabilities to free memory
*
* Advanced Features:
* - **Asset Bundles**: Group and manage related assets together
* - **Background Loading**: Load assets before they're needed over time
* - **Format Detection**: Automatically select optimal asset formats
*
* Supported Asset Types:
* | Type | Extensions | Loaders |
* | ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------- |
* | Textures | `.png`, `.jpg`, `.gif`, `.webp`, `.avif`, `.svg` | {@link loadTextures}, {@link loadSvg} |
* | Video Textures | `.mp4`, `.m4v`, `.webm`, `.ogg`, `.ogv`, `.h264`, `.avi`, `.mov` | {@link loadVideoTextures} |
* | Sprite Sheets | `.json` | {@link spritesheetAsset} |
* | Bitmap Fonts | `.fnt`, `.xml`, `.txt` | {@link loadBitmapFont} |
* | Web Fonts | `.ttf`, `.otf`, `.woff`, `.woff2` | {@link loadWebFont} |
* | JSON | `.json` | {@link loadJson} |
* | Text | `.txt` | {@link loadTxt} |
* | Compressed Textures | `.basis`, `.dds`, `.ktx`, `.ktx2` | {@link loadBasis}, {@link loadDDS}, {@link loadKTX}, {@link loadKTX2} |
* > [!NOTE] Some loaders allow for custom configuration, please refer to the specific loader documentation for details.
* @example
* ```typescript
* import { Assets } from 'pixi.js';
*
* // Initialize with options (optional). You can call Assets.load directly without init.
* await Assets.init({
* // Base path for all asset URLs
* basePath: 'https://my-cdn.com/assets/',
* // Manifest object that defines all assets
* manifest: {
* bundles: [{ name: 'gameAssets', assets: [] }, ...],
* }, *
* // Preferred texture settings
* texturePreference: {
* resolution: window.devicePixelRatio,
* format: ['avif', 'webp', 'png']
* }
* });
*
* // Basic loading
* const texture = await Assets.load('images/sprite.png');
*
* // Load multiple assets
* const assets = await Assets.load([
* 'images/bg.png',
* 'images/character.png',
* 'fonts/game.fnt'
* ]);
*
* // Using aliases + multiple formats
* await Assets.load({ alias: 'hero', src: 'images/hero.{webp,png}' });
* const sprite = Sprite.from('hero'); // Uses the best available format
*
* // background loading
* Assets.backgroundLoad(['images/level1.json', 'images/level2.json']); // Loads in the background one at a time
*
* // Load a bundle of assets from the manifest
* const levelAssets = await Assets.loadBundle('gameAssets');
* // Background loading of a bundle. This will load assets in the background one at a time.
* // Can be interrupted at any time by calling Assets.loadBundle('gameAssets') again.
* Assets.backgroundLoadBundle('resultsAssets');
*
* // Memory management
* await Assets.unload('hero');
* await Assets.unloadBundle('levelOne');
* ```
* @remarks
* - Assets are cached automatically and only loaded once
* - Background loading helps eliminate loading screens
* - Format detection ensures optimal asset delivery
* - Bundle management simplifies resource organization
*
* > [!IMPORTANT]
* > When unloading assets, ensure they aren't being used elsewhere
* > in your application to prevent missing texture references.
* @see {@link AssetInitOptions} For initialization options
* @see {@link AssetsPreferences} For advanced preferences
* @see {@link BackgroundLoader} For background loading capabilities
* @see {@link AssetsManifest} For manifest-based asset management
* @see {@link Loader} For the underlying loading system
* @see {@link Cache} For the caching system
* @see {@link Resolver} For URL resolution details
* @category assets
* @class
* @standard
*/
export declare const Assets: AssetsClass;
/**
* A promise and parser pair
* @category assets
* @advanced
*/
export interface PromiseAndParser {
/** the promise that is loading the asset */
promise: Promise<any>;
/** the parser that is loading the asset */
parser: LoaderParser;
}
/**
* Options for loading assets with the Loader
* @example
* ```ts
* await Assets.load(['file1.png', 'file2.png'], {
* onProgress: (progress) => console.log(`Progress: ${progress * 100}%`),
* onError: (error, url) => console.error(`Error loading ${url}: ${error.message}`),
* strategy: 'retry', // 'throw' | 'skip' | 'retry'
* retryCount: 5, // Number of retry attempts if strategy is 'retry'
* retryDelay: 500, // Delay in ms between retries
* });
* ```
* @category assets
* @standard
*/
export interface LoadOptions {
/**
* Callback for progress updates during loading
* @param progress - A number between 0 and 1 indicating the load progress
* @example
* ```ts
* const options: LoadOptions = {
* onProgress: (progress) => {
* console.log(`Loading progress: ${progress * 100}%`);
* },
* };
* await Assets.load('image.png', options);
* ```
*/
onProgress?: (progress: number) => void;
/**
* Callback for handling errors during loading
* @param error - The error that occurred
* @param url - The URL of the asset that failed to load
* @example
* ```ts
* const options: LoadOptions = {
* onError: (error, url) => {
* console.error(`Failed to load ${url}: ${error.message}`);
* },
* };
* await Assets.load('missing-file.png', options);
* ```
*/
onError?: (error: Error, url: string | ResolvedAsset) => void;
/**
* Strategy to handle load failures
* - 'throw': Immediately throw an error and stop loading (default)
* - 'skip': Skip the failed asset and continue loading others
* - 'retry': Retry loading the asset a specified number of times
* @default 'throw'
* @example
* ```ts
* const options: LoadOptions = {
* strategy: 'skip',
* };
* await Assets.load('sometimes-fails.png', options);
* ```
*/
strategy?: "throw" | "skip" | "retry";
/**
* Number of retry attempts if strategy is 'retry'
* @default 3
* @example
* ```ts
* const options: LoadOptions = {
* strategy: 'retry',
* retryCount: 5, // Retry up to 5 times
* };
* await Assets.load('unstable-asset.png', options);
* ```
*/
retryCount?: number;
/**
* Delay in milliseconds between retry attempts
* @default 250
* @example
* ```ts
* const options: LoadOptions = {
* strategy: 'retry',
* retryDelay: 1000, // Wait 1 second between retries
* };
* await Assets.load('sometimes-fails.png', options);
* ```
*/
retryDelay?: number;
}
/**
* The Loader is responsible for loading all assets, such as images, spritesheets, audio files, etc.
* It does not do anything clever with URLs - it just loads stuff!
* Behind the scenes all things are cached using promises. This means it's impossible to load an asset more than once.
* Through the use of LoaderParsers, the loader can understand how to load any kind of file!
*
* It is not intended that this class is created by developers - its part of the Asset class
* This is the second major system of PixiJS' main Assets class
* @category assets
* @advanced
*/
export declare class Loader {
/**
* Default options for loading assets
* @example
* ```ts
* // Change default load options globally
* Loader.defaultOptions = {
* strategy: 'skip', // Change default strategy to 'skip'
* retryCount: 5, // Change default retry count to 5
* retryDelay: 500, // Change default retry delay to 500ms
* };
* ```
*/
static defaultOptions: LoadOptions;
/**
* Options for loading assets with the loader.
* These options will be used as defaults for all load calls made with this loader instance.
* They can be overridden by passing options directly to the load method.
* @example
* ```ts
* // Create a loader with custom default options
* const loader = new Loader();
* loader.loadOptions = {
* strategy: 'skip', // Default strategy to 'skip'
* retryCount: 5, // Default retry count to 5
* retryDelay: 500, // Default retry delay to 500ms
* };
*
* // This load call will use the loader's default options
* await loader.load('image1.png');
*/
loadOptions: LoadOptions;
private readonly _parsers;
private _parserHash;
private _parsersValidated;
/**
* All loader parsers registered
* @type {assets.LoaderParser[]}
*/
parsers: LoaderParser<any, any, Record<string, any>>[];
/** Cache loading promises that ae currently active */
promiseCache: Record<string, PromiseAndParser>;
/** function used for testing */
reset(): void;
/**
* Used internally to generate a promise for the asset to be loaded.
* @param url - The URL to be loaded
* @param data - any custom additional information relevant to the asset being loaded
* @returns - a promise that will resolve to an Asset for example a Texture of a JSON object
*/
private _getLoadPromiseAndParser;
/**
* Loads one or more assets using the parsers added to the Loader.
* @example
* // Single asset:
* const asset = await Loader.load('cool.png');
* console.log(asset);
*
* // Multiple assets:
* const assets = await Loader.load(['cool.png', 'cooler.png']);
* console.log(assets);
* @param assetsToLoadIn - urls that you want to load, or a single one!
* @param onProgress - For multiple asset loading only, an optional function that is called
* 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. Do not use this function
* to detect when assets are complete and available, instead use the Promise returned by this function.
*/
load<T = any>(assetsToLoadIn: string | ResolvedAsset, onProgress?: ProgressCallback | LoadOptions): Promise<T>;
load<T = any>(assetsToLoadIn: string[] | ResolvedAsset[], onProgress?: ProgressCallback | LoadOptions): Promise<Record<string, T>>;
/**
* Unloads one or more assets. Any unloaded assets will be destroyed, freeing up memory for your app.
* The parser that created the asset, will be the one that unloads it.
* @example
* // Single asset:
* const asset = await Loader.load('cool.png');
*
* await Loader.unload('cool.png');
*
* console.log(asset.destroyed); // true
* @param assetsToUnloadIn - urls that you want to unload, or a single one!
*/
unload(assetsToUnloadIn: string | string[] | ResolvedAsset | ResolvedAsset[]): Promise<void>;
/** validates our parsers, right now it only checks for name conflicts but we can add more here as required! */
private _validateParsers;
private _loadAssetWithRetry;
}
/**
* The extension priority for loader parsers.
* Helpful when managing multiple parsers that share the same extension test.
* The higher priority parsers will be checked first.
* @category assets
* @advanced
*/
export declare enum LoaderParserPriority {
/** Generic parsers: txt, json, webfonts */
Low = 0,
/** PixiJS assets with generic extensions: spritesheets, bitmapfonts */
Normal = 1,
/** Specific texture types: svg, png, ktx, dds, basis */
High = 2
}
/**
* A more verbose version of the LoaderParser, allowing you to set the loaded, parsed, and unloaded asset separately
* @category assets
* @advanced
*/
export interface LoaderParserAdvanced<ASSET = any, PARSED_ASSET = ASSET, UNLOAD_ASSET = ASSET, META_DATA = any, CONFIG = Record<string, any>> {
/** Should be ExtensionType.LoaderParser */
extension?: ExtensionMetadata;
/** A config to adjust the parser */
config?: CONFIG;
/**
* @deprecated Use `id` instead.
*/
name?: string;
/** The name of the parser (this can be used when specifying parser in a ResolvedAsset) */
id: string;
/**
* 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!
* @param url - The URL to test
* @param resolvedAsset - Any custom additional information relevant to the asset being loaded
* @param loader - The loader instance
*/
test?: (url: string, resolvedAsset?: ResolvedAsset<META_DATA>, loader?: Loader) => boolean;
/**
* This is the promise that loads the URL provided
* resolves with a loaded asset if returned by the parser.
* @param url - The URL to load
* @param resolvedAsset - Any custom additional information relevant to the asset being loaded
* @param loader - The loader instance
*/
load?: <T>(url: string, resolvedAsset?: ResolvedAsset<META_DATA>, loader?: Loader) => Promise<ASSET | T>;
/**
* 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
* @param asset - The loaded asset data
* @param resolvedAsset - Any custom additional information relevant to the asset being loaded
* @param loader - The loader instance
*/
testParse?: (asset: ASSET, resolvedAsset?: ResolvedAsset<META_DATA>, loader?: Loader) => Promise<boolean>;
/**
* Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
* @param asset - The loaded asset data
* @param resolvedAsset - Any custom additional information relevant to the asset being loaded
* @param loader - The loader instance
*/
parse?: <T>(asset: ASSET, resolvedAsset?: ResolvedAsset<META_DATA>, loader?: Loader) => Promise<PARSED_ASSET | T>;
/**
* 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
* @param asset - The asset to unload/destroy
* @param resolvedAsset - Any custom additional information relevant to the asset being loaded
* @param loader - The loader instance
*/
unload?: (asset: UNLOAD_ASSET, resolvedAsset?: ResolvedAsset<META_DATA>, loader?: Loader) => Promise<void> | void;
}
/**
* 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
*
* <br/>
* Some loaders may only be used for parsing, some only for loading, and some for both!
* @category assets
* @advanced
*/
export interface LoaderParser<ASSET = any, META_DATA = any, CONFIG = Record<string, any>> extends LoaderParserAdvanced<ASSET, ASSET, ASSET, META_DATA, CONFIG> {
}
/**
* The layout data for a bitmap text.
* This contains the width, height, scale, offsetY and lines of text.
* Each line contains its width, character positions, characters, space width and spaces index.
* @category text
* @internal
*/
export interface BitmapTextLayoutData {
width: number;
height: number;
scale: number;
offsetY: number;
lines: {
width: number;
charPositions: number[];
chars: string[];
spaceWidth: number;
spacesIndex: number[];
}[];
}
/**
* @param chars
* @param style
* @param font
* @param trimEnd
* @internal
*/
export declare function getBitmapTextLayout(chars: string[], style: TextStyle, font: AbstractBitmapFont<any>, trimEnd: boolean): BitmapTextLayoutData;
/**
* The options for installing a new BitmapFont. Once installed, the font will be available
* for use in BitmapText objects through the fontFamily property of TextStyle.
* @example
* ```ts
* import { BitmapFont, BitmapText } from 'pixi.js';
*
* // Basic font installation
* BitmapFont.install({
* name: 'BasicFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: '#ffffff'
* }
* });
*
* // Advanced font installation
* BitmapFont.install({
* name: 'AdvancedFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: '#ff0000',
* stroke: { color: '#000000', width: 2 }
* },
* // Include specific character ranges
* chars: [
* ['a', 'z'], // lowercase letters
* ['A', 'Z'], // uppercase letters
* ['0', '9'], // numbers
* '!@#$%^&*()_+-=[]{}' // symbols
* ],
* resolution: 2, // High-DPI support
* padding: 4, // Glyph padding
* skipKerning: false, // Enable kerning
* textureStyle: {
* scaleMode: 'linear',
* }
* });
*
* // Using the installed font
* const text = new BitmapText({
* text: 'Hello World',
* style: {
* fontFamily: 'AdvancedFont',
* fontSize: 48
* }
* });
* ```
* @category text
* @standard
*/
export interface BitmapFontInstallOptions {
/**
* The name of the font. This will be used as the fontFamily in text styles to access this font.
* Must be unique across all installed bitmap fonts.
* @example
* ```ts
* BitmapFont.install({
* name: 'MyCustomFont',
* style: { fontFamily: 'Arial' }
* });
* ```
*/
name?: string;
/**
* Characters included in the font set. You can specify individual characters or ranges.
* Don't forget to include spaces ' ' in your character set!
* @default BitmapFont.ALPHANUMERIC
* @example
* ```ts
* // Different ways to specify characters
* BitmapFont.install({
* name: 'RangeFont',
* chars: [
* ['a', 'z'], // Range of characters
* '0123456789', // String of characters
* [['0', '9'], ['A', 'Z']] // Multiple ranges
* ]
* });
* ```
*/
chars?: string | (string | string[])[];
/**
* Render resolution for glyphs. Higher values create sharper text at the cost of memory.
* Useful for supporting high-DPI displays.
* @default 1
* @example
* ```ts
* BitmapFont.install({
* name: 'HiDPIFont',
* resolution: window.devicePixelRatio || 2
* });
* ```
*/
resolution?: number;
/**
* Padding between glyphs on texture atlas. Balances visual quality with texture space.
* - Lower values: More compact, but may have visual artifacts
* - Higher values: Better quality, but uses more texture space
* @default 4
* @example
* ```ts
* BitmapFont.install({
* name: 'PaddedFont',
* padding: 8 // More padding for better quality
* });
* ```
*/
padding?: number;
/**
* Skip generation of kerning information for the BitmapFont.
* - true: Faster generation, but text may have inconsistent spacing
* - false: Better text appearance, but slower generation
* @default false
* @example
* ```ts
* BitmapFont.install({
* name: 'FastFont',
* skipKerning: true // Prioritize performance
* });
* ```
*/
skipKerning?: boolean;
/**
* Style options to render the BitmapFont with.
* Supports all TextStyle properties including fill, stroke, and shadow effects.
* @example
* ```ts
* BitmapFont.install({
* name: 'StyledFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: 'white',
* stroke: { color: '#000000', width: 2 },
* dropShadow: {
* color: '#000000',
* blur: 2,
* distance: 3
* }
* }
* });
* ```
*/
style?: TextStyle | TextStyleOptions;
/**
* Optional texture style to use when creating the font textures.
* Controls how the font textures are rendered and filtered.
* @example
* ```ts
* BitmapFont.install({
* name: 'CrispFont',
* textureStyle: {
* scaleMode: 'nearest',
* }
* });
* ```
*/
textureStyle?: TextureStyle | TextureStyleOptions;
/**
* Whether to allow overriding the fill color with a tint at runtime.
*
* When enabled, the font can be dynamically tinted using the `tint` property of BitmapText,
* allowing a single font to display multiple colors without creating separate font textures.
* This is memory efficient but requires the font to be rendered with white fill color.
*
* When disabled, the fill color is permanently baked into the font texture. This allows
* any fill color but prevents runtime tinting - each color variation requires a separate font.
* @default false (automatically determined based on style)
*
* **Requirements for tinting:**
* - Fill color must be white (`0xFFFFFF` or `'#ffffff'`)
* - No stroke effects
* - No drop shadows (or only black shadows)
* - No gradient or pattern fills
*
* **Performance considerations:**
* - ✅ Enabled: One font texture, multiple colors via tinting (memory efficient)
* - ❌ Disabled: Separate font texture per color (higher memory usage)
* @example
* ```ts
* // Correct usage - white fill with tinting enabled
* BitmapFont.install({
* name: 'TintableFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xFFFFFF // Must be white for tinting
* },
* dynamicFill: true
* });
*
* // Use the font with different colors via tinting
* const redText = new BitmapText({
* text: 'Red Text',
* style: { fontFamily: 'TintableFont', fill: 'red }, // Red tint
* });
*
* const blueText = new BitmapText({
* text: 'Blue Text',
* style: { fontFamily: 'TintableFont', fill: 'blue' }, // Blue tint
* });
* ```
* @example
* ```ts
* // Incorrect usage - colored fill with tinting enabled
* BitmapFont.install({
* name: 'BadTintFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xFF0000 // ❌ Red fill won't tint properly
* },
* dynamicFill: true // ❌ Will not work as expected
* });
* ```
* @example
* ```ts
* // Alternative - baked colors (no tinting)
* BitmapFont.install({
* name: 'BakedColorFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xFF0000, // Any color works
* stroke: { color: 0x000000, width: 2 } // Strokes allowed
* },
* dynamicFill: false // Color is baked in
* });
* ```
*/
dynamicFill?: boolean;
}
declare class BitmapFontManagerClass {
/**
* This character set includes all the letters in the alphabet (both lower- and upper- case).
* @type {string[][]}
* @example
* BitmapFont.from('ExampleFont', style, { chars: BitmapFont.ALPHA })
*/
readonly ALPHA: (string | string[])[];
/**
* This character set includes all decimal digits (from 0 to 9).
* @type {string[][]}
* @example
* BitmapFont.from('ExampleFont', style, { chars: BitmapFont.NUMERIC })
*/
readonly NUMERIC: string[][];
/**
* This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`.
* @type {string[][]}
*/
readonly ALPHANUMERIC: (string | string[])[];
/**
* This character set consists of all the ASCII table.
* @type {string[][]}
* @see http://www.asciitable.com/
*/
readonly ASCII: string[][];
/** Default options for installing a new BitmapFont. */
defaultOptions: Omit<BitmapFontInstallOptions, "style">;
/** Cache for measured text layouts to avoid recalculating them multiple times. */
readonly measureCache: import("tiny-lru").LRU<BitmapTextLayoutData>;
/**
* Get a font for the specified text and style.
* @param text - The text to get the font for
* @param style - The style to use
*/
getFont(text: string, style: TextStyle): BitmapFont;
/**
* Get the layout of a text for the specified style.
* @param text - The text to get the layout for
* @param style - The style to use
* @param trimEnd - Whether to ignore whitespaces at the end of each line
*/
getLayout(text: string, style: TextStyle, trimEnd?: boolean): BitmapTextLayoutData;
/**
* Measure the text using the specified style.
* @param text - The text to measure
* @param style - The style to use
* @param trimEnd - Whether to ignore whitespaces at the end of each line
*/
measureText(text: string, style: TextStyle, trimEnd?: boolean): {
width: number;
height: number;
scale: number;
offsetY: number;
};
/**
* Generates a bitmap-font for the given style and character set
* @param options - Setup options for font generation.
* @returns Font generated by style options.
* @example
* import { BitmapFontManager, BitmapText } from 'pixi.js';
*
* BitmapFontManager.install('TitleFont', {
* fontFamily: 'Arial',
* fontSize: 12,
* strokeThickness: 2,
* fill: 'purple',
* });
*
* const title = new BitmapText({ text: 'This is the title', fontFamily: 'TitleFont' });
*/
install(options: BitmapFontInstallOptions): BitmapFont;
/** @deprecated since 7.0.0 */
install(name: string, style?: TextStyle | TextStyleOptions, options?: BitmapFontInstallOptions): BitmapFont;
/**
* Uninstalls a bitmap font from the cache.
* @param {string} name - The name of the bitmap font to uninstall.
*/
uninstall(name: string): void;
/**
* Determines if a style can use tinting instead of baking colors into the bitmap.
* Tinting is more efficient as it allows reusing the same bitmap with different colors.
* @param style - The text style to evaluate
* @returns true if the style can use tinting, false if colors must be baked in
* @private
*/
private _canUseTintForStyle;
}
/**
* The BitmapFontManager is a helper that exists to install and uninstall fonts
* into the cache for BitmapText objects.
* @category text
* @advanced
* @class
* @example
* import { BitmapFontManager, BitmapText } from 'pixi.js';
*
* BitmapFontManager.install({
* name: 'TitleFont',
* style: {}
* });
*
* const title = new BitmapText({ text: 'This is the title', style: { fontFamily: 'TitleFont' }});
*/
export declare const BitmapFontManager: BitmapFontManagerClass;
/**
* Options for creating a BitmapFont. Used when loading or creating bitmap fonts from existing textures and data.
* @example
* ```ts
* import { BitmapFont, Texture } from 'pixi.js';
*
* // Create a bitmap font from loaded textures and data
* const font = new BitmapFont({
* // Font data containing character metrics and layout info
* data: {
* pages: [{ id: 0, file: 'font.png' }],
* chars: {
* '65': { // 'A'
* id: 65,
* page: 0,
* x: 0,
* y: 0,
* width: 32,
* height: 32,
* xOffset: 0,
* yOffset: 0,
* xAdvance: 32,
* letter: 'A'
* }
* // ... other characters
* },
* fontSize: 32,
* lineHeight: 36,
* baseLineOffset: 26,
* fontFamily: 'MyFont',
* // Optional distance field info for MSDF/SDF fonts
* distanceField: {
* type: 'msdf',
* range: 4
* }
* },
* // Array of textures containing the font glyphs
* textures: [
* Texture.from('font.png')
* ]
* });
* ```
* @category text
* @standard
*/
export interface BitmapFontOptions {
/**
* The bitmap font data containing character metrics, layout information,
* and font properties. This includes character positions, dimensions,
* kerning data, and general font settings.
*/
data: BitmapFontData;
/**
* Array of textures containing the font glyphs. Each texture corresponds
* to a page in the font data. For simple fonts this is typically just
* one texture, but complex fonts may split glyphs across multiple textures.
*/
textures: Texture[];
}
/**
* A BitmapFont object represents a particular font face, size, and style.
* This class handles both pre-loaded bitmap fonts and dynamically generated ones.
* @example
* ```ts
* import { BitmapFont, Texture } from 'pixi.js';
*
* // Create a bitmap font from loaded textures and data
* const font = new BitmapFont({
* data: {
* pages: [{ id: 0, file: 'font.png' }],
* chars: {
* '65': { // 'A'
* id: 65,
* page: 0,
* x: 0,
* y: 0,
* width: 32,
* height: 32,
* xOffset: 0,
* yOffset: 0,
* xAdvance: 32,
* letter: 'A'
* }
* },
* fontSize: 32,
* lineHeight: 36,
* baseLineOffset: 26,
* fontFamily: 'MyFont',
* distanceField: {
* type: 'msdf',
* range: 4
* }
* },
* textures: [Texture.from('font.png')]
* });
*
* // Install a font for global use
* BitmapFont.install({
* name: 'MyCustomFont',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: '#ffffff',
* stroke: { color: '#000000', width: 2 }
* }
* });
*
* // Uninstall when no longer needed
* BitmapFont.uninstall('MyCustomFont');
* ```
* @category text
* @standard
*/
export declare class BitmapFont extends AbstractBitmapFont<BitmapFont> {
/**
* The URL from which the font was loaded, if applicable.
* This is useful for tracking font sources and reloading.
* @example
* ```ts
* console.log(font.url); // 'fonts/myFont.fnt'
* ```
*/
url?: string;
constructor(options: BitmapFontOptions, url?: string);
/** Destroys the BitmapFont object. */
destroy(): void;
/**
* Generates and installs a bitmap font with the specified options.
* The font will be cached and available for use in BitmapText objects.
* @param options - Setup options for font generation
* @returns Installed font instance
* @example
* ```ts
* // Install a basic font
* BitmapFont.install({
* name: 'Title',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: '#ffffff'
* }
* });
*
* // Install with advanced options
* BitmapFont.install({
* name: 'Custom',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: '#00ff00',
* stroke: { color: '#000000', width: 2 }
* },
* chars: [['a', 'z'], ['A', 'Z'], ['0', '9']],
* resolution: 2,
* padding: 4,
* textureStyle: {
* scaleMode: 'nearest'
* }
* });
* ```
*/
static install(options: BitmapFontInstallOptions): void;
/**
* Uninstalls a bitmap font from the cache.
* This frees up memory and resources associated with the font.
* @param name - The name of the bitmap font to uninstall
* @example
* ```ts
* // Remove a font when it's no longer needed
* BitmapFont.uninstall('MyCustomFont');
*
* // Clear multiple fonts
* ['Title', 'Heading', 'Body'].forEach(BitmapFont.uninstall);
* ```
*/
static uninstall(name: string): void;
}
/**
* simple loader plugin for loading in bitmap fonts!
* @category assets
* @internal
*/
export declare const bitmapFontCachePlugin: {
extension: {
type: ExtensionType.CacheParser;
name: string;
};
test: (asset: BitmapFont) => boolean;
getCacheableAssets(keys: string[], asset: BitmapFont): Record<string, BitmapFont>;
};
/**
* Loader plugin for loading bitmap fonts.
* It supports both XML and text formats, and can handle distance field fonts.
* @category assets
* @advanced
*/
export declare const loadBitmapFont: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
testParse(data: string): Promise<boolean>;
parse<T>(asset: string, data: ResolvedAsset, loader: Loader): Promise<BitmapFont>;
load<T_1>(url: string, _options: ResolvedAsset): Promise<string>;
unload(bitmapFont: BitmapFont, _resolvedAsset: ResolvedAsset<any>, loader: Loader): Promise<void>;
};
/** @internal */
export declare class BitmapTextGraphics extends Graphics implements GPUData {
destroy(): void;
}
/** @internal */
export declare class BitmapTextPipe implements RenderPipe<BitmapText> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "bitmapText";
};
private _renderer;
private readonly _managedBitmapTexts;
constructor(renderer: Renderer);
validateRenderable(bitmapText: BitmapText): boolean;
addRenderable(bitmapText: BitmapText, instructionSet: InstructionSet): void;
updateRenderable(bitmapText: BitmapText): void;
private _updateContext;
private _getGpuBitmapText;
initGpuText(bitmapText: BitmapText): BitmapTextGraphics;
private _updateDistanceField;
destroy(): void;
}
export interface BitmapText extends PixiMixins.BitmapText, AbstractText<TextStyle, TextStyleOptions, TextOptions, BitmapTextGraphics> {
}
/**
* A BitmapText object creates text using pre-rendered bitmap fonts.
* It supports both loaded bitmap fonts (XML/FNT) and dynamically generated ones.
*
* To split a line you can use '\n' in your text string, or use the `wordWrap` and
* `wordWrapWidth` style properties.
*
* Key Features:
* - High-performance text rendering using pre-generated textures
* - Support for both pre-loaded and dynamic bitmap fonts
* - Compatible with MSDF/SDF fonts for crisp scaling
* - Automatic font reuse and optimization
*
* Performance Benefits:
* - Faster rendering compared to Canvas/HTML text
* - Lower memory usage for repeated characters
* - More efficient text changes
* - Better batching capabilities
*
* Limitations:
* - Full character set support is impractical due to the number of chars (mainly affects CJK languages)
* - Initial font generation/loading overhead
* - Less flexible styling compared to Canvas/HTML text
* @example
* ```ts
* import { BitmapText, BitmapFont } from 'pixi.js';
*
* // Dynamic font generation
* const dynamicText = new BitmapText({
* text: 'Hello Pixi!',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* }
* });
*
* // Pre-installed font usage
* BitmapFont.install({
* name: 'myFont',
* style: {
* fontFamily: 'Arial',
* }
* });
*
* const preinstalledText = new BitmapText({
* text: 'Hello Pixi!',
* style: {
* fontFamily: 'myFont',
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* }
* });
*
* // Load and use external bitmap font, if the font supports MSDF/SDF then it will be used
* const font = await Assets.load('fonts/myFont.fnt');
*
* const loadedFontText = new BitmapText({
* text: 'Hello Pixi!',
* style: {
* fontFamily: 'myLoadedFont', // Name from .fnt file
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* }
* });
*
* // Multiline text with word wrap
* const wrappedText = new BitmapText({
* text: 'This is a long text that will wrap automatically',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* wordWrap: true,
* wordWrapWidth: 200,
* }
* });
* ```
*
* Font Types:
* 1. Pre-loaded Bitmap Fonts:
* - Load via Asset Manager (XML/FNT formats)
* - Support for MSDF/SDF fonts
* - Create using tools like https://msdf-bmfont.donmccurdy.com/
*
* 2. Dynamic Bitmap Fonts:
* - Generated at runtime from system fonts
* - Automatic font reuse and optimization
* - Smart scaling for similar font sizes
*
* Font Management:
* - Automatic font generation when needed
* - Manual pre-installation via `BitmapFont.install`
* - Smart font reuse to optimize memory
* - Scale existing fonts instead of generating new ones when possible
* @category text
* @standard
* @see {@link BitmapFont} For font installation and management
* @see {@link Text} For canvas-based text rendering
* @see {@link HTMLText} For HTML/CSS-based text rendering
*/
export declare class BitmapText extends AbstractText<TextStyle, TextStyleOptions, TextOptions, BitmapTextGraphics> implements View {
/** @internal */
readonly renderPipeId: string;
/**
* **Note:** Our docs parser struggles to properly understand the constructor signature.
* This is the correct signature.
* ```ts
* new BitmapText(options?: TextOptions);
* ```
* @param { TextOptions } options - The options of the bitmap text.
*/
constructor(options?: TextOptions);
/** @deprecated since 8.0.0 */
constructor(text?: TextString, options?: Partial<TextStyle>);
/**
* @param now - The current time in milliseconds.
* @internal
*/
_onTouch(now: number): void;
/** @private */
protected updateBounds(): void;
/**
* The resolution / device pixel ratio for text rendering.
* Unlike other text types, BitmapText resolution is managed by the BitmapFont.
* Individual resolution changes are not supported.
* @example
* ```ts
* // ❌ Incorrect: Setting resolution directly (will trigger warning)
* const text = new BitmapText({
* text: 'Hello',
* resolution: 2 // This will be ignored
* });
*
* // ✅ Correct: Set resolution when installing the font
* BitmapFont.install({
* name: 'MyFont',
* style: {
* fontFamily: 'Arial',
* },
* resolution: 2 // Resolution is set here
* });
*
* const text = new BitmapText({
* text: 'Hello',
* style: {
* fontFamily: 'MyFont' // Uses font's resolution
* }
* });
* ```
* @default 1
* @see {@link BitmapFont.install} For setting font resolution
* @throws {Warning} When attempting to change resolution directly
* @readonly
*/
set resolution(value: number);
get resolution(): number;
}
/** @internal */
export interface DynamicBitmapFontOptions {
style: TextStyle;
skipKerning?: boolean;
resolution?: number;
padding?: number;
overrideFill?: boolean;
overrideSize?: boolean;
textureSize?: number;
mipmap?: boolean;
textureStyle?: TextureStyle | TextureStyleOptions;
}
/**
* A BitmapFont that generates its glyphs dynamically.
* @category text
* @internal
*/
export declare class DynamicBitmapFont extends AbstractBitmapFont<DynamicBitmapFont> {
static defaultOptions: DynamicBitmapFontOptions;
/**
* this is a resolution modifier for the font size..
* texture resolution will also be used to scale texture according to its font size also
*/
resolution: number;
/** The pages of the font. */
readonly pages: {
canvasAndContext?: CanvasAndContext;
texture: Texture;
}[];
private readonly _padding;
private readonly _measureCache;
private _currentChars;
private _currentX;
private _currentY;
private _currentMaxCharHeight;
private _currentPageIndex;
private readonly _style;
private readonly _skipKerning;
private readonly _textureSize;
private readonly _mipmap;
private readonly _textureStyle?;
/**
* @param options - The options for the dynamic bitmap font.
*/
constructor(options: DynamicBitmapFontOptions);
ensureCharacters(chars: string): void;
/**
* @deprecated since 8.0.0
* The map of base page textures (i.e., sheets of glyphs).
*/
get pageTextures(): DynamicBitmapFont["pages"];
private _applyKerning;
private _nextPage;
private _setupContext;
private _drawGlyph;
destroy(): void;
}
/**
* Types of text objects that can be split into characters, words, and lines.
* Currently supports Text and BitmapText instances.
* @internal
*/
export type SplitableTextObject = Text$1 | BitmapText;
/**
* Contains the output elements from a text split operation.
* Provides access to the hierarchical structure of split text elements.
* @example
* ```ts
* const splitResult = Text.split(myText);
*
* // Access individual characters
* splitResult.chars.forEach(char => {
* char.alpha = 0;
* gsap.to(char, { alpha: 1, duration: 0.5 });
* });
*
* // Access words (groups of characters)
* splitResult.words.forEach(word => {
* word.scale.set(0);
* gsap.to(word.scale, { x: 1, y: 1, duration: 0.5 });
* });
*
* // Access lines (groups of words)
* splitResult.lines.forEach(line => {
* line.x = -200;
* gsap.to(line, { x: 0, duration: 0.5 });
* });
* ```
* @category text
* @standard
*/
export interface TextSplitOutput<T extends SplitableTextObject> {
/** Array of individual character Text objects */
chars: T[];
/** Array of word containers, each containing character objects */
words: Container[];
/** Array of line containers, each containing word containers */
lines: Container[];
}
/**
* Configuration options for text splitting.
* @category text
* @standard
*/
export interface AbstractSplitOptions {
/** Text content to be split */
text: string;
/** Text styling - accepts TextStyle instance or style object */
style: TextStyle | Partial<TextStyleOptions>;
/**
* Enables automatic splitting on text/style changes
* @default true
*/
autoSplit?: boolean;
/**
* Transform origin for line segments. Range: [0-1]
* @example
* ```ts
* lineAnchor: 0.5 // Center horizontally and vertically
* lineAnchor: { x: 0, y: 0.5 } // Left-center alignment
*
* ```
* @default 0
*/
lineAnchor?: number | PointData;
/**
* Transform origin for word segments. Range: [0-1]
* @example
* ```ts
* wordAnchor: { x: 1, y: 0 } // Top-right alignment
* wordAnchor: 0.5 // Center alignment
* ```
* @default 0
*/
wordAnchor?: number | PointData;
/**
* Transform origin for character segments. Range: [0-1]
* @example
* ```ts
* charAnchor: { x: 0.5, y: 1 } // Bottom-center alignment
* charAnchor: 0.5 // Center alignment
* ```
* @default 0
*/
charAnchor?: number | PointData;
}
/**
* Configuration options for SplitText, combining container properties with text splitting settings.
* @example Basic Usage
* ```ts
* const options: SplitTextOptions = {
* text: 'Hello World',
* style: { fontSize: 32, fill: 0xffffff },
* // Transform origins
* lineAnchor: 0.5, // Center each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center each char
* };
* ```
* @example Advanced Configuration
* ```ts
* const options: SplitTextOptions = {
* // Text content and style
* text: 'Multi\nLine Text',
* style: new TextStyle({
* fontSize: 24,
* fill: 'white',
* strokeThickness: 2,
* }),
*
* // Container properties
* x: 100,
* y: 100,
* alpha: 0.8,
*
* // Splitting settings
* autoSplit: true,
*
* // Transform origins (normalized 0-1)
* lineAnchor: { x: 1, y: 0 }, // Top-right
* wordAnchor: 0.5, // Center
* charAnchor: { x: 0, y: 1 }, // Bottom-left
* };
* ```
*
* Properties:
* - Container options from {@link ContainerOptions}
* - Text split options from {@link AbstractSplitOptions}
* @see {@link AbstractSplitText} For the main implementation
* @see {@link ContainerOptions} For base container properties
* @see {@link AbstractSplitOptions} For text splitting options
* @category text
* @standard
*/
export interface AbstractSplitTextOptions extends ContainerOptions, AbstractSplitOptions {
}
/**
* @experimental
* A container that splits text into individually manipulatable segments (lines, words, and characters)
* for advanced text effects and animations.
* @example Basic Usage
* ```ts
* const text = new SplitText({
* text: "Hello World",
* style: { fontSize: 24 },
* // Origin points for transformations (0-1 range)
* lineAnchor: 0.5, // Center of each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center of each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center of each character
* autoSplit: true // Auto-update segments on text/style changes
* });
* ```
*
* Features:
* - Hierarchical text splitting (lines → words → characters)
* - Independent transformation origins for each segment level
* - Automatic or manual segment updates
* - Support for both canvas text and bitmap text
* @example Animation Example
* ```ts
* // Character fade-in sequence
* text.chars.forEach((char, i) => {
* gsap.from(char, {
* alpha: 0,
* delay: i * 0.1
* });
* });
*
* // Word scale animation
* text.words.forEach((word, i) => {
* gsap.to(word.scale, {
* x: 1.2, y: 1.2,
* yoyo: true,
* repeat: -1,
* delay: i * 0.2
* });
* });
*
* // Line slide-in effect
* text.lines.forEach((line, i) => {
* gsap.from(line, {
* x: -200,
* delay: i * 0.3
* });
* });
* ```
*
* Configuration Options:
* - `text`: The string to render and segment
* - `style`: TextStyle instance or configuration object
* - `autoSplit`: Automatically update segments on changes (default: true)
* - `lineAnchor`: Transform origin for lines (default: 0)
* - `wordAnchor`: Transform origin for words (default: 0)
* - `charAnchor`: Transform origin for characters (default: 0)
*
* > [!NOTE] Anchor points are normalized (0-1):
* > - 0,0: Top-left
* > - 0.5,0.5: Center
* > - 1,1: Bottom-right
*
* > [!WARNING] Limitations
* > - Character spacing may differ slightly from standard text due to browser
* > kerning being lost when characters are separated
* @category text
* @standard
*/
export declare abstract class AbstractSplitText<T extends SplitableTextObject> extends Container {
/**
* Individual character segments of the text.
* @example
* ```ts
* // Fade in characters sequentially
* text.chars.forEach((char, i) => {
* char.alpha = 0;
* gsap.to(char, {
* alpha: 1,
* delay: i * 0.1
* });
* });
* ```
*/
chars: T[];
/**
* Word segments of the text, each containing one or more characters.
* @example
* ```ts
* // Scale words on hover
* text.words.forEach(word => {
* word.interactive = true;
* word.on('pointerover', () => {
* gsap.to(word.scale, { x: 1.2, y: 1.2 });
* });
* word.on('pointerout', () => {
* gsap.to(word.scale, { x: 1, y: 1 });
* });
* });
* ```
*/
words: Container[];
/**
* Line segments of the text, each containing one or more words.
* @example
* ```ts
* // Stagger line entrance animations
* text.lines.forEach((line, i) => {
* line.x = -200;
* gsap.to(line, {
* x: 0,
* duration: 0.5,
* delay: i * 0.2,
* ease: 'back.out'
* });
* });
* ```
*/
lines: Container[];
protected _originalText: string;
protected _lineAnchor: number | PointData;
protected _wordAnchor: number | PointData;
protected _charAnchor: number | PointData;
protected _autoSplit: boolean;
protected _style: TextStyle;
protected _dirty: boolean;
protected _canReuseChars: boolean;
constructor(config: AbstractSplitTextOptions);
protected abstract splitFn(): TextSplitOutput<T>;
/**
* Splits the text into lines, words, and characters.
* Call this manually when autoSplit is false.
* @example Manual Splitting
* ```ts
* const text = new SplitText({
* text: 'Manual Update',
* autoSplit: false
* });
*
* text.text = 'New Content';
* text.style = { fontSize: 32 };
* text.split(); // Apply changes
* ```
*/
split(): void;
get text(): string;
/**
* Gets or sets the text content.
* Setting new text triggers splitting if autoSplit is true.
* > [!NOTE] Setting this frequently can have a performance impact, especially with large texts and canvas text.
* @example Dynamic Text Updates
* ```ts
* const text = new SplitText({
* text: 'Original',
* autoSplit: true
* });
*
* // Auto-splits on change
* text.text = 'Updated Content';
*
* // Manual update
* text.autoSplit = false;
* text.text = 'Manual Update';
* text.split();
* ```
*/
set text(value: string);
private _setOrigin;
/**
* Gets or sets the transform anchor for line segments.
* The anchor point determines the center of rotation and scaling for each line.
* @example Setting Line Anchors
* ```ts
* // Center rotation/scaling
* text.lineAnchor = 0.5;
*
* // Rotate/scale from top-right corner
* text.lineAnchor = { x: 1, y: 0 };
*
* // Custom anchor point
* text.lineAnchor = {
* x: 0.2, // 20% from left
* y: 0.8 // 80% from top
* };
* ```
*/
get lineAnchor(): number | PointData;
set lineAnchor(value: number | PointData);
/**
* Gets or sets the transform anchor for word segments.
* The anchor point determines the center of rotation and scaling for each word.
* @example
* ```ts
* // Center each word
* text.wordAnchor = 0.5;
*
* // Scale from bottom-left
* text.wordAnchor = { x: 0, y: 1 };
*
* // Rotate around custom point
* text.wordAnchor = {
* x: 0.75, // 75% from left
* y: 0.5 // Middle vertically
* };
* ```
*/
get wordAnchor(): number | PointData;
set wordAnchor(value: number | PointData);
/**
* Gets or sets the transform anchor for character segments.
* The anchor point determines the center of rotation and scaling for each character.
* @example Setting Character Anchors
* ```ts
* // Center each character
* text.charAnchor = 0.5;
*
* // Rotate from top-center
* text.charAnchor = { x: 0.5, y: 0 };
*
* // Scale from bottom-right
* text.charAnchor = { x: 1, y: 1 };
* ```
* @example Animation with Anchors
* ```ts
* // Rotate characters around their centers
* text.charAnchor = 0.5;
* text.chars.forEach((char, i) => {
* gsap.to(char, {
* rotation: Math.PI * 2,
* duration: 1,
* delay: i * 0.1,
* repeat: -1
* });
* });
* ```
*/
get charAnchor(): number | PointData;
set charAnchor(value: number | PointData);
get style(): TextStyle;
/**
* The style configuration for the text.
* Can be a TextStyle instance or a configuration object.
* @example
* ```ts
* const text = new Text({
* text: 'Styled Text',
* style: {
* fontSize: 24,
* fill: 0xff1010, // Red color
* fontFamily: 'Arial',
* align: 'center', // Center alignment
* stroke: { color: '#4a1850', width: 5 }, // Purple stroke
* dropShadow: {
* color: '#000000', // Black shadow
* blur: 4, // Shadow blur
* distance: 6 // Shadow distance
* }
* }
* });
* // Update style dynamically
* text.style = {
* fontSize: 30, // Change font size
* fill: 0x00ff00, // Change color to green
* align: 'right', // Change alignment to right
* stroke: { color: '#000000', width: 2 }, // Add black stroke
* }
*/
set style(style: TextStyle | Partial<TextStyle> | TextStyleOptions);
protected onTextUpdate(): void;
/**
* Destroys the SplitText instance and all its resources.
* Cleans up all segment arrays, event listeners, and optionally the text style.
* @param options - Destroy configuration options
* @example
* ```ts
* // Clean up everything
* text.destroy({ children: true, texture: true, style: true });
*
* // Remove from parent but keep style
* text.destroy({ children: true, style: false });
* ```
*/
destroy(options?: DestroyOptions): void;
}
/**
* Configuration options for Text splitting.
* @category text
* @standard
* @interface
*/
export interface SplitOptions extends AbstractSplitOptions {
}
/**
* Configuration options for SplitText, combining container properties with text splitting settings.
* @example Basic Usage
* ```ts
* const options: SplitTextOptions = {
* text: 'Hello World',
* style: { fontSize: 32, fill: 0xffffff },
* // Transform origins
* lineAnchor: 0.5, // Center each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center each char
* };
* ```
* @example Advanced Configuration
* ```ts
* const options: SplitTextOptions = {
* // Text content and style
* text: 'Multi\nLine Text',
* style: new TextStyle({
* fontSize: 24,
* fill: 'white',
* strokeThickness: 2,
* }),
*
* // Container properties
* x: 100,
* y: 100,
* alpha: 0.8,
*
* // Splitting settings
* autoSplit: true,
*
* // Transform origins (normalized 0-1)
* lineAnchor: { x: 1, y: 0 }, // Top-right
* wordAnchor: 0.5, // Center
* charAnchor: { x: 0, y: 1 }, // Bottom-left
* };
* ```
*
* Properties:
* - Container options from {@link ContainerOptions}
* - Text splitting options from {@link SplitOptions}
* - Additional PixiJS-specific options from PixiMixins.SplitText
* @see {@link SplitText} For the main implementation
* @see {@link ContainerOptions} For base container properties
* @see {@link SplitOptions} For text splitting options
* @category text
* @standard
*/
export interface SplitTextOptions extends PixiMixins.SplitText, ContainerOptions, SplitOptions {
}
/**
* @experimental
* A container that splits text into individually manipulatable segments (lines, words, and characters)
* for advanced text effects and animations.
* Converts each segment into a separate Text object.
* @example Basic Usage
* ```ts
* const text = new SplitText({
* text: "Hello World",
* style: { fontSize: 24 },
* // Origin points for transformations (0-1 range)
* lineAnchor: 0.5, // Center of each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center of each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center of each character
* autoSplit: true // Auto-update segments on text/style changes
* });
* ```
*
* Features:
* - Hierarchical text segmentation (lines → words → characters)
* - Independent transformation origins for each segment level
* - Automatic or manual segment updates
* @example Animation Example
* ```ts
* // Character fade-in sequence
* text.chars.forEach((char, i) => {
* gsap.from(char, {
* alpha: 0,
* delay: i * 0.1
* });
* });
*
* // Word scale animation
* text.words.forEach((word, i) => {
* gsap.to(word.scale, {
* x: 1.2, y: 1.2,
* yoyo: true,
* repeat: -1,
* delay: i * 0.2
* });
* });
*
* // Line slide-in effect
* text.lines.forEach((line, i) => {
* gsap.from(line, {
* x: -200,
* delay: i * 0.3
* });
* });
* ```
*
* Configuration Options:
* - `text`: The string to render and segment
* - `style`: TextStyle instance or configuration object
* - `autoSplit`: Automatically update segments on changes (default: true)
* - `lineAnchor`: Transform origin for lines (default: 0)
* - `wordAnchor`: Transform origin for words (default: 0)
* - `charAnchor`: Transform origin for characters (default: 0)
*
* > [!NOTE] Anchor points are normalized (0-1):
* > - 0,0: Top-left
* > - 0.5,0.5: Center
* > - 1,1: Bottom-right
*
* > [!WARNING] Limitations
* > - Character spacing may differ slightly from standard text due to browser
* > kerning being lost when characters are separated
* @category text
* @standard
*/
export declare class SplitText extends AbstractSplitText<Text$1> {
/**
* Default configuration options for SplitText instances.
* @example
* ```ts
* // Override defaults globally
* SplitText.defaultOptions = {
* autoSplit: false,
* lineAnchor: 0.5, // Center alignment
* wordAnchor: { x: 0, y: 0.5 }, // Left-center
* charAnchor: { x: 0.5, y: 1 } // Bottom-center
* };
* ```
*/
static defaultOptions: Partial<SplitTextOptions>;
constructor(config: SplitTextOptions);
/**
* Creates a SplitText instance from an existing text object.
* Useful for converting standard Text or Text objects into segmented versions.
* @param text - The source text object to convert
* @param options - Additional splitting options
* @returns A new SplitText instance
* @example
* ```ts
* const text = new Text({
* text: 'Bitmap Text',
* style: { fontFamily: 'Arial' }
* });
*
* const segmented = SplitText.from(text);
*
* // with additional options
* const segmentedWithOptions = SplitText.from(text, {
* autoSplit: false,
* lineAnchor: 0.5,
* wordAnchor: { x: 0, y: 0.5 },
* })
* ```
*/
static from(text: Text$1, options?: Omit<SplitTextOptions, "text" | "style">): SplitText;
protected splitFn(): TextSplitOutput<Text$1>;
}
/**
* Splits a Text object into segments based on the text's layout and style,
* and adds these segments as individual Text objects to a specified container.
*
* This function handles word wrapping, alignment, and letter spacing,
* ensuring that each segment is rendered correctly according to the original text's style.
* @param options - Configuration options for the text split operation.
* @returns An array of Text objects representing the split segments.
* @internal
*/
export declare function bitmapTextSplit(options: Pick<SplitOptions, "text" | "style"> & {
chars: BitmapText[];
}): TextSplitOutput<BitmapText>;
/**
* Processes the passed character set data and returns a flattened array of all the characters.
*
* Ignored because not directly exposed.
* @ignore
* @param {string | string[] | string[][] } chars
* @returns {string[]} the flattened array of characters
*/
export declare function resolveCharacters(chars: string | (string | string[])[]): string[];
/**
* The BatchableHTMLText class extends the BatchableSprite class and is used to handle HTML text rendering.
* It includes a promise for the texture as generating the HTML texture takes some time.
* @internal
*/
export declare class BatchableHTMLText extends BatchableSprite {
texturePromise: Promise<Texture>;
generatingTexture: boolean;
currentKey: string;
/** Destroys the BatchableHTMLText instance. Returns the texture promise to the renderer and cleans up references. */
destroy(): void;
}
/**
* Constructor options used for `HTMLText` instances. Extends the base text options
* with HTML-specific features and texture styling capabilities.
* @example
* ```ts
* // Basic HTML text
* const basicText = new HTMLText({
* text: '<b>Bold</b> and <i>Italic</i> text',
* style: {
* fontSize: 24,
* fill: 0xff1010
* }
* });
*
* // Rich HTML text with styling
* const richText = new HTMLText({
* text: '<custom>Custom Tag</custom>',
* style: {
* fontFamily: 'Arial',
* fontSize: 32,
* fill: 0x4a4a4a,
* align: 'center',
* tagStyles: {
* custom: {
* fontSize: 32,
* fill: '#00ff00',
* fontStyle: 'italic'
* }
* }
* }
* textureStyle: {
* scaleMode: 'linear',
* }
* });
* ```
* @category text
* @standard
*/
export interface HTMLTextOptions extends TextOptions<HTMLTextStyle, HTMLTextStyleOptions>, PixiMixins.HTMLTextOptions {
/**
* Optional texture style to use for the text texture. This allows fine control over
* how the text is rendered to a texture before being displayed.
*
* The texture style can affect:
* - Scale mode (nearest/linear)
* - Resolution
* - Format (rgb/rgba)
* - Alpha handling
* @example
* ```ts
* const text = new HTMLText({
* text: 'Crisp Text',
* textureStyle: {
* scaleMode: 'nearest', // Pixel-perfect scaling
* }
* });
* ```
* @advanced
*/
textureStyle?: TextureStyle | TextureStyleOptions;
}
export interface HTMLText extends PixiMixins.HTMLText, AbstractText<HTMLTextStyle, HTMLTextStyleOptions, HTMLTextOptions, BatchableHTMLText> {
}
/**
* A HTMLText object creates text using HTML/CSS rendering with SVG foreignObject.
* This allows for rich text formatting using standard HTML tags and CSS styling.
*
* Key features:
* - HTML tag support (<strong>, <em>, etc.)
* - CSS styling and custom style overrides
* - Emoji and special character support
* - Line breaking and word wrapping
* - SVG-based rendering
* @example
* ```ts
* import { HTMLText } from 'pixi.js';
*
* // Basic HTML text with tags
* const text = new HTMLText({
* text: '<h1>Title</h1><p>This is a <strong>bold</strong> and <em>italic</em> text.</p>',
* style: {
* fontFamily: 'Arial',
* fontSize: 24,
* fill: 0xff1010,
* align: 'center',
* }
* });
*
* // Rich HTML text with custom styling
* const richText = new HTMLText({
* text: `
* <div class="title">Welcome</div>
* <div class="content">
* This text supports:
* <ul>
* <li>✨ Emojis</li>
* <li>🎨 Custom CSS</li>
* <li>📏 Auto-sizing</li>
* </ul>
* </div>
* `,
* style: {
* fontSize: 24,
* fill: '#334455',
* cssOverrides: [
* '.title { font-size: 32px; color: red; }',
* '.content { line-height: 1.5; }'
* ],
* wordWrap: true,
* wordWrapWidth: 300,
* }
* });
*
* // Text with custom texture settings
* const crispText = new HTMLText({
* text: '<div style="padding: 10px">High Quality Text</div>',
* style: {
* fontSize: 24,
* fill: '#4a4a4a',
* },
* textureStyle: {
* scaleMode: 'nearest',
* }
* });
* ```
*
* Platform Considerations:
* - Rendering may vary slightly between browsers
* - Requires browser support for foreignObject
* - Performance similar to Canvas text
* - Memory usage comparable to Canvas text
* @category text
* @standard
* @see {@link HTMLTextStyle} For detailed style options
* @see {@link Text} For canvas-based text rendering
* @see {@link BitmapText} For high-performance static text
*/
export declare class HTMLText extends AbstractText<HTMLTextStyle, HTMLTextStyleOptions, HTMLTextOptions, BatchableHTMLText> implements View {
/** @internal */
readonly renderPipeId: string;
/**
* Optional texture style to use for the text.
* > [!NOTE] HTMLText is not updated when this property is updated,
* > you must update the text manually by calling `text.onViewUpdate()`
* @advanced
*/
textureStyle?: TextureStyle;
/**
* @param {HTMLTextOptions} options - The options of the html text.
*/
constructor(options?: HTMLTextOptions);
/** @deprecated since 8.0.0 */
constructor(text?: TextString, options?: Partial<HTMLTextStyle>);
/** @private */
protected updateBounds(): void;
get text(): string;
/**
* The text content to display. Use '\n' for line breaks.
* Accepts strings, numbers, or objects with toString() method.
* @example
* ```ts
* const text = new HTMLText({
* text: 'Hello Pixi!',
* });
* const multilineText = new HTMLText({
* text: 'Line 1\nLine 2\nLine 3',
* });
* const numberText = new HTMLText({
* text: 12345, // Will be converted to '12345'
* });
* const objectText = new HTMLText({
* text: { toString: () => 'Object Text' }, // Custom toString
* });
*
* // Update text dynamically
* text.text = 'Updated Text'; // Re-renders with new text
* text.text = 67890; // Updates to '67890'
* text.text = { toString: () => 'Dynamic Text' }; // Uses custom toString method
* // Clear text
* text.text = ''; // Clears the text
* ```
* @default ''
*/
set text(text: TextString);
/**
* Sanitise text - replace `<br>` with `<br/>`, ` ` with ` `
* @param text
* @see https://www.sitepoint.com/community/t/xhtml-1-0-transitional-xml-parsing-error-entity-nbsp-not-defined/3392/3
*/
private _sanitiseText;
private _removeInvalidHtmlTags;
}
/**
* The HTMLTextPipe class is responsible for rendering HTML text.
* @internal
*/
export declare class HTMLTextPipe implements RenderPipe<HTMLText> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "htmlText";
};
private _renderer;
private readonly _managedTexts;
constructor(renderer: Renderer);
protected resolutionChange(): void;
validateRenderable(htmlText: HTMLText): boolean;
addRenderable(htmlText: HTMLText, instructionSet: InstructionSet): void;
updateRenderable(htmlText: HTMLText): void;
private _updateGpuText;
private _getGpuText;
initGpuText(htmlText: HTMLText): BatchableHTMLText;
protected onTextUnload(text: HTMLText): void;
destroy(): void;
}
/** @internal */
export declare class HTMLTextRenderData {
svgRoot: SVGSVGElement;
foreignObject: SVGForeignObjectElement;
domElement: HTMLElement;
styleElement: HTMLElement;
image: ImageLike;
canvasAndContext?: CanvasAndContext;
constructor();
destroy(): void;
}
/**
* System plugin to the renderer to manage HTMLText
* @category rendering
* @advanced
*/
export declare class HTMLTextSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "htmlText";
};
/**
* WebGPU has a cors issue when uploading an image that is an SVGImage
* To get around this we need to create a canvas draw the image to it and upload that instead.
* Bit of a shame.. but no other work around just yet!
*/
private readonly _createCanvas;
private readonly _renderer;
private readonly _activeTextures;
constructor(renderer: Renderer);
/**
* @param options
* @deprecated Use getTexturePromise instead
*/
getTexture(options: HTMLTextOptions): Promise<Texture>;
/**
* Increases the reference count for a texture.
* @param text - The HTMLText instance associated with the texture.
*/
getManagedTexture(text: HTMLText): Promise<Texture>;
/**
* Gets the current reference count for a texture associated with a text key.
* @param textKey - The unique key identifying the text style configuration
* @returns The number of Text instances currently using this texture
*/
getReferenceCount(textKey: string): number;
private _increaseReferenceCount;
/**
* Decreases the reference count for a texture.
* If the count reaches zero, the texture is cleaned up.
* @param textKey - The key associated with the HTMLText instance.
*/
decreaseReferenceCount(textKey: string): void;
/**
* Returns a promise that resolves to a texture for the given HTMLText options.
* @param options - The options for the HTMLText.
* @returns A promise that resolves to a Texture.
*/
getTexturePromise(options: HTMLTextOptions): Promise<Texture>;
private _buildTexturePromise;
returnTexturePromise(texturePromise: Promise<Texture>): void;
private _cleanUp;
destroy(): void;
}
/**
* Extracts font families from text. It will extract font families from the style, tagStyles and any font families
* embedded in the text. It should also strip out duplicates as it goes.
* @param text - The text to extract font families from
* @param style - The style to extract font families from
* @returns {string[]} - The font families as an array of strings
* @internal
*/
export declare function extractFontFamilies(text: string, style: HTMLTextStyle): string[];
/** @internal */
export declare const FontStylePromiseCache: Map<string, Promise<string>>;
/**
* takes the font families and returns a css string that can be injected into a style tag
* It will contain the font families and the font urls encoded as base64
* @param fontFamilies - The font families to load
* @returns - The css string
* @internal
*/
export declare function getFontCss(fontFamilies: string[]): Promise<string>;
/**
* takes all the data and returns a svg url string can be loaded by an image element
* @param text - The text to measure
* @param style - The style to use
* @param resolution - The resolution to use
* @param fontCSS - The font css to use
* @param htmlTextData - The HTMLTextRenderData to write the SVG to
* @returns - The SVG as a url string
* @internal
*/
export declare function getSVGUrl(text: string, style: HTMLTextStyle, resolution: number, fontCSS: string, htmlTextData: HTMLTextRenderData): string;
/**
* This function converts an image to a canvas, and returns the canvas.
* It is used to convert images to canvases to work around a CORS issue where WebGPU cannot
* upload an SVGImage to a texture.
*
* It uses the CanvasPool to get an optimal canvas and context, and then draws the image onto it.
* Remember to return this canvas is immediately to the CanvasPool for reuse when you are done with it.
* (eg upload it to the GPU!)
* @param image - The image to convert to a canvas.
* @param resolution - The resolution of the canvas.
* @internal
*/
export declare function getTemporaryCanvasFromImage(image: ImageLike, resolution: number): CanvasAndContext;
/**
* Resolves a font url to a base64 string
* @param url - The url to load the font from
* @returns - The font as a base64 string
* @internal
*/
export declare function loadFontAsBase64(url: string): Promise<string>;
/**
* Options for the font CSS style
* @category text
* @internal
*/
export interface FontCSSStyleOptions {
/**
* The font family to use in the CSS
* @example
* 'Arial' or ['Arial', 'Helvetica']
*/
fontFamily: string | string[];
/**
* The font weight to use in the CSS
* @example
* 'normal', 'bold', '100', '200', etc.
*/
fontWeight: string;
/**
* The font style to use in the CSS
* @example
* 'normal', 'italic', 'oblique'
*/
fontStyle: string;
}
/**
* This will take a font url and a style and return a css string that can be injected into a style tag
* This will contain inlined base64 font and the font family information
* @param style - the style to generate the css for
* @param url - The url to load the font from
* @returns - The css string
* @internal
*/
export declare function loadFontCSS(style: FontCSSStyleOptions, url: string): Promise<string>;
/**
* This function loads an SVG image into an IImage element.
* The image can then be uploaded as texture to the GPU.
* iOS has a bug where embedded fonts are not available immediately after the image loads,
* so we wait an arbitrary amount of time before resolving the promise.
* @param image - The image to load the SVG into
* @param url - The url to load the SVG from
* @param delay - Whether to delay the load
* @returns - A promise that resolves when the image has loaded
* @internal
*/
export declare function loadSVGImage(image: ImageLike, url: string, delay: boolean): Promise<void>;
/**
* Measures the HTML text without actually generating an image.
* This is used to calculate the size of the text.
* @param text - The text to measure
* @param style - The style to use
* @param fontStyleCSS - The font css to use
* @param htmlTextRenderData - The HTMLTextRenderData to write the SVG to
* @returns - The size of the text
* @internal
*/
export declare function measureHtmlText(text: string, style: HTMLTextStyle, fontStyleCSS?: string, htmlTextRenderData?: HTMLTextRenderData): Size;
/**
* Internally converts all of the style properties into CSS equivalents.
* @param style
* @returns The CSS style string, for setting `style` property of root HTMLElement.
* @internal
*/
export declare function textStyleToCSS(style: HTMLTextStyle): string;
/**
* Configuration options for BitmapText splitting.
* @category text
* @standard
* @interface
*/
export interface SplitBitmapOptions extends AbstractSplitOptions {
}
/**
* Configuration options for SplitBitmapText, combining container properties with text splitting settings.
* @example Basic Usage
* ```ts
* const options: SplitBitmapTextOptions = {
* text: 'Hello World',
* style: { fontSize: 32, fill: 0xffffff },
* // Transform origins
* lineAnchor: 0.5, // Center each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center each char
* };
* ```
* @example Advanced Configuration
* ```ts
* const options: SplitBitmapTextOptions = {
* // Text content and style
* text: 'Multi\nLine Text',
* style: new TextStyle({
* fontSize: 24,
* fill: 'white',
* strokeThickness: 2,
* }),
*
* // Container properties
* x: 100,
* y: 100,
* alpha: 0.8,
*
* // Splitting settings
* autoSplit: true,
*
* // Transform origins (normalized 0-1)
* lineAnchor: { x: 1, y: 0 }, // Top-right
* wordAnchor: 0.5, // Center
* charAnchor: { x: 0, y: 1 }, // Bottom-left
* };
* ```
*
* Properties:
* - Container options from {@link ContainerOptions}
* - Text splitting options from {@link SplitBitmapOptions}
* - Additional PixiJS-specific options from PixiMixins.SplitBitmapText
* @see {@link SplitBitmapText} For the main implementation
* @see {@link ContainerOptions} For base container properties
* @see {@link SplitBitmapOptions} For text splitting options
* @category text
* @standard
*/
export interface SplitBitmapTextOptions extends PixiMixins.SplitBitmapText, ContainerOptions, SplitBitmapOptions {
}
/**
* @experimental
* A container that splits text into individually manipulatable segments (lines, words, and characters)
* for advanced text effects and animations.
* Converts each segment into a separate BitmapText object.
* @example Basic Usage
* ```ts
* const text = new SplitBitmapText({
* text: "Hello World",
* style: { fontSize: 24 },
* // Origin points for transformations (0-1 range)
* lineAnchor: 0.5, // Center of each line
* wordAnchor: { x: 0, y: 0.5 }, // Left-center of each word
* charAnchor: { x: 0.5, y: 1 }, // Bottom-center of each character
* autoSplit: true // Auto-update segments on text/style changes
* });
* ```
*
* Features:
* - Hierarchical text segmentation (lines → words → characters)
* - Independent transformation origins for each segment level
* - Automatic or manual segment updates
* @example Animation Example
* ```ts
* // Character fade-in sequence
* text.chars.forEach((char, i) => {
* gsap.from(char, {
* alpha: 0,
* delay: i * 0.1
* });
* });
*
* // Word scale animation
* text.words.forEach((word, i) => {
* gsap.to(word.scale, {
* x: 1.2, y: 1.2,
* yoyo: true,
* repeat: -1,
* delay: i * 0.2
* });
* });
*
* // Line slide-in effect
* text.lines.forEach((line, i) => {
* gsap.from(line, {
* x: -200,
* delay: i * 0.3
* });
* });
* ```
*
* Configuration Options:
* - `text`: The string to render and segment
* - `style`: TextStyle instance or configuration object
* - `autoSplit`: Automatically update segments on changes (default: true)
* - `lineAnchor`: Transform origin for lines (default: 0)
* - `wordAnchor`: Transform origin for words (default: 0)
* - `charAnchor`: Transform origin for characters (default: 0)
*
* > [!NOTE] Anchor points are normalized (0-1):
* > - 0,0: Top-left
* > - 0.5,0.5: Center
* > - 1,1: Bottom-right
*
* > [!WARNING] Limitations
* > - Character spacing may differ slightly from standard text due to browser
* > kerning being lost when characters are separated
* @category text
* @standard
*/
export declare class SplitBitmapText extends AbstractSplitText<BitmapText> {
/**
* Default configuration options for SplitBitmapText instances.
* @example
* ```ts
* // Override defaults globally
* SplitBitmapText.defaultOptions = {
* autoSplit: false,
* lineAnchor: 0.5, // Center alignment
* wordAnchor: { x: 0, y: 0.5 }, // Left-center
* charAnchor: { x: 0.5, y: 1 } // Bottom-center
* };
* ```
*/
static defaultOptions: Partial<SplitBitmapTextOptions>;
constructor(config: SplitBitmapTextOptions);
/**
* Creates a SplitBitmapText instance from an existing text object.
* Useful for converting standard Text or BitmapText objects into segmented versions.
* @param text - The source text object to convert
* @param options - Additional splitting options
* @returns A new SplitBitmapText instance
* @example
* ```ts
* const bitmapText = new BitmapText({
* text: 'Bitmap Text',
* style: { fontFamily: 'Arial' }
* });
*
* const segmented = SplitBitmapText.from(bitmapText);
*
* // with additional options
* const segmentedWithOptions = SplitBitmapText.from(bitmapText, {
* autoSplit: false,
* lineAnchor: 0.5,
* wordAnchor: { x: 0, y: 0.5 },
* })
* ```
*/
static from(text: BitmapText, options?: Omit<SplitBitmapTextOptions, "text" | "style">): SplitBitmapText;
protected splitFn(): TextSplitOutput<BitmapText>;
}
declare class CanvasTextGeneratorClass {
/**
* Creates a canvas with the specified text rendered to it.
*
* Generates a canvas of appropriate size, renders the text with the provided style,
* and returns both the canvas/context and a Rectangle representing the text bounds.
*
* When trim is enabled in the style, the frame will represent the bounds of the
* non-transparent pixels, which can be smaller than the full canvas.
* @param options - The options for generating the text canvas
* @param options.text - The text to render
* @param options.style - The style to apply to the text
* @param options.resolution - The resolution of the canvas (defaults to 1)
* @param options.padding
* @returns An object containing the canvas/context and the frame (bounds) of the text
*/
getCanvasAndContext(options: {
text: string;
style: TextStyle;
resolution?: number;
padding?: number;
}): {
canvasAndContext: CanvasAndContext;
frame: Rectangle;
};
/**
* Returns a canvas and context to the pool.
*
* This should be called when you're done with the canvas to allow reuse
* and prevent memory leaks.
* @param canvasAndContext - The canvas and context to return to the pool
*/
returnCanvasAndContext(canvasAndContext: CanvasAndContext): void;
/**
* Renders text to its canvas, and updates its texture.
* @param text - The text to render
* @param style - The style of the text
* @param padding - The padding of the text
* @param resolution - The resolution of the text
* @param canvasAndContext - The canvas and context to render the text to
*/
private _renderTextToCanvas;
/**
* Render the text with letter-spacing.
*
* This method handles rendering text with the correct letter spacing, using either:
* 1. Native letter spacing if supported by the browser
* 2. Manual letter spacing calculation if not natively supported
*
* For manual letter spacing, it calculates the position of each character
* based on its width and the desired spacing.
* @param text - The text to draw
* @param style - The text style to apply
* @param canvasAndContext - The canvas and context to draw to
* @param x - Horizontal position to draw the text
* @param y - Vertical position to draw the text
* @param isStroke - Whether to render the stroke (true) or fill (false)
* @private
*/
private _drawLetterSpacing;
}
/** @internal */
export declare const CanvasTextGenerator: CanvasTextGeneratorClass;
/** @internal */
export declare class CanvasTextPipe implements RenderPipe<Text$1> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "text";
};
private _renderer;
private readonly _managedTexts;
constructor(renderer: Renderer);
protected resolutionChange(): void;
validateRenderable(text: Text$1): boolean;
addRenderable(text: Text$1, instructionSet: InstructionSet): void;
updateRenderable(text: Text$1): void;
private _updateGpuText;
private _getGpuText;
initGpuText(text: Text$1): BatchableText;
protected onTextUnload(text: Text$1): void;
destroy(): void;
}
/**
* System plugin to the renderer to manage canvas text.
* @category rendering
* @advanced
*/
export declare class CanvasTextSystem implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem,
ExtensionType.CanvasSystem
];
readonly name: "canvasText";
};
private readonly _renderer;
private readonly _activeTextures;
constructor(_renderer: Renderer);
/** @deprecated since 8.0.0 */
getTexture(text: string, resolution: number, style: TextStyle, textKey: string): Texture;
/**
* This is a function that will create a texture from a text string, style and resolution.
* Useful if you want to make a texture of your text and use if for various other pixi things!
* @param options - The options of the text that will be used to generate the texture.
* @param options.text - the text to render
* @param options.style - the style of the text
* @param options.resolution - the resolution of the texture
* @returns the newly created texture
*/
getTexture(options: CanvasTextOptions): Texture;
/**
* Returns a texture that was created wit the above `getTexture` function.
* Handy if you are done with a texture and want to return it to the pool.
* @param texture - The texture to be returned.
*/
returnTexture(texture: Texture): void;
/**
* Renders text to its canvas, and updates its texture.
* @deprecated since 8.10.0
*/
renderTextToCanvas(): void;
/**
* Gets or creates a managed texture for a Text object. This method handles texture reuse and reference counting.
* @param text - The Text object that needs a texture
* @returns A Texture instance that represents the rendered text
* @remarks
* This method performs the following:
* 1. Sets the appropriate resolution based on auto-resolution settings
* 2. Checks if a texture already exists for the text's style
* 3. Creates a new texture if needed or returns an existing one
* 4. Manages reference counting for texture reuse
*/
getManagedTexture(text: Text$1): Texture<TextureSource<any>>;
/**
* Decreases the reference count for a texture associated with a text key.
* When the reference count reaches zero, the texture is returned to the pool.
* @param textKey - The unique key identifying the text style configuration
* @remarks
* This method is crucial for memory management, ensuring textures are properly
* cleaned up when they are no longer needed by any Text instances.
*/
decreaseReferenceCount(textKey: string): void;
/**
* Gets the current reference count for a texture associated with a text key.
* @param textKey - The unique key identifying the text style configuration
* @returns The number of Text instances currently using this texture
*/
getReferenceCount(textKey: string): number;
private _increaseReferenceCount;
/**
* Applies the specified filters to the given texture.
*
* This method takes a texture and a list of filters, applies the filters to the texture,
* and returns the resulting texture. It also ensures that the alpha mode of the resulting
* texture is set to 'premultiplied-alpha'.
* @param {Texture} texture - The texture to which the filters will be applied.
* @param {Filter[]} filters - The filters to apply to the texture.
* @returns {Texture} The resulting texture after all filters have been applied.
*/
private _applyFilters;
destroy(): void;
}
/**
* Generates a font style string to use for `TextMetrics.measureFont()`.
* @param style
* @returns Font style string, for passing to `TextMetrics.measureFont()`
* @internal
*/
export declare function fontStringFromTextStyle(style: TextStyle): string;
/**
* Converts a PixiJS fill style into a Canvas-compatible fill style.
* Handles solid colors, textures, patterns, and gradients.
* @param fillStyle - The PixiJS fill style to convert
* @param context - The canvas rendering context
* @param textMetrics - Metrics about the text being rendered
* @param padding - Padding to add to the text metrics (used to ensure that the gradient accommodates the stroke width)
* @returns Canvas-compatible fill style (string, CanvasGradient, or CanvasPattern)
* @internal
*/
export declare function getCanvasFillStyle(fillStyle: ConvertedFillStyle, context: ICanvasRenderingContext2D, textMetrics?: CanvasTextMetrics, padding?: number): string | CanvasGradient | CanvasPattern;
/** @internal */
export declare class SdfShader extends Shader {
constructor(maxTextures: number);
}
/** @internal */
export declare const localUniformMSDFBit: {
name: string;
vertex: {
header: string;
main: string;
end: string;
};
fragment: {
header: string;
main: string;
};
};
/** @internal */
export declare const localUniformMSDFBitGl: {
name: string;
vertex: {
header: string;
main: string;
end: string;
};
fragment: {
header: string;
main: string;
};
};
/** @internal */
export declare const mSDFBit: {
name: string;
fragment: {
header: string;
};
};
/** @internal */
export declare const mSDFBitGl: {
name: string;
fragment: {
header: string;
};
};
/**
* Splits a Text object into segments based on the text's layout and style,
* and adds these segments as individual Text objects to a specified container.
*
* This function handles word wrapping, alignment, and letter spacing,
* ensuring that each segment is rendered correctly according to the original text's style.
* It uses the CanvasTextMetrics to measure text dimensions and segment the text into lines.
* @param options - Configuration options for the text split operation.
* @returns An array of Text objects representing the split segments.
* @internal
*/
export declare function canvasTextSplit(options: Pick<SplitOptions, "text" | "style"> & {
chars: Text$1[];
}): TextSplitOutput<Text$1>;
/**
* Generates a unique key for the text style.
* @param style - The style to generate a key for.
* @returns the key for the style.
* @internal
* @deprecated 8.12.0
*/
export declare function generateTextStyleKey(style: TextStyle): string;
/**
* Takes an image and creates a texture from it, using a power of 2 texture from the texture pool.
* Remember to return the texture when you don't need it any more!
* @param image - The image to create a texture from
* @param width - the frame width of the texture
* @param height - the frame height of the texture
* @param resolution - The resolution of the texture
* @returns - The texture
* @internal
*/
export declare function getPo2TextureFromSource(image: ImageLike | HTMLCanvasElement | ICanvas, width: number, height: number, resolution: number): Texture;
/**
* Updates the bounds of the given batchable sprite based on the provided text object.
*
* This function adjusts the bounds of the batchable sprite to match the dimensions
* and anchor point of the text's texture. Additionally, it compensates for any padding
* specified in the text's style to ensure the text is rendered correctly on screen.
* @param {BatchableSprite} batchableSprite - The sprite whose bounds need to be updated.
* @param {AbstractText} text - The text object containing the texture and style information.
* @internal
*/
export declare function updateTextBounds(batchableSprite: BatchableSprite, text: AbstractText<TextStyle, TextStyleOptions>): void;
/**
* Shader that uses a texture.
* This is the default shader used by `Mesh` when no shader is provided.
* It is a simple shader that samples a texture and applies it to the geometry.
* @category scene
* @advanced
*/
export interface TextureShader extends Shader {
/** The texture that the shader uses. */
texture: Texture;
}
/**
* Constructor options used for `Mesh` instances. Extends {@link MeshViewOptions}
* ```js
* const mesh = new Mesh({
* texture: Texture.from('assets/image.png'),
* geometry: new PlaneGeometry(),
* shader: Shader.from(VERTEX, FRAGMENT),
* });
* ```
* @see {@link Mesh}
* @see {@link MeshViewOptions}
* @category scene
*/
/**
* Options for creating a Mesh instance.
* @category scene
* @advanced
* @noInheritDoc
*/
export interface MeshOptions<GEOMETRY extends Geometry = MeshGeometry, SHADER extends Shader = TextureShader> extends PixiMixins.MeshOptions, ContainerOptions {
/**
* Includes vertex positions, face indices, colors, UVs, and
* custom attributes within buffers, reducing the cost of passing all
* this data to the GPU. Can be shared between multiple Mesh objects.
*/
geometry: GEOMETRY;
/**
* Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
* Can be shared between multiple Mesh objects.
*/
shader?: SHADER | null;
/** The state of WebGL required to render the mesh. */
state?: State;
/** The texture that the Mesh uses. Null for non-MeshMaterial shaders */
texture?: Texture;
/** Whether or not to round the x/y position. */
roundPixels?: boolean;
}
export interface Mesh extends PixiMixins.Mesh, ViewContainer<MeshGpuData> {
}
/**
* Base mesh class.
*
* This class empowers you to have maximum flexibility to render any kind of WebGL/WebGPU visuals you can think of.
* This class assumes a certain level of WebGL/WebGPU knowledge.
* If you know a bit this should abstract enough away to make your life easier!
*
* Pretty much ALL WebGL/WebGPU can be broken down into the following:
* - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc..
* - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry)
* - State - This is the state of WebGL required to render the mesh.
*
* Through a combination of the above elements you can render anything you want, 2D or 3D!
* @category scene
* @advanced
*/
export declare class Mesh<GEOMETRY extends Geometry = MeshGeometry, SHADER extends Shader = TextureShader> extends ViewContainer<MeshGpuData> implements View, Instruction {
/** @internal */
readonly renderPipeId: string;
state: State;
/** @internal */
_texture: Texture;
/** @internal */
_geometry: GEOMETRY;
/** @internal */
_shader: SHADER | null;
/**
* @param {MeshOptions} options - options for the mesh instance
*/
constructor(options: MeshOptions<GEOMETRY, SHADER>);
/** @deprecated since 8.0.0 */
constructor(geometry: GEOMETRY, shader: SHADER, state?: State, drawMode?: Topology);
/** Alias for {@link Mesh#shader}. */
get material(): SHADER;
/**
* Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
* Can be shared between multiple Mesh objects.
*/
set shader(value: SHADER | null);
get shader(): SHADER | null;
/**
* Includes vertex positions, face indices, colors, UVs, and
* custom attributes within buffers, reducing the cost of passing all
* this data to the GPU. Can be shared between multiple Mesh objects.
*/
set geometry(value: GEOMETRY);
get geometry(): GEOMETRY;
/** The texture that the Mesh uses. Null for non-MeshMaterial shaders */
set texture(value: Texture);
get texture(): Texture;
get batched(): boolean;
/**
* The local bounds of the mesh.
* @type {Bounds}
*/
get bounds(): Bounds;
/**
* Update local bounds of the mesh.
* @private
*/
protected updateBounds(): void;
/**
* Checks if the object contains the given point.
* @param point - The point to check
*/
containsPoint(point: PointData): boolean;
/**
* Destroys this sprite renderable and optionally its texture.
* @param options - Options parameter. A boolean will act as if all options
* have been set to that value
* @example
* mesh.destroy();
* mesh.destroy(true);
* mesh.destroy({ texture: true, textureSource: true });
*/
destroy(options?: DestroyOptions): void;
}
/**
* GPUData for Mesh
* @internal
*/
export declare class MeshGpuData implements GPUData {
meshData?: MeshData;
batchableMesh?: BatchableMesh;
destroy(): void;
}
interface MeshData {
/** if the mesh is batched or not */
batched: boolean;
/** the size of the index buffer */
indexSize: number;
/** the size of the vertex buffer */
vertexSize: number;
}
/** @internal */
export interface MeshAdaptor {
init(): void;
execute(meshPipe: MeshPipe, mesh: Mesh): void;
destroy(): void;
}
/**
* The MeshPipe is responsible for handling the rendering of Mesh objects.
* It manages the batching of meshes, updates their GPU data, and executes the rendering instructions.
* It also handles the local uniforms for each mesh, such as transformation matrices and colors.
* @category scene
* @internal
*/
export declare class MeshPipe implements RenderPipe<Mesh>, InstructionPipe<Mesh> {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLPipes,
ExtensionType.WebGPUPipes,
ExtensionType.CanvasPipes
];
readonly name: "mesh";
};
localUniforms: UniformGroup<{
uTransformMatrix: {
value: Matrix;
type: "mat3x3<f32>";
};
uColor: {
value: Float32Array;
type: "vec4<f32>";
};
uRound: {
value: number;
type: "f32";
};
}>;
localUniformsBindGroup: BindGroup;
renderer: Renderer;
private _adaptor;
constructor(renderer: Renderer, adaptor: MeshAdaptor);
validateRenderable(mesh: Mesh): boolean;
addRenderable(mesh: Mesh, instructionSet: InstructionSet): void;
updateRenderable(mesh: Mesh): void;
execute(mesh: Mesh): void;
private _getMeshData;
private _initMeshData;
private _getBatchableMesh;
private _initBatchableMesh;
destroy(): void;
}
declare global {
namespace PixiMixins {
interface RendererPipes {
mesh: MeshPipe;
}
}
}
declare global {
namespace PixiMixins {
interface RendererPipes {
particle: ParticleContainerPipe;
}
}
}
declare global {
namespace PixiMixins {
interface Container<C extends ContainerChild = ContainerChild> extends ChildrenHelperMixin<C>, ToLocalGlobalMixin, OnRenderMixin, MeasureMixin, EffectsMixin, FindMixin, SortMixin, GetGlobalMixin, CollectRenderablesMixin, GetFastGlobalBoundsMixin, CacheAsTextureMixin {
}
interface ContainerOptions extends OnRenderMixinConstructor, MeasureMixinConstructor, EffectsMixinConstructor, FindMixinConstructor, SortMixinConstructor, CacheAsTextureMixinConstructor {
}
interface ViewContainer {
}
interface ViewContainerOptions {
}
interface Graphics {
}
interface GraphicsOptions {
}
interface Mesh {
}
interface MeshOptions {
}
interface ParticleContainer {
}
interface ParticleContainerOptions {
}
interface Sprite {
}
interface SpriteOptions {
}
interface AnimatedSprite {
}
interface AnimatedSpriteOptions {
}
interface NineSliceSprite {
}
interface NineSliceSpriteOptions {
}
interface TilingSprite {
}
interface TilingSpriteOptions {
}
interface Text {
}
interface BitmapText {
}
interface TextOptions {
}
interface HTMLText {
}
interface HTMLTextOptions {
}
interface SplitText {
}
interface SplitTextOptions {
}
interface SplitBitmapText {
}
interface SplitBitmapTextOptions {
}
}
}
declare global {
namespace PixiMixins {
interface RendererPipes {
nineSliceSprite: NineSliceSpritePipe;
}
}
}
declare global {
namespace PixiMixins {
interface RendererPipes {
tilingSprite: TilingSpritePipe;
}
}
}
declare global {
namespace PixiMixins {
interface RendererPipes {
bitmapText: BitmapTextPipe;
}
}
}
declare global {
namespace PixiMixins {
interface RendererSystems {
htmlText: HTMLTextSystem;
}
interface RendererPipes {
htmlText: HTMLTextPipe;
}
}
}
declare global {
namespace PixiMixins {
interface RendererSystems {
canvasText: CanvasTextSystem;
}
interface RendererPipes {
text: CanvasTextPipe;
}
}
}
/** @internal */
export interface BlendModeFilterOptions {
source?: string;
gpu?: {
functions?: string;
main?: string;
};
gl?: {
functions?: string;
main?: string;
};
}
/** @internal */
export declare class BlendModeFilter extends Filter {
constructor(options: BlendModeFilterOptions);
}
/**
* The final color has the hue and saturation of the top color, while using the luminosity of the bottom color.
* The effect preserves gray levels and can be used to colorize the foreground.
*
* Available as `container.blendMode = 'color'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'color'
* @category filters
* @noInheritDoc
*/
export declare class ColorBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is the result of inverting the bottom color, dividing the value by the top color,
* and inverting that value. A white foreground leads to no change.
* A foreground with the inverse color of the backdrop leads to a black final image.
* This blend mode is similar to multiply, but the foreground need only be as dark as the inverse
* of the backdrop to make the final image black.
*
* Available as `container.blendMode = 'color-burn'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'color-burn'
* @category filters
* @noInheritDoc
*/
export declare class ColorBurnBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is the result of dividing the bottom color by the inverse of the top color.
* A black foreground leads to no change.
* A foreground with the inverse color of the backdrop leads to a fully lit color.
* This blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color.
*
* Available as `container.blendMode = 'color-dodge'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'color-dodge'
* @category filters
* @noInheritDoc
*/
export declare class ColorDodgeBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is composed of the darkest values of each color channel.
*
* Available as `container.blendMode = 'darken'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'darken'
* @category filters
* @noInheritDoc
*/
export declare class DarkenBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is the result of subtracting the darker of the two colors from the lighter one.
* black layer has no effect, while a white layer inverts the other layer's color.
*
* Available as `container.blendMode = 'difference'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'difference'
* @category filters
* @noInheritDoc
*/
export declare class DifferenceBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The Divide blend mode divides the RGB channel values of the bottom layer by those of the top layer.
* The darker the top layer, the brighter the bottom layer will appear.
* Blending any color with black yields white, and blending with white has no effect
*
* Available as `container.blendMode = 'divide'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'divide'
* @category filters
* @noInheritDoc
*/
export declare class DivideBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is similar to difference, but with less contrast.
* As with difference, a black layer has no effect, while a white layer inverts the other layer's color.
*
* Available as `container.blendMode = 'exclusion'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'exclusion'
* @category filters
* @noInheritDoc
*/
export declare class ExclusionBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is the result of multiply if the top color is darker, or screen if the top color is lighter.
* This blend mode is equivalent to overlay but with the layers swapped.
* The effect is similar to shining a harsh spotlight on the backdrop.
*
* Available as `container.blendMode = 'hard-light'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'hard-light'
* @category filters
* @noInheritDoc
*/
export declare class HardLightBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Hard defines each of the color channel values of the blend color to the RGB values of the base color.
* If the sum of a channel is 255, it receives a value of 255; if less than 255, a value of 0.
*
* Available as `container.blendMode = 'hard-mix'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'hard-mix'
* @category filters
* @noInheritDoc
*/
export declare class HardMixBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is composed of the lightest values of each color channel.
*
* Available as `container.blendMode = 'lighten'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'lighten'
* @category filters
* @noInheritDoc
*/
export declare class LightenBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Looks at the color information in each channel and darkens the base color to
* reflect the blend color by increasing the contrast between the two.
*
* Available as `container.blendMode = 'linear-burn'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'linear-burn'
* @category filters
* @noInheritDoc
*/
export declare class LinearBurnBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Looks at the color information in each channel and brightens the base color to reflect the blend color by decreasing contrast between the two.
*
* Available as `container.blendMode = 'linear-dodge'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'linear-dodge'
* @category filters
* @noInheritDoc
*/
export declare class LinearDodgeBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Increase or decrease brightness by burning or dodging color values, based on the blend color
*
* Available as `container.blendMode = 'linear-light'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'linear-light'
* @category filters
* @noInheritDoc
*/
export declare class LinearLightBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color has the luminosity of the top color, while using the hue and saturation of the bottom color.
* This blend mode is equivalent to color, but with the layers swapped.
*
* Available as `container.blendMode = 'luminosity'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'luminosity'
* @category filters
* @noInheritDoc
*/
export declare class LuminosityBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Implements the Negation blend mode which creates an inverted effect based on the brightness values.
*
* Available as `container.blendMode = 'negation'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'negation'
* @category filters
* @noInheritDoc
*/
export declare class NegationBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is the result of multiply if the bottom color is darker, or screen if the bottom color is lighter.
* This blend mode is equivalent to hard-light but with the layers swapped.
*
* Available as `container.blendMode = 'overlay'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'overlay'
* @category filters
* @noInheritDoc
*/
export declare class OverlayBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Replaces colors based on the blend color.
*
* Available as `container.blendMode = 'pin-light'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'pin-light'
* @category filters
* @noInheritDoc
*/
export declare class PinLightBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color has the saturation of the top color, while using the hue and luminosity of the bottom color.
* A pure gray backdrop, having no saturation, will have no effect.
*
* Available as `container.blendMode = 'saturation'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'saturation'
* @category filters
* @noInheritDoc
*/
export declare class SaturationBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light.
* The effect is similar to shining a diffused spotlight on the backdrop.
*
* Available as `container.blendMode = 'soft-light'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'soft-light'
* @category filters
* @noInheritDoc
*/
export declare class SoftLightBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Subtracts the blend from the base color using each color channel
*
* Available as `container.blendMode = 'subtract'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'subtract'
* @category filters
* @noInheritDoc
*/
export declare class SubtractBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* Darkens values darker than 50% gray and lightens those brighter than 50% gray, creating a dramatic effect.
* It's essentially an extreme version of the Overlay mode, with a significant impact on midtones
*
* Available as `container.blendMode = 'vivid-light'` after importing `pixi.js/advanced-blend-modes`.
* @example
* import 'pixi.js/advanced-blend-modes';
* import { Sprite } from 'pixi.js';
*
* const sprite = Sprite.from('something.png');
* sprite.blendMode = 'vivid-light'
* @category filters
* @noInheritDoc
*/
export declare class VividLightBlend extends BlendModeFilter {
/** @ignore */
static extension: ExtensionMetadata;
constructor();
}
/**
* A more verbose version of the AssetExtension,
* allowing you to set the cached, loaded, parsed, and unloaded asset separately
* @category assets
* @advanced
*/
export interface AssetExtensionAdvanced<ASSET = any, PARSED_ASSET = ASSET, UNLOAD_ASSET = ASSET, CACHE_ASSET = ASSET, META_DATA = any> {
/** The type of extension */
extension: ExtensionType.Asset;
/** the asset loader */
loader?: LoaderParserAdvanced<ASSET, PARSED_ASSET, UNLOAD_ASSET, META_DATA>;
/** the asset resolve parser */
resolver?: Partial<ResolveURLParser>;
/** the asset cache parser */
cache?: Partial<CacheParser<CACHE_ASSET>>;
/** the asset format detection parser */
detection?: Partial<FormatDetectionParser>;
}
/**
* 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
* },
* async load(url: string, options: ResolvedAsset, loader: Loader) {
* // This is the promise that loads the URL provided
* },
* 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,
* }
* @category assets
* @advanced
*/
export interface AssetExtension<ASSET = any, META_DATA = any> extends AssetExtensionAdvanced<ASSET, ASSET, ASSET, ASSET, META_DATA> {
}
/**
* The BackgroundLoader handles loading assets passively in the background to prepare them for future use.
* It loads one asset at a time to minimize impact on application performance.
*
* Key features:
* - Sequential loading of assets
* - Automatic pause when high-priority loads occur
* - Configurable concurrency
* @example
* ```ts
* import { Assets } from 'pixi.js';
*
* // Background load level assets while in menu
* Assets.backgroundLoad([
* 'level1/background.png',
* 'level1/sprites.json',
* 'level1/music.mp3'
* ]);
*
* // Assets will be instantly available when needed
* const assets = await Assets.load([
* 'level1/background.png',
* 'level1/sprites.json'
* ]);
*
* // Background load bundles
* Assets.backgroundLoadBundle('level2');
*
* // Later, instant access
* const level2 = await Assets.loadBundle('level2');
* ```
* > [!NOTE] You typically do not need to use this class directly. Use the main {@link Assets.backgroundLoad} API instead.
* @remarks
* - Background loading is automatically paused when `Assets.load()` is called
* - Assets are loaded sequentially to minimize performance impact
* - Assets are cached as they complete loading
* - No progress tracking is available for background loading
* @see {@link Assets.backgroundLoad} For the main background loading API
* @see {@link Assets.backgroundLoadBundle} For background loading bundles
* @category assets
* @advanced
*/
export declare class BackgroundLoader {
/** Whether or not the loader should continue loading. */
private _isActive;
/** Assets to load. */
private readonly _assetList;
/** Whether or not the loader is loading. */
private _isLoading;
/** Number of assets to load at a time. */
private readonly _maxConcurrent;
/**
* Should the loader log to the console.
* @advanced
*/
verbose: boolean;
private readonly _loader;
/**
* @param loader
* @param verbose - should the loader log to the console
*/
constructor(loader: Loader, verbose?: boolean);
/**
* Adds assets to the background loading queue. Assets are loaded one at a time to minimize
* performance impact.
* @param assetUrls - Array of resolved assets to load in the background
* @example
* ```ts
* // Add assets to background load queue
* backgroundLoader.add([
* { src: 'images/level1/bg.png' },
* { src: 'images/level1/characters.json' }
* ]);
*
* // Assets will load sequentially in the background
* // The loader automatically pauses when high-priority loads occur
* // e.g. Assets.load() is called
* ```
* @remarks
* - Assets are loaded one at a time to minimize performance impact
* - Loading automatically pauses when Assets.load() is called
* - No progress tracking is available for background loading
* - Assets are cached as they complete loading
* @internal
*/
add(assetUrls: ResolvedAsset[]): void;
/**
* Loads the next set of assets. Will try to load as many assets as it can at the same time.
*
* The max assets it will try to load at one time will be 4.
*/
private _next;
/**
* Controls the active state of the background loader. When active, the loader will
* continue processing its queue. When inactive, loading is paused.
* @returns Whether the background loader is currently active
* @example
* ```ts
* // Pause background loading
* backgroundLoader.active = false;
*
* // Resume background loading
* backgroundLoader.active = true;
*
* // Check current state
* console.log(backgroundLoader.active); // true/false
*
* // Common use case: Pause during intensive operations
* backgroundLoader.active = false; // Pause background loading
* ... // Perform high-priority tasks
* backgroundLoader.active = true; // Resume background loading
* ```
* @remarks
* - Setting to true resumes loading immediately
* - Setting to false pauses after current asset completes
* - Background loading is automatically paused during `Assets.load()`
* - Assets already being loaded will complete even when set to false
*/
get active(): boolean;
set active(value: boolean);
}
/**
* Returns an object of textures from an array of textures to be cached
* @category assets
* @internal
*/
export declare const cacheTextureArray: CacheParser<Texture[]>;
/**
* Detects if the browser supports the AVIF image format.
* @category assets
* @internal
*/
export declare const detectAvif: FormatDetectionParser;
/**
* Adds some default image formats to the detection parser
* @category assets
* @internal
*/
export declare const detectDefaults: FormatDetectionParser;
/**
* Detects if the browser supports the MP4 video format.
* @category assets
* @internal
*/
export declare const detectMp4: FormatDetectionParser;
/**
* Detects if the browser supports the OGV video format.
* @category assets
* @internal
*/
export declare const detectOgv: FormatDetectionParser;
/**
* Detects if the browser supports the WebM video format.
* @category assets
* @internal
*/
export declare const detectWebm: FormatDetectionParser;
/**
* Detects if the browser supports the WebP image format.
* @category assets
* @internal
*/
export declare const detectWebp: FormatDetectionParser;
/**
* @param imageData
* @internal
*/
export declare function testImageFormat(imageData: string): Promise<boolean>;
/**
* @param mimeType
* @internal
*/
export declare function testVideoFormat(mimeType: string): boolean;
/**
* A simple loader plugin for loading json data
* @category assets
* @advanced
*/
export declare const loadJson: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string): Promise<T>;
};
/**
* A simple loader plugin for loading text data
* @category assets
* @advanced
*/
export declare const loadTxt: {
/** used for deprecation purposes */
name: string;
id: string;
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
test(url: string): boolean;
load<T>(url: string): Promise<string>;
};
/**
* Cache for font faces
* @internal
*/
export interface FontFaceCache {
entries: {
url: string;
faces: FontFace[];
}[];
}
/**
* Data for loading a font
* @category assets
* @advanced
*/
export type LoadFontData = {
/** Font family name */
family: string;
/** A set of optional descriptors passed as an object. It can contain any of the descriptors available for @font-face: */
display: 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.
*/
featureSettings: string;
/** The stretch property of the FontFace interface retrieves or sets how the font stretches. */
stretch: string;
/** The style property of the FontFace interface retrieves or sets the font's style. */
style: string;
/**
* The unicodeRange property of the FontFace interface retrieves or sets the range of
* unicode code points encompassing the font.
*/
unicodeRange: string;
/** The variant property of the FontFace interface programmatically retrieves or sets font variant values. */
variant: string;
/** The weight property of the FontFace interface retrieves or sets the weight of the font. */
weights: string[];
};
/**
* Return font face name from a file name
* Ex.: 'fonts/titan-one.woff' turns into 'Titan One'
* @param url - File url
* @category assets
* @internal
*/
export declare function getFontFamilyName(url: string): string;
/**
* 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'],
* }
* })
* @category assets
* @advanced
*/
export declare const loadWebFont: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string, options?: ResolvedAsset<LoadFontData>): Promise<FontFace | FontFace[]>;
unload(font: FontFace | FontFace[]): void;
};
/**
* Set cross origin based detecting the url and the crossorigin
* @param element - Element to apply crossOrigin
* @param url - URL to check
* @param crossorigin - Cross origin value to use
* @category assets
* @advanced
*/
export declare function crossOrigin(element: ImageLike | HTMLVideoElement, url: string, crossorigin?: boolean | string): void;
/**
* Preload a video element
* @param element - Video element to preload
* @internal
*/
export declare function preloadVideo(element: HTMLVideoElement): Promise<void>;
/**
* Sets the `crossOrigin` property for this resource based on if the url
* for this resource is cross-origin. If crossOrigin was manually set, this
* function does nothing.
* Nipped from the resource loader!
* @ignore
* @param url - The url to test.
* @param {object} [loc=window.location] - The location object to test against.
* @returns The crossOrigin value to use (or empty string for none).
* @category assets
*/
export declare function determineCrossOrigin(url: string, loc?: Location): string;
type LoadVideoData = VideoSourceOptions & {
mime?: string;
};
/**
* 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 Assets.load().
* ```js
* // Set the data
* const texture = await Assets.load({
* src: './assets/city.mp4',
* data: {
* preload: true,
* autoPlay: true,
* },
* });
* ```
* @category assets
* @advanced
*/
export declare const loadVideoTextures: {
/** used for deprecation purposes */
name: string;
id: string;
extension: {
type: ExtensionType.LoadParser;
name: string;
};
test(url: string): boolean;
load<T>(url: string, asset: ResolvedAsset<LoadVideoData>, loader: Loader): Promise<Texture>;
unload(texture: Texture): void;
};
/**
* Creates a texture from a source and adds it to the cache.
* @param source - source of the texture
* @param loader - loader
* @param url - url of the texture
* @ignore
*/
export declare function createTexture(source: TextureSource, loader: Loader, url: string): Texture<TextureSource<any>>;
declare class WorkerManagerClass {
/**
* Hash map storing resolve/reject functions for pending worker requests.
* Keyed by UUID to match responses with their corresponding promises.
*/
private _resolveHash;
/** Pool of available workers ready for use */
private readonly _workerPool;
/** Queue of pending work items waiting for available workers */
private readonly _queue;
/** Whether the worker manager has been initialized */
private _initialized;
/** Current number of created workers (used to enforce MAX_WORKERS limit) */
private _createdWorkers;
/** Cached promise for ImageBitmap support check */
private _isImageBitmapSupported?;
constructor();
/**
* Checks if ImageBitmap is supported in the current environment.
*
* This method uses a dedicated worker to test ImageBitmap support
* and caches the result for subsequent calls.
* @returns Promise that resolves to true if ImageBitmap is supported, false otherwise
*/
isImageBitmapSupported(): Promise<boolean>;
/**
* Loads an image as an ImageBitmap using a web worker.
* @param src - The source URL or path of the image to load
* @param asset - Optional resolved asset containing additional texture source options
* @returns Promise that resolves to the loaded ImageBitmap
* @example
* ```typescript
* const bitmap = await WorkerManager.loadImageBitmap('image.png');
* const bitmapWithOptions = await WorkerManager.loadImageBitmap('image.png', asset);
* ```
*/
loadImageBitmap(src: string, asset?: ResolvedAsset<TextureSourceOptions<any>>): Promise<ImageBitmap>;
/**
* Initializes the worker pool if not already initialized.
* Currently a no-op but reserved for future initialization logic.
*/
private _initWorkers;
/**
* Gets an available worker from the pool or creates a new one if needed.
*
* Workers are created up to the MAX_WORKERS limit (based on navigator.hardwareConcurrency).
* Each worker is configured with a message handler for processing results.
* @returns Available worker or undefined if pool is at capacity and no workers are free
*/
private _getWorker;
/**
* Returns a worker to the pool after completing a task.
* @param worker - The worker to return to the pool
*/
private _returnWorker;
/**
* Handles completion of a worker task by resolving or rejecting the corresponding promise.
* @param data - Result data from the worker containing uuid, data, and optional error
*/
private _complete;
/**
* Executes a task using the worker pool system.
*
* Queues the task and processes it when a worker becomes available.
* @param id - Identifier for the type of task to run
* @param args - Arguments to pass to the worker
* @returns Promise that resolves with the worker's result
*/
private _run;
/**
* Processes the next item in the queue if workers are available.
*
* This method is called after worker initialization and when workers
* complete tasks to continue processing the queue.
*/
private _next;
/**
* Resets the worker manager, terminating all workers and clearing the queue.
*
* This method:
* - Terminates all active workers
* - Rejects all pending promises with an error
* - Clears all internal state
* - Resets initialization flags
*
* This should be called when the worker manager is no longer needed
* to prevent memory leaks and ensure proper cleanup.
* @example
* ```typescript
* // Clean up when shutting down
* WorkerManager.reset();
* ```
*/
reset(): void;
}
/**
* Manages a pool of web workers for loading ImageBitmap objects asynchronously.
*
* This class provides a thread-safe way to load images using web workers,
* automatically managing worker creation, pooling, and cleanup. It supports
* checking ImageBitmap support and queuing multiple load requests.
*
* > [!IMPORTANT] You should not need to use this class directly
* > However, you can call `WorkerManager.reset()` to clean up all workers when they are no longer needed.
* @category Assets
* @advanced
*/
export declare const WorkerManager: WorkerManagerClass;
/**
* A parser that will resolve a json urls resolution for spritesheets
* e.g. `assets/spritesheet@1x.json`
* @category assets
* @internal
*/
export declare const resolveJsonUrl: {
extension: {
type: ExtensionType.ResolveParser;
priority: number;
name: string;
};
test: (value: string) => boolean;
parse: (value: string) => {
resolution: number;
format: string;
src: string;
};
};
/**
* A parser that will resolve a texture url
* @category assets
* @internal
*/
export declare const resolveTextureUrl: {
extension: {
type: ExtensionType.ResolveParser;
name: string;
};
test: (url: string, resolvedAsset?: ResolvedAsset<TextureSourceOptions<any>>, loader?: Loader) => boolean;
parse: (value: string) => {
resolution: number;
format: string;
src: string;
};
};
/**
* @param url
* @param mimes
* @internal
*/
export declare function checkDataUrl(url: string, mimes: string | string[]): boolean;
/**
* @param url
* @param extension
* @internal
*/
export declare function checkExtension(url: string, extension: string | string[]): boolean;
/**
* @param input
* @param transform
* @param forceTransform
* @internal
*/
export declare const convertToList: <T>(input: string | T | (string | T)[], transform?: (input: string) => T, forceTransform?: boolean) => T[];
/**
* Copies the search params from one url to another
* @param targetUrl - the url to copy the search params to
* @param sourceUrl - the url container the search params we want to copy
* @returns the url with the search params copied
* @internal
*/
export declare const copySearchParams: (targetUrl: string, sourceUrl: string) => string;
/**
* Creates a list of all possible combinations of the given strings.
* @example
* const out2 = createStringVariations('name is {chicken,wolf,sheep}');
* console.log(out2); // [ 'name is chicken', 'name is wolf', 'name is sheep' ]
* @param string - The string to process
* @internal
*/
export declare function createStringVariations(string: string): string[];
/**
* Checks if the given value is an array.
* @param item - The item to test
* @internal
*/
export declare const isSingleItem: (item: unknown) => boolean;
/**
* Detects if Basis textures are supported by the browser.
* This is done by checking if WebGL or WebGPU is supported.
* If either is supported, Basis textures can be used.
* @category assets
* @internal
*/
export declare const detectBasis: FormatDetectionParser;
/**
* Loads Basis textures using a web worker.
* @category assets
* @advanced
*/
export declare const loadBasis: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string, _asset: ResolvedAsset, loader: Loader): Promise<Texture | Texture[]>;
unload(texture: Texture | Texture[]): void;
};
/** @internal */
export type BASISModuleCreator = (config: {
locateFile: (file: string) => string;
}) => {
then: (result: (libktx: BASISModule) => void) => void;
};
/** @internal */
export type BasisTextureConstructor = new (data: Uint8Array) => BasisTexture;
/** @internal */
export interface BASISModule {
initializeBasis(): void;
BasisFile: BasisTextureConstructor;
}
/** @internal */
export interface BasisTexture {
getNumImages(): number;
getNumLevels(imageIndex: number): number;
startTranscoding(): boolean;
getImageWidth(imageIndex: number, levelIndex: number): number;
getImageHeight(imageIndex: number, levelIndex: number): number;
getImageTranscodedSizeInBytes(imageIndex: number, levelIndex: number, format: number): number;
transcodeImage(buffer: Uint8Array, imageIndex: number, levelIndex: number, format: number, unused: number, getAlphaForOpaqueFormats: number): boolean;
}
/**
* @param basisTexture
* @param basisTranscoderFormat
* @internal
*/
export declare function createLevelBuffers(basisTexture: BasisTexture, basisTranscoderFormat: number): Uint8Array[];
/**
* @param transcoderFormat
* @internal
*/
export declare function gpuFormatToBasisTranscoderFormat(transcoderFormat: string): number;
/**
* The urls for the Basis transcoder files.
* These can be set to custom paths if needed.
* @category assets
* @advanced
*/
export declare const basisTranscoderUrls: {
jsUrl: string;
wasmUrl: string;
};
/**
* Sets the Basis transcoder paths.
* This allows you to override the default paths for the Basis transcoder files.
* @param config - The configuration object containing the new paths.
* @category assets
* @advanced
*/
export declare function setBasisTranscoderPath(config: Partial<typeof basisTranscoderUrls>): void;
/**
* @param url
* @param supportedTextures
* @internal
*/
export declare function loadBasisOnWorker(url: string, supportedTextures: TEXTURE_FORMATS[]): Promise<TextureSourceOptions>;
/**
* @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format
* This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining
* ones to their correct value)
* @ignore
*/
export declare enum DXGI_FORMAT {
DXGI_FORMAT_UNKNOWN = 0,
DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
DXGI_FORMAT_R32G32B32A32_UINT = 3,
DXGI_FORMAT_R32G32B32A32_SINT = 4,
DXGI_FORMAT_R32G32B32_TYPELESS = 5,
DXGI_FORMAT_R32G32B32_FLOAT = 6,
DXGI_FORMAT_R32G32B32_UINT = 7,
DXGI_FORMAT_R32G32B32_SINT = 8,
DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
DXGI_FORMAT_R16G16B16A16_UNORM = 11,
DXGI_FORMAT_R16G16B16A16_UINT = 12,
DXGI_FORMAT_R16G16B16A16_SNORM = 13,
DXGI_FORMAT_R16G16B16A16_SINT = 14,
DXGI_FORMAT_R32G32_TYPELESS = 15,
DXGI_FORMAT_R32G32_FLOAT = 16,
DXGI_FORMAT_R32G32_UINT = 17,
DXGI_FORMAT_R32G32_SINT = 18,
DXGI_FORMAT_R32G8X24_TYPELESS = 19,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
DXGI_FORMAT_R10G10B10A2_UNORM = 24,
DXGI_FORMAT_R10G10B10A2_UINT = 25,
DXGI_FORMAT_R11G11B10_FLOAT = 26,
DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
DXGI_FORMAT_R8G8B8A8_UNORM = 28,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
DXGI_FORMAT_R8G8B8A8_UINT = 30,
DXGI_FORMAT_R8G8B8A8_SNORM = 31,
DXGI_FORMAT_R8G8B8A8_SINT = 32,
DXGI_FORMAT_R16G16_TYPELESS = 33,
DXGI_FORMAT_R16G16_FLOAT = 34,
DXGI_FORMAT_R16G16_UNORM = 35,
DXGI_FORMAT_R16G16_UINT = 36,
DXGI_FORMAT_R16G16_SNORM = 37,
DXGI_FORMAT_R16G16_SINT = 38,
DXGI_FORMAT_R32_TYPELESS = 39,
DXGI_FORMAT_D32_FLOAT = 40,
DXGI_FORMAT_R32_FLOAT = 41,
DXGI_FORMAT_R32_UINT = 42,
DXGI_FORMAT_R32_SINT = 43,
DXGI_FORMAT_R24G8_TYPELESS = 44,
DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
DXGI_FORMAT_R8G8_TYPELESS = 48,
DXGI_FORMAT_R8G8_UNORM = 49,
DXGI_FORMAT_R8G8_UINT = 50,
DXGI_FORMAT_R8G8_SNORM = 51,
DXGI_FORMAT_R8G8_SINT = 52,
DXGI_FORMAT_R16_TYPELESS = 53,
DXGI_FORMAT_R16_FLOAT = 54,
DXGI_FORMAT_D16_UNORM = 55,
DXGI_FORMAT_R16_UNORM = 56,
DXGI_FORMAT_R16_UINT = 57,
DXGI_FORMAT_R16_SNORM = 58,
DXGI_FORMAT_R16_SINT = 59,
DXGI_FORMAT_R8_TYPELESS = 60,
DXGI_FORMAT_R8_UNORM = 61,
DXGI_FORMAT_R8_UINT = 62,
DXGI_FORMAT_R8_SNORM = 63,
DXGI_FORMAT_R8_SINT = 64,
DXGI_FORMAT_A8_UNORM = 65,
DXGI_FORMAT_R1_UNORM = 66,
DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
DXGI_FORMAT_BC1_TYPELESS = 70,
DXGI_FORMAT_BC1_UNORM = 71,
DXGI_FORMAT_BC1_UNORM_SRGB = 72,
DXGI_FORMAT_BC2_TYPELESS = 73,
DXGI_FORMAT_BC2_UNORM = 74,
DXGI_FORMAT_BC2_UNORM_SRGB = 75,
DXGI_FORMAT_BC3_TYPELESS = 76,
DXGI_FORMAT_BC3_UNORM = 77,
DXGI_FORMAT_BC3_UNORM_SRGB = 78,
DXGI_FORMAT_BC4_TYPELESS = 79,
DXGI_FORMAT_BC4_UNORM = 80,
DXGI_FORMAT_BC4_SNORM = 81,
DXGI_FORMAT_BC5_TYPELESS = 82,
DXGI_FORMAT_BC5_UNORM = 83,
DXGI_FORMAT_BC5_SNORM = 84,
DXGI_FORMAT_B5G6R5_UNORM = 85,
DXGI_FORMAT_B5G5R5A1_UNORM = 86,
DXGI_FORMAT_B8G8R8A8_UNORM = 87,
DXGI_FORMAT_B8G8R8X8_UNORM = 88,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89,
DXGI_FORMAT_B8G8R8A8_TYPELESS = 90,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91,
DXGI_FORMAT_B8G8R8X8_TYPELESS = 92,
DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93,
DXGI_FORMAT_BC6H_TYPELESS = 94,
DXGI_FORMAT_BC6H_UF16 = 95,
DXGI_FORMAT_BC6H_SF16 = 96,
DXGI_FORMAT_BC7_TYPELESS = 97,
DXGI_FORMAT_BC7_UNORM = 98,
DXGI_FORMAT_BC7_UNORM_SRGB = 99,
DXGI_FORMAT_AYUV = 100,
DXGI_FORMAT_Y410 = 101,
DXGI_FORMAT_Y416 = 102,
DXGI_FORMAT_NV12 = 103,
DXGI_FORMAT_P010 = 104,
DXGI_FORMAT_P016 = 105,
DXGI_FORMAT_420_OPAQUE = 106,
DXGI_FORMAT_YUY2 = 107,
DXGI_FORMAT_Y210 = 108,
DXGI_FORMAT_Y216 = 109,
DXGI_FORMAT_NV11 = 110,
DXGI_FORMAT_AI44 = 111,
DXGI_FORMAT_IA44 = 112,
DXGI_FORMAT_P8 = 113,
DXGI_FORMAT_A8P8 = 114,
DXGI_FORMAT_B4G4R4A4_UNORM = 115,
DXGI_FORMAT_P208 = 116,
DXGI_FORMAT_V208 = 117,
DXGI_FORMAT_V408 = 118,
DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 119,
DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 120,
DXGI_FORMAT_FORCE_UINT = 121
}
/**
* Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION}
* @ignore
*/
export declare enum D3D10_RESOURCE_DIMENSION {
DDS_DIMENSION_TEXTURE1D = 2,
DDS_DIMENSION_TEXTURE2D = 3,
DDS_DIMENSION_TEXTURE3D = 6
}
/**
* Four character codes for DXTn formats
* https://learn.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide
* https://learn.microsoft.com/en-us/windows/win32/direct3d9/d3dformat
* @internal
*/
export declare enum D3DFMT {
UNKNOWN = 0,
R8G8B8 = 20,
A8R8G8B8 = 21,
X8R8G8B8 = 22,
R5G6B5 = 23,
X1R5G5B5 = 24,
A1R5G5B5 = 25,
A4R4G4B4 = 26,
R3G3B2 = 27,
A8 = 28,
A8R3G3B2 = 29,
X4R4G4B4 = 30,
A2B10G10R10 = 31,
A8B8G8R8 = 32,
X8B8G8R8 = 33,
G16R16 = 34,
A2R10G10B10 = 35,
A16B16G16R16 = 36,
A8P8 = 40,
P8 = 41,
L8 = 50,
A8L8 = 51,
A4L4 = 52,
V8U8 = 60,
L6V5U5 = 61,
X8L8V8U8 = 62,
Q8W8V8U8 = 63,
V16U16 = 64,
A2W10V10U10 = 67,
Q16W16V16U16 = 110,
R16F = 111,
G16R16F = 112,
A16B16G16R16F = 113,
R32F = 114,
G32R32F = 115,
A32B32G32R32F = 116,
UYVY,
R8G8_B8G8,
YUY2,
D3DFMT_G8R8_G8B8,
DXT1,
DXT2,
DXT3,
DXT4,
DXT5,
ATI1,
AT1N,
ATI2,
AT2N,
BC4U,
BC4S,
BC5U,
BC5S,
DX10
}
/**
* Maps `FOURCC_*` formats to {@link TEXTURE_FORMATS}.
* https://en.wikipedia.org/wiki/S3_Texture_Compression#S3TC_format_comparison
* https://github.com/microsoft/DirectXTex/blob/main/DDSTextureLoader/DDSTextureLoader11.cpp
* @ignore
*/
export declare const FOURCC_TO_TEXTURE_FORMAT: {
[id: number]: TEXTURE_FORMATS;
};
/**
* Maps {@link DXGI_FORMAT} to {@link TEXTURE_FORMATS}
* @ignore
*/
export declare const DXGI_TO_TEXTURE_FORMAT: {
[id: number]: TEXTURE_FORMATS;
};
/**
* Maps {@link DXGI_FORMAT} to {@link D3DFMT}
* @internal
*/
export declare const DDS: {
MAGIC_VALUE: number;
MAGIC_SIZE: number;
HEADER_SIZE: number;
HEADER_DX10_SIZE: number;
PIXEL_FORMAT_FLAGS: {
ALPHAPIXELS: number;
ALPHA: number;
FOURCC: number;
RGB: number;
RGBA: number;
YUV: number;
LUMINANCE: number;
LUMINANCEA: number;
};
RESOURCE_MISC_TEXTURECUBE: number;
HEADER_FIELDS: {
MAGIC: number;
SIZE: number;
FLAGS: number;
HEIGHT: number;
WIDTH: number;
MIPMAP_COUNT: number;
PIXEL_FORMAT: number;
PF_FLAGS: number;
FOURCC: number;
RGB_BITCOUNT: number;
R_BIT_MASK: number;
G_BIT_MASK: number;
B_BIT_MASK: number;
A_BIT_MASK: number;
};
HEADER_DX10_FIELDS: {
DXGI_FORMAT: number;
RESOURCE_DIMENSION: number;
MISC_FLAG: number;
ARRAY_SIZE: number;
MISC_FLAGS2: number;
};
DXGI_FORMAT: typeof DXGI_FORMAT;
D3D10_RESOURCE_DIMENSION: typeof D3D10_RESOURCE_DIMENSION;
D3DFMT: typeof D3DFMT;
};
/** @internal */
export declare const TEXTURE_FORMAT_BLOCK_SIZE: Record<string, number>;
/**
* Loads DDS textures.
* @category assets
* @advanced
*/
export declare const loadDDS: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string, _asset: ResolvedAsset, loader: Loader): Promise<Texture | Texture[]>;
unload(texture: Texture | Texture[]): void;
};
/**
* @param arrayBuffer
* @param supportedFormats
* @internal
*/
export declare function parseDDS(arrayBuffer: ArrayBuffer, supportedFormats: TEXTURE_FORMATS[]): TextureSourceOptions<Uint8Array[]>;
/**
* Loads KTX textures.
* @category assets
* @advanced
*/
export declare const loadKTX: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string, _asset: ResolvedAsset, loader: Loader): Promise<Texture | Texture[]>;
unload(texture: Texture | Texture[]): void;
};
/**
* @param arrayBuffer
* @param supportedFormats
* @internal
*/
export declare function parseKTX(arrayBuffer: ArrayBuffer, supportedFormats: TEXTURE_FORMATS[]): TextureSourceOptions<Uint8Array[]>;
/** @internal */
export declare enum GL_INTERNAL_FORMAT {
RGBA8_SNORM = 36759,
RGBA = 6408,
RGBA8UI = 36220,
SRGB8_ALPHA8 = 35907,
RGBA8I = 36238,
RGBA8 = 32856,
COMPRESSED_RGB_S3TC_DXT1_EXT = 33776,
COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777,
COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778,
COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779,
COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917,
COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918,
COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919,
COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916,
COMPRESSED_RED_RGTC1_EXT = 36283,
COMPRESSED_SIGNED_RED_RGTC1_EXT = 36284,
COMPRESSED_RED_GREEN_RGTC2_EXT = 36285,
COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 36286,
COMPRESSED_R11_EAC = 37488,
COMPRESSED_SIGNED_R11_EAC = 37489,
COMPRESSED_RG11_EAC = 37490,
COMPRESSED_SIGNED_RG11_EAC = 37491,
COMPRESSED_RGB8_ETC2 = 37492,
COMPRESSED_RGBA8_ETC2_EAC = 37496,
COMPRESSED_SRGB8_ETC2 = 37493,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495,
COMPRESSED_RGBA_ASTC_4x4_KHR = 37808,
COMPRESSED_RGBA_ASTC_5x4_KHR = 37809,
COMPRESSED_RGBA_ASTC_5x5_KHR = 37810,
COMPRESSED_RGBA_ASTC_6x5_KHR = 37811,
COMPRESSED_RGBA_ASTC_6x6_KHR = 37812,
COMPRESSED_RGBA_ASTC_8x5_KHR = 37813,
COMPRESSED_RGBA_ASTC_8x6_KHR = 37814,
COMPRESSED_RGBA_ASTC_8x8_KHR = 37815,
COMPRESSED_RGBA_ASTC_10x5_KHR = 37816,
COMPRESSED_RGBA_ASTC_10x6_KHR = 37817,
COMPRESSED_RGBA_ASTC_10x8_KHR = 37818,
COMPRESSED_RGBA_ASTC_10x10_KHR = 37819,
COMPRESSED_RGBA_ASTC_12x10_KHR = 37820,
COMPRESSED_RGBA_ASTC_12x12_KHR = 37821,
COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840,
COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 37841,
COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 37842,
COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 37843,
COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 37844,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 37845,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 37846,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 37847,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 37848,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 37849,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 37850,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 37851,
COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 37852,
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 37853,
COMPRESSED_RGBA_BPTC_UNORM_EXT = 36492,
COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 36493,
COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 36494,
COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 36495
}
/**
* The KTX file format constants.
* @internal
*/
export declare const KTX: {
FILE_HEADER_SIZE: number;
FILE_IDENTIFIER: number[];
FORMATS_TO_COMPONENTS: {
[id: number]: number;
};
INTERNAL_FORMAT_TO_BYTES_PER_PIXEL: {
[id: number]: number;
};
INTERNAL_FORMAT_TO_TEXTURE_FORMATS: {
[id: number]: TEXTURE_FORMATS;
};
FIELDS: {
FILE_IDENTIFIER: number;
ENDIANNESS: number;
GL_TYPE: number;
GL_TYPE_SIZE: number;
GL_FORMAT: number;
GL_INTERNAL_FORMAT: number;
GL_BASE_INTERNAL_FORMAT: number;
PIXEL_WIDTH: number;
PIXEL_HEIGHT: number;
PIXEL_DEPTH: number;
NUMBER_OF_ARRAY_ELEMENTS: number;
NUMBER_OF_FACES: number;
NUMBER_OF_MIPMAP_LEVELS: number;
BYTES_OF_KEY_VALUE_DATA: number;
};
TYPES_TO_BYTES_PER_COMPONENT: {
[id: number]: number;
};
TYPES_TO_BYTES_PER_PIXEL: {
[id: number]: number;
};
ENDIANNESS: number;
};
/**
* Loader parser for KTX2 textures.
* This parser loads KTX2 textures using a web worker for transcoding.
* It supports both single and multiple textures.
* @category assets
* @advanced
*/
export declare const loadKTX2: {
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
/** used for deprecation purposes */
name: string;
id: string;
test(url: string): boolean;
load<T>(url: string, _asset: ResolvedAsset, loader: Loader): Promise<Texture | Texture[]>;
unload(texture: Texture | Texture[]): Promise<void>;
};
/** @internal */
export type LIBKTXModuleCreator = (config: {
locateFile: (file: string) => string;
}) => {
then: (result: (libktx: LIBKTXModule) => void) => void;
};
/** @internal */
export interface KTXTexture {
getImageData(level: number, layer: number, face: number): Uint8Array;
glInternalformat: number;
vkFormat: number;
classId: number;
numLevels: number;
baseHeight: number;
baseWidth: number;
transcodeBasis(transcodeFormat: any, arg1: number): unknown;
needsTranscoding: boolean;
}
/** @internal */
export interface LIBKTXModule {
ErrorCode: any;
TranscodeTarget: any;
ktxTexture: new (data: Uint8Array) => KTXTexture;
}
/** @internal */
export type COMPRESSED_TEXTURE_FORMATS = TEXTURE_FORMATS | "rgb8unorm" | "rgb8unorm-srgb";
/**
* @param textureOptions
* @internal
*/
export declare function convertFormatIfRequired(textureOptions: TextureSourceOptions): void;
/**
* @param ktxTexture
* @internal
*/
export declare function createLevelBuffersFromKTX(ktxTexture: KTXTexture): Uint8Array[];
/**
* @param ktxTexture
* @internal
*/
export declare function getTextureFormatFromKTXTexture(ktxTexture: KTXTexture): COMPRESSED_TEXTURE_FORMATS;
/**
* @param glInternalFormat
* @internal
*/
export declare function glFormatToGPUFormat(glInternalFormat: number): COMPRESSED_TEXTURE_FORMATS;
/**
* @param transcoderFormat
* @internal
*/
export declare function gpuFormatToKTXBasisTranscoderFormat(transcoderFormat: string): string;
/**
* The urls for the KTX transcoder library.
* These can be set to custom paths if needed.
* @category assets
* @advanced
*/
export declare const ktxTranscoderUrls: {
jsUrl: string;
wasmUrl: string;
};
/**
* Sets the paths for the KTX transcoder library.
* @param config - Partial configuration object to set custom paths for the KTX transcoder.
* This allows you to override the default URLs for the KTX transcoder library.
* @category assets
* @advanced
*/
export declare function setKTXTranscoderPath(config: Partial<typeof ktxTranscoderUrls>): void;
/**
* @param vkFormat
* @internal
*/
export declare function vkFormatToGPUFormat(vkFormat: number): COMPRESSED_TEXTURE_FORMATS;
/**
* @param url
* @param supportedTextures
* @internal
*/
export declare function loadKTX2onWorker(url: string, supportedTextures: TEXTURE_FORMATS[]): Promise<TextureSourceOptions>;
/**
* Detects if the browser supports compressed texture formats.
* @category assets
* @internal
*/
export declare const detectCompressed: FormatDetectionParser;
/** @internal */
export declare const validFormats: string[];
/**
* A parser that will resolve a compressed texture url
* @category assets
* @internal
*/
export declare const resolveCompressedTextureUrl: {
extension: ExtensionType.ResolveParser;
test: (value: string) => boolean;
parse: (value: string) => {
resolution: number;
format: string;
src: string;
};
};
/**
* A rectangle-like object that contains x, y, width, and height properties.
* @example
* const rect = { x: 0, y: 0, width: 100, height: 100 };
* @category utils
* @advanced
*/
export type RectangleLike = {
x: number;
y: number;
width: number;
height: number;
};
/**
* The Culler class is responsible for managing and culling containers.
* Culling optimizes rendering performance by skipping objects outside the visible area.
*
* > [!IMPORTANT] culling is not always a golden bullet, it can be more expensive than rendering
* > objects that are not visible, so it is best used in scenarios where you have many objects
* > that are not visible at the same time, such as in large scenes or games with many sprites.
* @example
* ```ts
* import { Culler, Container, Rectangle } from 'pixi.js';
*
* // Create a culler and container
* const culler = new Culler();
* const stage = new Container();
*
* // Set up container with culling
* stage.cullable = true;
* stage.cullArea = new Rectangle(0, 0, 800, 600);
*
* // Add some sprites that will be culled
* for (let i = 0; i < 1000; i++) {
* const sprite = Sprite.from('texture.png');
* sprite.x = Math.random() * 2000;
* sprite.y = Math.random() * 2000;
* sprite.cullable = true;
* stage.addChild(sprite);
* }
*
* // Cull objects outside view
* culler.cull(stage, {
* x: 0,
* y: 0,
* width: 800,
* height: 600
* });
*
* // Only visible objects will be rendered
* renderer.render(stage);
* ```
* @see {@link CullerPlugin} For automatic culling in applications
* @see {@link CullingMixinConstructor} For culling properties
* @category scene
* @standard
*/
export declare class Culler {
/**
* Culls the children of a specific container based on the given view rectangle.
* This determines which objects should be rendered and which can be skipped.
* @param container - The container to cull. Must be a Container instance.
* @param view - The view rectangle that defines the visible area
* @param skipUpdateTransform - Whether to skip updating transforms for better performance
* @example
* ```ts
* // Basic culling with view bounds
* const culler = new Culler();
* culler.cull(stage, {
* x: 0,
* y: 0,
* width: 800,
* height: 600
* });
*
* // Culling to renderer screen
* culler.cull(stage, renderer.screen, false);
* ```
* @remarks
* - Recursively processes all cullable children
* - Uses cullArea if defined, otherwise calculates bounds
* - Performance depends on scene complexity
* @see {@link CullingMixinConstructor.cullable} For enabling culling on objects
* @see {@link CullingMixinConstructor.cullArea} For custom culling boundaries
*/
cull(container: Container, view: RectangleLike, skipUpdateTransform?: boolean): void;
private _cullRecursive;
/**
* A shared instance of the Culler class. Provides a global culler instance for convenience.
* @example
* ```ts
* // Use the shared instance instead of creating a new one
* Culler.shared.cull(stage, {
* x: 0,
* y: 0,
* width: 800,
* height: 600
* });
* ```
* @see {@link CullerPlugin} For automatic culling using this instance
*/
static shared: Culler;
}
/**
* CanvasObserver class synchronizes the DOM element's transform with the canvas size and position.
* It uses ResizeObserver for efficient updates and requestAnimationFrame for fallback.
* This ensures that the DOM element is always correctly positioned and scaled relative to the canvas.
* @internal
*/
export declare class CanvasObserver {
/** A cached value of the last transform applied to the DOM element. */
private _lastTransform;
/** A ResizeObserver instance to observe changes in the canvas size. */
private _observer;
/** The canvas element that this observer is associated with. */
private _canvas;
/** The DOM element that will be transformed based on the canvas size and position. */
private readonly _domElement;
/** The renderer instance that this observer is associated with. */
private readonly _renderer;
/** The last scale values applied to the DOM element, used to avoid unnecessary updates. */
private _lastScaleX;
/** The last scale values applied to the DOM element, used to avoid unnecessary updates. */
private _lastScaleY;
/** A flag to indicate whether the observer is attached to the Ticker for continuous updates. */
private _tickerAttached;
constructor(options: {
domElement: HTMLElement;
renderer: Renderer;
});
/** The canvas element that this CanvasObserver is associated with. */
get canvas(): HTMLCanvasElement;
/** Attaches the DOM element to the canvas parent if it is not already attached. */
ensureAttached(): void;
/**
* Updates the transform of the DOM element based on the canvas size and position.
* This method calculates the scale and translation needed to keep the DOM element in sync with the canvas.
*/
readonly updateTranslation: () => void;
/** Sets up a ResizeObserver if available. This ensures that the DOM element is kept in sync with the canvas size . */
private _attachObserver;
/** Destroys the CanvasObserver instance, cleaning up observers and Ticker. */
destroy(): void;
}
/**
* This interface describes all the DOM dependent calls that Pixi makes throughout its codebase.
* Implementations of this interface can be used to make sure Pixi will work in any environment,
* such as browser, Web Workers, and Node.js.
* @category environment
* @advanced
*/
export interface Adapter {
/** Returns a canvas object that can be used to create a webgl context. */
createCanvas: (width?: number, height?: number) => ICanvas;
/** Returns an IImage (HTMLImageElement) that can be used to create a texture. */
createImage: () => ImageLike;
/** Returns a 2D rendering context. */
getCanvasRenderingContext2D: () => {
prototype: ICanvasRenderingContext2D;
};
/** Returns a WebGL rendering context. */
getWebGLRenderingContext: () => typeof WebGLRenderingContext;
/** Returns a partial implementation of the browsers window.navigator */
getNavigator: () => {
userAgent: string;
gpu: GPU | null;
};
/** Returns the current base URL For browser environments this is either the document.baseURI or window.location.href */
getBaseUrl: () => string;
/** Return the font face set if available */
getFontFaceSet: () => FontFaceSet | null;
/** Returns a Response object that has been fetched from the given URL. */
fetch: (url: RequestInfo, options?: RequestInit) => Promise<Response>;
/** Returns Document object that has been parsed from the given XML string. */
parseXML: (xml: string) => Document;
}
/**
* The DOMAdapter is a singleton that allows PixiJS to perform DOM operations, such as creating a canvas.
* This allows PixiJS to be used in any environment, such as a web browser, Web Worker, or Node.js.
* It uses the {@link Adapter} interface to abstract away the differences between these environments
* and uses the {@link BrowserAdapter} by default.
*
* It has two methods: `get():Adapter` and `set(adapter: Adapter)`.
*
* Defaults to the {@link BrowserAdapter}.
* @example
* import { DOMAdapter, WebWorkerAdapter } from 'pixi.js';
*
* // WebWorkerAdapter is an implementation of the Adapter interface
* DOMAdapter.set(WebWorkerAdapter);
*
* // use the adapter to create a canvas (in this case an OffscreenCanvas)
* DOMAdapter.get().createCanvas(800, 600);
* @category environment
* @advanced
*/
export declare const DOMAdapter: {
/**
* Returns the current adapter.
* @returns {environment.Adapter} The current adapter.
*/
get(): Adapter;
/**
* Sets the current adapter.
* @param adapter - The new adapter.
*/
set(adapter: Adapter): void;
};
/**
* Automatically detects the environment and loads the appropriate extensions.
* @param skip - whether to skip loading the default extensions
* @category environment
* @advanced
*/
export declare function loadEnvironmentExtensions(skip: boolean): Promise<void>;
/**
* @param add - whether to add the default imports to the bundle
* @deprecated since 8.1.6. Use `loadEnvironmentExtensions` instead
* @category environment
* @advanced
*/
export declare function autoDetectEnvironment(add: boolean): Promise<void>;
/**
* This is an implementation of the {@link Adapter} interface.
* It can be used to make Pixi work in the browser.
* @category environment
* @property {Function} createCanvas - Creates a canvas element of the given size.
* This canvas is created using the browser's native canvas element.
* @property {Function} getCanvasRenderingContext2D - Returns a 2D rendering context.
* @property {Function} getWebGLRenderingContext - Returns a WebGL rendering context.
* @property {Function} getNavigator - Returns browsers window.navigator
* @property {Function} getBaseUrl - Returns the current base URL for browser environments this is either
* the document.baseURI or window.location.href
* @property {Function} getFontFaceSet - Return the font face set if available
* @property {Function} fetch - Returns a Response object that has been fetched from the given URL.
* @property {Function} parseXML - Returns Document object that has been parsed from the given XML string.
* @advanced
*/
export declare const BrowserAdapter: Adapter;
/**
* Extension for the browser environment.
* @category environment
* @internal
*/
export declare const browserExt: {
extension: {
type: ExtensionType;
name: string;
priority: number;
};
test: () => boolean;
load: () => Promise<void>;
};
/**
* This is an implementation of the {@link Adapter} interface.
* It can be used to make Pixi work in a Web Worker.
* @category environment
* @property {Function} createCanvas - Creates a canvas element of the given size using the browser's native OffscreenCanvas.
* @property {Function} getCanvasRenderingContext2D - Returns a 2D rendering context.
* @property {Function} getWebGLRenderingContext - Returns a WebGL rendering context.
* @property {Function} getNavigator - Returns browsers window.navigator
* @property {Function} getBaseUrl - Returns the current base URL of the worker, which is globalThis.location.href
* @property {Function} getFontFaceSet - Return the font face set if available
* @property {Function} fetch - Returns a Response object that has been fetched from the given URL.
* @property {Function} parseXML - Returns Document object that has been parsed from the given XML string.
* @category environment
* @advanced
*/
export declare const WebWorkerAdapter: Adapter;
/**
* Extension for the webworker environment.
* @category environment
* @internal
*/
export declare const webworkerExt: {
extension: {
type: ExtensionType;
name: string;
priority: number;
};
test: () => boolean;
load: () => Promise<void>;
};
/**
* A simplified shape of an interactive object for the `eventTarget` property of a {@link FederatedEvent}
* @category events
* @deprecated since 8.1.4
* @internal
*/
export interface FederatedEventTarget extends EventEmitter, EventTarget, Required<FederatedOptions> {
/** The parent of this event target. */
readonly parent?: FederatedEventTarget;
/** The children of this event target. */
readonly children?: ReadonlyArray<FederatedEventTarget>;
_internalEventMode: EventMode;
/** Returns true if the Container has interactive 'static' or 'dynamic' */
isInteractive: () => boolean;
/** Remove all listeners, or those of the specified event. */
removeAllListeners(event?: string | symbol): this;
}
declare class EventsTickerClass {
/** The event system. */
events: EventSystem;
/** The DOM element to listen to events on. */
domElement: HTMLElement;
/** The frequency that fake events will be fired. */
interactionFrequency: number;
private _deltaTime;
private _didMove;
private _tickerAdded;
private _pauseUpdate;
/**
* Initializes the event ticker.
* @param events - The event system.
*/
init(events: EventSystem): void;
/** Whether to pause the update checks or not. */
get pauseUpdate(): boolean;
set pauseUpdate(paused: boolean);
/** Adds the ticker listener. */
addTickerListener(): void;
/** Removes the ticker listener. */
removeTickerListener(): void;
/** Sets flag to not fire extra events when the user has already moved there mouse */
pointerMoved(): void;
/** Updates the state of interactive objects. */
private _update;
/**
* Updates the state of interactive objects if at least {@link interactionFrequency}
* milliseconds have passed since the last invocation.
*
* Invoked by a throttled ticker update from {@link Ticker.system}.
* @param ticker - The throttled ticker.
*/
private _tickerUpdate;
/** Destroys the event ticker. */
destroy(): void;
}
/**
* This class handles automatic firing of PointerEvents
* in the case where the pointer is stationary for too long.
* This is to ensure that hit-tests are still run on moving objects.
* @since 7.2.0
* @category events
* @class
* @advanced
*/
export declare const EventsTicker: EventsTickerClass;
/**
* A helper object containing the hsl shader code for both glsl
* @internal
*/
export declare const hslgl = "\n\tfloat getLuminosity(vec3 c) {\n\t\treturn 0.3 * c.r + 0.59 * c.g + 0.11 * c.b;\n\t}\n\n\tvec3 setLuminosity(vec3 c, float lum) {\n\t\tfloat modLum = lum - getLuminosity(c);\n\t\tvec3 color = c.rgb + vec3(modLum);\n\n\t\t// clip back into legal range\n\t\tmodLum = getLuminosity(color);\n\t\tvec3 modLumVec = vec3(modLum);\n\n\t\tfloat cMin = min(color.r, min(color.g, color.b));\n\t\tfloat cMax = max(color.r, max(color.g, color.b));\n\n\t\tif(cMin < 0.0) {\n\t\t\tcolor = mix(modLumVec, color, modLum / (modLum - cMin));\n\t\t}\n\n\t\tif(cMax > 1.0) {\n\t\t\tcolor = mix(modLumVec, color, (1.0 - modLum) / (cMax - modLum));\n\t\t}\n\n\t\treturn color;\n\t}\n\n\tfloat getSaturation(vec3 c) {\n\t\treturn max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b));\n\t}\n\n\tvec3 setSaturationMinMidMax(vec3 cSorted, float s) {\n\t\tvec3 colorSorted = cSorted;\n\n\t\tif(colorSorted.z > colorSorted.x) {\n\t\t\tcolorSorted.y = (((colorSorted.y - colorSorted.x) * s) / (colorSorted.z - colorSorted.x));\n\t\t\tcolorSorted.z = s;\n\t\t}\n\t\telse {\n\t\t\tcolorSorted.y = 0.0;\n\t\t\tcolorSorted.z = 0.0;\n\t\t}\n\n\t\tcolorSorted.x = 0.0;\n\n\t\treturn colorSorted;\n\t}\n\n\tvec3 setSaturation(vec3 c, float s) {\n\t\tvec3 color = c;\n\n\t\tif(color.r <= color.g && color.r <= color.b) {\n\t\t\tif(color.g <= color.b) {\n\t\t\t\tcolor = setSaturationMinMidMax(color.rgb, s).rgb;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcolor = setSaturationMinMidMax(color.rbg, s).rbg;\n\t\t\t}\n\t\t}\n\t\telse if(color.g <= color.r && color.g <= color.b) {\n\t\t\tif(color.r <= color.b) {\n\t\t\t\tcolor = setSaturationMinMidMax(color.grb, s).grb;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcolor = setSaturationMinMidMax(color.gbr, s).gbr;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// Using bgr for both fixes part of hue\n\t\t\tif(color.r <= color.g) {\n\t\t\t\tcolor = setSaturationMinMidMax(color.brg, s).brg;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcolor = setSaturationMinMidMax(color.bgr, s).bgr;\n\t\t\t}\n\t\t}\n\n\t\treturn color;\n\t}\n ";
/**
* A helper object containing the hsl shader code for wgsl
* @internal
*/
export declare const hslgpu = "\n\tfn getLuminosity(c: vec3<f32>) -> f32\n\t{\n\t\treturn 0.3*c.r + 0.59*c.g + 0.11*c.b;\n\t}\n\n\tfn setLuminosity(c: vec3<f32>, lum: f32) -> vec3<f32>\n\t{\n\t\tvar modLum: f32 = lum - getLuminosity(c);\n\t\tvar color: vec3<f32> = c.rgb + modLum;\n\n\t\t// clip back into legal range\n\t\tmodLum = getLuminosity(color);\n\t\tlet modLumVec = vec3<f32>(modLum);\n\n\t\tlet cMin: f32 = min(color.r, min(color.g, color.b));\n\t\tlet cMax: f32 = max(color.r, max(color.g, color.b));\n\n\t\tif(cMin < 0.0)\n\t\t{\n\t\t\tcolor = mix(modLumVec, color, modLum / (modLum - cMin));\n\t\t}\n\n\t\tif(cMax > 1.0)\n\t\t{\n\t\t\tcolor = mix(modLumVec, color, (1 - modLum) / (cMax - modLum));\n\t\t}\n\n\t\treturn color;\n\t}\n\n\tfn getSaturation(c: vec3<f32>) -> f32\n\t{\n\t\treturn max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b));\n\t}\n\n\tfn setSaturationMinMidMax(cSorted: vec3<f32>, s: f32) -> vec3<f32>\n\t{\n\t\tvar colorSorted = cSorted;\n\n\t\tif(colorSorted.z > colorSorted.x)\n\t\t{\n\t\t\tcolorSorted.y = (((colorSorted.y - colorSorted.x) * s) / (colorSorted.z - colorSorted.x));\n\t\t\tcolorSorted.z = s;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcolorSorted.y = 0;\n\t\t\tcolorSorted.z = 0;\n\t\t}\n\n\t\tcolorSorted.x = 0;\n\n\t\treturn colorSorted;\n\t}\n\n\tfn setSaturation(c: vec3<f32>, s: f32) -> vec3<f32>\n\t{\n\t\tvar color = c;\n\n\t\tif (color.r <= color.g && color.r <= color.b)\n\t\t{\n\t\t\tif (color.g <= color.b)\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.rgb, s)).rgb;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.rbg, s)).rbg;\n\t\t\t}\n\t\t}\n\t\telse if (color.g <= color.r && color.g <= color.b)\n\t\t{\n\t\t\tif (color.r <= color.b)\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.grb, s)).grb;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.gbr, s)).gbr;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Using bgr for both fixes part of hue\n\t\t\tif (color.r <= color.g)\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.brg, s)).brg;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcolor = vec3<f32>(setSaturationMinMidMax(color.bgr, s)).bgr;\n\t\t\t}\n\t\t}\n\n\t\treturn color;\n\t}\n\t";
/**
* Options for AlphaFilter
* @category filters
* @standard
*/
export interface AlphaFilterOptions extends FilterOptions {
/**
* Amount of alpha from 0 to 1, where 0 is transparent
* @default 1
*/
alpha: number;
}
/**
* Simplest filter - applies alpha.
*
* Use this instead of Container's alpha property to avoid visual layering of individual elements.
* AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains.
* If elements are not opaque, they will blend with each other anyway.
*
* Very handy if you want to use common features of all filters:
*
* 1. Assign a blendMode to this filter, blend all elements inside display object with background.
*
* 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter.
* @category filters
* @standard
* @noInheritDoc
* @example
* import { AlphaFilter } from 'pixi.js';
*
* const filter = new AlphaFilter({ alpha: 0.5 });
* sprite.filters = filter;
*
* // update alpha
* filter.alpha = 0.8;
*/
export declare class AlphaFilter extends Filter {
/**
* Default options for the AlphaFilter.
* @example
* ```ts
* AlphaFilter.defaultOptions = {
* alpha: 0.5, // Default alpha value
* };
* // Use default options
* const filter = new AlphaFilter(); // Uses default alpha of 0.5
* ```
*/
static defaultOptions: AlphaFilterOptions;
constructor(options?: AlphaFilterOptions);
/**
* The alpha value of the filter.
* Controls the transparency of the filtered display object.
* @example
* ```ts
* // Create filter with initial alpha
* const filter = new AlphaFilter({ alpha: 0.5 });
*
* // Update alpha value dynamically
* filter.alpha = 0.8;
* ```
* @default 1
* @remarks
* - 0 = fully transparent
* - 1 = fully opaque
* - Values are clamped between 0 and 1
*/
get alpha(): number;
set alpha(value: number);
}
/**
* Options for BlurFilterPass
* @category filters
* @internal
*/
export interface BlurFilterPassOptions extends BlurFilterOptions {
/** Do pass along the x-axis (`true`) or y-axis (`false`). */
horizontal: boolean;
}
/**
* The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object.
* @category filters
* @advanced
* @example
* import { BlurFilterPass } from 'pixi.js';
*
* const filter = new BlurFilterPass({ horizontal: true, strength: 8 });
* sprite.filters = filter;
*
* // update blur
* filter.blur = 16;
*/
export declare class BlurFilterPass extends Filter {
/** Default blur filter pass options */
static defaultOptions: Partial<BlurFilterPassOptions>;
/** Do pass along the x-axis (`true`) or y-axis (`false`). */
horizontal: boolean;
/** The number of passes to run the filter. */
passes: number;
/** The strength of the blur filter. */
strength: number;
private _quality;
private readonly _uniforms;
/**
* @param options
* @param options.horizontal - Do pass along the x-axis (`true`) or y-axis (`false`).
* @param options.strength - The strength of the blur filter.
* @param options.quality - The quality of the blur filter.
* @param options.kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
*/
constructor(options: BlurFilterPassOptions);
/**
* Applies the filter.
* @param filterManager - The manager.
* @param input - The input target.
* @param output - The output target.
* @param clearMode - How to clear
*/
apply(filterManager: FilterSystem, input: Texture, output: RenderSurface, clearMode: boolean): void;
/**
* Sets the strength of both the blur.
* @default 16
*/
get blur(): number;
set blur(value: number);
/**
* Sets the quality of the blur by modifying the number of passes. More passes means higher
* quality blurring but the lower the performance.
* @default 4
*/
get quality(): number;
set quality(value: number);
}
/**
* Configuration options for the BlurFilter.
* Controls how the Gaussian blur effect is applied.
* @example
* ```ts
* // Basic blur with default values
* const filter = new BlurFilter();
*
* // Custom blur configuration
* const filter = new BlurFilter({
* strength: 8, // Overall blur strength
* quality: 4, // Higher quality = better blur
* kernelSize: 5 // Size of blur kernel
* });
*
* // Different horizontal/vertical blur
* const filter = new BlurFilter({
* strengthX: 4, // Horizontal blur only
* strengthY: 12, // Stronger vertical blur
* quality: 2 // Lower quality for better performance
* });
* ```
* @remarks
* - Higher quality values produce better blur but impact performance
* - KernelSize affects blur precision and performance
* - Strength values determine blur intensity
* @see {@link BlurFilter} The filter that uses these options
* @see {@link FilterOptions} Base filter options
* @category filters
* @standard
*/
export interface BlurFilterOptions extends FilterOptions {
/**
* The strength of the blur filter.
* Applied to both horizontal and vertical blur if strengthX/Y not set.
* @default 8
*/
strength?: number;
/**
* The horizontal strength of the blur.
* Overrides strength parameter for x-axis.
* @default 8
*/
strengthX?: number;
/**
* The vertical strength of the blur.
* Overrides strength parameter for y-axis.
* @default 8
*/
strengthY?: number;
/**
* The quality of the blur filter.
* Higher values mean better quality but slower performance.
* @default 4
*/
quality?: number;
/**
* The kernelSize of the blur filter.
* Larger values create more precise blur but impact performance.
* Options: 5, 7, 9, 11, 13, 15.
* @default 5
*/
kernelSize?: number;
}
/**
* The BlurFilter applies a Gaussian blur to an object.
* The strength of the blur can be set for the x-axis and y-axis separately.
* @example
* ```ts
* import { BlurFilter } from 'pixi.js';
*
* // Create with default settings
* const filter = new BlurFilter();
*
* // Create with custom settings
* const filter = new BlurFilter({
* strength: 8, // Overall blur strength
* quality: 4, // Blur quality (higher = better but slower)
* kernelSize: 5 // Size of blur kernel matrix
* });
*
* // Apply to a display object
* sprite.filters = [filter];
*
* // Update properties
* filter.strength = 10; // Set both X and Y blur
* filter.strengthX = 5; // Set only horizontal blur
* filter.strengthY = 15; // Set only vertical blur
* filter.quality = 2; // Adjust quality
*
* // Enable edge pixel clamping
* filter.repeatEdgePixels = true;
* ```
* @remarks
* - Higher quality values produce better blur but impact performance
* - Strength controls blur intensity independently for X and Y
* - Can be optimized using quality and kernelSize settings
* - Supports edge pixel clamping for special effects
* @see {@link BlurFilterPass} For single-direction blur
* @see {@link FilterOptions} For base filter options
* @category filters
* @standard
* @noInheritDoc
*/
export declare class BlurFilter extends Filter {
/**
* Default blur filter options
* @example
* ```ts
* // Set default options for all BlurFilters
* BlurFilter.defaultOptions = {
* strength: 10, // Default blur strength
* quality: 2, // Default blur quality
* kernelSize: 7 // Default kernel size
* };
* // Create a filter with these defaults
* const filter = new BlurFilter(); // Uses default options
* ```
* @remarks
* - These options are used when creating a new BlurFilter without specific parameters
* - Can be overridden by passing options to the constructor
* - Useful for setting global defaults for all blur filters in your application
* @see {@link BlurFilterOptions} For detailed options
* @see {@link BlurFilter} The filter that uses these options
*/
static defaultOptions: Partial<BlurFilterOptions>;
/**
* The horizontal blur filter
* @advanced
*/
blurXFilter: BlurFilterPass;
/**
* The vertical blur filter
* @advanced
*/
blurYFilter: BlurFilterPass;
private _repeatEdgePixels;
/**
* @param {filters.BlurFilterOptions} options - The options of the blur filter.
*/
constructor(options?: BlurFilterOptions);
/** @deprecated since 8.0.0 */
constructor(strength?: number, quality?: number, resolution?: number | null, kernelSize?: number);
/**
* Applies the filter.
* @param filterManager - The manager.
* @param input - The input target.
* @param output - The output target.
* @param clearMode - How to clear
* @advanced
*/
apply(filterManager: FilterSystem, input: Texture, output: RenderSurface, clearMode: boolean): void;
protected updatePadding(): void;
/**
* Sets the strength of both the blurX and blurY properties simultaneously.
* Controls the overall intensity of the Gaussian blur effect.
* @example
* ```ts
* // Set equal blur strength for both axes
* filter.strength = 8;
*
* // Will throw error if X and Y are different
* filter.strengthX = 4;
* filter.strengthY = 8;
* filter.strength; // Error: BlurFilter's strengthX and strengthY are different
* ```
* @default 8
* @throws {Error} If strengthX and strengthY are different values
*/
get strength(): number;
set strength(value: number);
/**
* Sets the number of passes for blur. More passes means higher quality blurring.
* Controls the precision and smoothness of the blur effect at the cost of performance.
* @example
* ```ts
* // High quality blur (slower)
* filter.quality = 8;
*
* // Low quality blur (faster)
* filter.quality = 2;
* ```
* @default 4
* @remarks Higher values produce better quality but impact performance
*/
get quality(): number;
set quality(value: number);
/**
* Sets the strength of horizontal blur.
* Controls the blur intensity along the x-axis independently.
* @example
* ```ts
* // Apply horizontal-only blur
* filter.strengthX = 8;
* filter.strengthY = 0;
*
* // Create motion blur effect
* filter.strengthX = 16;
* filter.strengthY = 2;
* ```
* @default 8
*/
get strengthX(): number;
set strengthX(value: number);
/**
* Sets the strength of the vertical blur.
* Controls the blur intensity along the y-axis independently.
* @example
* ```ts
* // Apply vertical-only blur
* filter.strengthX = 0;
* filter.strengthY = 8;
*
* // Create radial blur effect
* filter.strengthX = 8;
* filter.strengthY = 8;
* ```
* @default 8
*/
get strengthY(): number;
set strengthY(value: number);
/**
* Sets the strength of both the blurX and blurY properties simultaneously
* @default 2
* @deprecated since 8.3.0
* @see BlurFilter.strength
*/
get blur(): number;
set blur(value: number);
/**
* Sets the strength of the blurX property
* @default 2
* @deprecated since 8.3.0
* @see BlurFilter.strengthX
*/
get blurX(): number;
set blurX(value: number);
/**
* Sets the strength of the blurY property
* @default 2
* @deprecated since 8.3.0
* @see BlurFilter.strengthY
*/
get blurY(): number;
set blurY(value: number);
/**
* If set to true the edge of the target will be clamped
* @default false
*/
get repeatEdgePixels(): boolean;
set repeatEdgePixels(value: boolean);
}
interface IGAUSSIAN_VALUES {
[x: number]: number[];
}
/** @internal */
export declare const GAUSSIAN_VALUES: IGAUSSIAN_VALUES;
/**
* @internal
* @param kernelSize - The size of the kernel.
*/
export declare function generateBlurFragSource(kernelSize: number): string;
/**
* @internal
* @param horizontal - Whether to generate a horizontal or vertical blur program.
* @param kernelSize - The size of the kernel.
*/
export declare function generateBlurGlProgram(horizontal: boolean, kernelSize: number): GlProgram;
/**
* @internal
* @param kernelSize - The size of the kernel.
* @param x - Whether to generate a horizontal or vertical blur program.
*/
export declare function generateBlurVertSource(kernelSize: number, x: boolean): string;
/**
* @internal
* @param horizontal - Whether to generate a horizontal or vertical blur program.
* @param kernelSize - The size of the kernel.
*/
export declare function generateBlurProgram(horizontal: boolean, kernelSize: number): GpuProgram;
/**
* 5x4 matrix for transforming RGBA color and alpha
* @category filters
* @standard
*/
export type ColorMatrix = ArrayFixed<number, 20>;
/**
* The ColorMatrixFilter class lets you apply color transformations to display objects using a 5x4 matrix.
* The matrix transforms the RGBA color and alpha values of every pixel to produce a new set of values.
*
* The class provides convenient methods for common color adjustments like brightness, contrast, saturation,
* and various photo filter effects.
* @example
* ```js
* import { ColorMatrixFilter } from 'pixi.js';
*
* // Create a new color matrix filter
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply it to a container
* container.filters = [colorMatrix];
*
* // Adjust contrast
* colorMatrix.contrast(2);
*
* // Chain multiple effects
* colorMatrix
* .saturate(0.5) // 50% saturation
* .brightness(1.2) // 20% brighter
* .hue(90); // 90 degree hue rotation
* ```
*
* Common use cases:
* - Adjusting brightness, contrast, or saturation
* - Applying color tints or color grading
* - Creating photo filter effects (sepia, negative, etc.)
* - Converting to grayscale
* - Implementing dynamic day/night transitions
* @author Clément Chenebault <clement@goodboydigital.com>
* @category filters
* @standard
* @noInheritDoc
*/
export declare class ColorMatrixFilter extends Filter {
constructor(options?: FilterOptions);
/**
* Transforms current matrix and set the new one
* @param {number[]} matrix - 5x4 matrix
* @param multiply - if true, current matrix and matrix are multiplied. If false,
* just set the current matrix with matrix
*/
private _loadMatrix;
/**
* Multiplies two mat5's
* @private
* @param out - 5x4 matrix the receiving matrix
* @param a - 5x4 matrix the first operand
* @param b - 5x4 matrix the second operand
* @returns {number[]} 5x4 matrix
*/
private _multiply;
/**
* Create a Float32 Array and normalize the offset component to 0-1
* @param {number[]} matrix - 5x4 matrix
* @returns {number[]} 5x4 matrix with all values between 0-1
*/
private _colorMatrix;
/**
* Adjusts the brightness of a display object.
*
* The brightness adjustment works by multiplying the RGB channels by a scalar value while keeping
* the alpha channel unchanged. Values below 1 darken the image, while values above 1 brighten it.
* @param b - The brightness multiplier to apply. Values between 0-1 darken the image (0 being black),
* while values > 1 brighten it (2.0 would make it twice as bright)
* @param multiply - When true, the new matrix is multiplied with the current one instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* // Create a new color matrix filter
* const colorMatrix = new ColorMatrixFilter();
*
* // Darken the image to 50% brightness
* colorMatrix.brightness(0.5, false);
*
* // Chain with other effects by using multiply
* colorMatrix
* .brightness(1.2, true) // Brighten by 20%
* .saturate(1.1, true); // Increase saturation by 10%
* ```
*/
brightness(b: number, multiply: boolean): void;
/**
* Sets each channel on the diagonal of the color matrix to apply a color tint.
*
* This method provides a way to tint display objects using the color matrix filter, similar to
* the tint property available on Sprites and other display objects. The tint is applied by
* scaling the RGB channels of each pixel.
* @param color - The color to use for tinting, this can be any valid color source.
* @param multiply - When true, the new tint matrix is multiplied with the current matrix instead
* of replacing it. This allows for combining tints with other color effects.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply a red tint
* colorMatrix.tint(0xff0000);
*
* // Layer a green tint on top of existing effects
* colorMatrix.tint('green', true);
*
* // Chain with other color adjustments
* colorMatrix
* .tint('blue') // Blue tint
* .brightness(1.2, true) // Increase brightness
* ```
*/
tint(color: ColorSource, multiply?: boolean): void;
/**
* Converts the display object to greyscale by applying a weighted matrix transformation.
*
* The greyscale effect works by setting equal RGB values for each pixel based on the scale parameter,
* effectively removing color information while preserving luminance.
* @param scale - The intensity of the greyscale effect. Value between 0-1, where:
* - 0 produces black
* - 0.5 produces 50% grey
* - 1 produces white
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Convert to 50% grey
* colorMatrix.greyscale(0.5, false);
*
* // Chain with other effects
* colorMatrix
* .greyscale(0.6, true) // Add grey tint
* .brightness(1.2, true); // Brighten the result
* ```
*/
greyscale(scale: number, multiply: boolean): void;
/**
* Converts the display object to grayscale by applying a weighted matrix transformation.
*
* The grayscale effect works by setting equal RGB values for each pixel based on the scale parameter,
* effectively removing color information while preserving luminance.
* @param scale - The intensity of the grayscale effect. Value between 0-1, where:
* - 0 produces black
* - 0.5 produces 50% grey
* - 1 produces white
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Convert to 50% grey
* colorMatrix.grayscale(0.5, false);
*
* // Chain with other effects
* colorMatrix
* .grayscale(0.6, true) // Add grey tint
* .brightness(1.2, true); // Brighten the result
* ```
*/
grayscale(scale: number, multiply: boolean): void;
/**
* Converts the display object to pure black and white using a luminance-based threshold.
*
* This method applies a matrix transformation that removes all color information and reduces
* the image to just black and white values based on the luminance of each pixel. The transformation
* uses standard luminance weightings: 30% red, 60% green, and 10% blue.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Convert to black and white
* colorMatrix.blackAndWhite(false);
*
* // Chain with other effects
* colorMatrix
* .blackAndWhite(true) // Apply B&W effect
* .brightness(1.2, true); // Then increase brightness
* ```
*/
blackAndWhite(multiply: boolean): void;
/**
* Adjusts the hue of the display object by rotating the color values around the color wheel.
*
* This method uses an optimized matrix transformation that accurately rotates the RGB color space
* around its luminance axis. The implementation is based on RGB cube rotation in 3D space, providing
* better results than traditional matrices with magic luminance constants.
* @param rotation - The angle of rotation in degrees around the color wheel:
* - 0 = no change
* - 90 = rotate colors 90° clockwise
* - 180 = invert all colors
* - 270 = rotate colors 90° counter-clockwise
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Rotate hue by 90 degrees
* colorMatrix.hue(90, false);
*
* // Chain multiple color adjustments
* colorMatrix
* .hue(45, true) // Rotate colors by 45°
* .saturate(1.2, true) // Increase saturation
* .brightness(1.1, true); // Slightly brighten
* ```
*/
hue(rotation: number, multiply: boolean): void;
/**
* Adjusts the contrast of the display object by modifying the separation between dark and bright values.
*
* This method applies a matrix transformation that affects the difference between dark and light areas
* in the image. Increasing contrast makes shadows darker and highlights brighter, while decreasing
* contrast brings shadows up and highlights down, reducing the overall dynamic range.
* @param amount - The contrast adjustment value. Range is 0 to 1, where:
* - 0 represents minimum contrast (flat gray)
* - 0.5 represents normal contrast
* - 1 represents maximum contrast
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Increase contrast by 50%
* colorMatrix.contrast(0.75, false);
*
* // Chain with other effects
* colorMatrix
* .contrast(0.6, true) // Boost contrast
* .brightness(1.1, true) // Slightly brighten
* .saturate(1.2, true); // Increase color intensity
* ```
*/
contrast(amount: number, multiply: boolean): void;
/**
* Adjusts the saturation of the display object by modifying color separation.
*
* This method applies a matrix transformation that affects the intensity of colors.
* Increasing saturation makes colors more vivid and intense, while decreasing saturation
* moves colors toward grayscale.
* @param amount - The saturation adjustment value. Range is -1 to 1, where:
* - -1 produces grayscale
* - 0 represents no change
* - 1 produces maximum saturation
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Double the saturation
* colorMatrix.saturate(1, false);
*
* // Chain with other effects
* colorMatrix
* .saturate(0.5, true) // Increase saturation by 50%
* .brightness(1.1, true) // Slightly brighten
* .contrast(0.8, true); // Reduce contrast
* ```
*/
saturate(amount?: number, multiply?: boolean): void;
/**
* Completely removes color information from the display object, creating a grayscale version.
*
* This is a convenience method that calls `saturate(-1)` internally. The transformation preserves
* the luminance of the original image while removing all color information.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Convert image to grayscale
* colorMatrix.desaturate();
*
* // Can be chained with other effects
* colorMatrix
* .desaturate() // Remove all color
* .brightness(1.2); // Then increase brightness
* ```
*/
desaturate(): void;
/**
* Creates a negative effect by inverting all colors in the display object.
*
* This method applies a matrix transformation that inverts the RGB values of each pixel
* while preserving the alpha channel. The result is similar to a photographic negative.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Create negative effect
* colorMatrix.negative(false);
*
* // Chain with other effects
* colorMatrix
* .negative(true) // Apply negative effect
* .brightness(1.2, true) // Increase brightness
* .contrast(0.8, true); // Reduce contrast
* ```
*/
negative(multiply: boolean): void;
/**
* Applies a sepia tone effect to the display object, creating a warm brown tint reminiscent of vintage photographs.
*
* This method applies a matrix transformation that converts colors to various shades of brown while
* preserving the original luminance values.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply sepia effect
* colorMatrix.sepia(false);
*
* // Chain with other effects
* colorMatrix
* .sepia(true) // Add sepia tone
* .brightness(1.1, true) // Slightly brighten
* .contrast(0.9, true); // Reduce contrast
* ```
*/
sepia(multiply: boolean): void;
/**
* Applies a Technicolor-style effect that simulates the early color motion picture process.
*
* This method applies a matrix transformation that recreates the distinctive look of the
* Technicolor process. The effect produces highly
* saturated colors with a particular emphasis on reds, greens, and blues.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply Technicolor effect
* colorMatrix.technicolor(false);
*
* // Chain with other effects
* colorMatrix
* .technicolor(true) // Add Technicolor effect
* .contrast(1.1, true) // Boost contrast
* .brightness(0.9, true); // Slightly darken
* ```
*/
technicolor(multiply: boolean): void;
/**
* Applies a vintage Polaroid camera effect to the display object.
*
* This method applies a matrix transformation that simulates the distinctive look of
* Polaroid instant photographs, characterized by slightly enhanced contrast, subtle color shifts,
* and a warm overall tone.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply Polaroid effect
* colorMatrix.polaroid(false);
*
* // Chain with other effects
* colorMatrix
* .polaroid(true) // Add Polaroid effect
* .brightness(1.1, true) // Slightly brighten
* .contrast(1.1, true); // Boost contrast
* ```
*/
polaroid(multiply: boolean): void;
/**
* Swaps the red and blue color channels in the display object.
*
* This method applies a matrix transformation that exchanges the red and blue color values
* while keeping the green channel and alpha unchanged.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Swap red and blue channels
* colorMatrix.toBGR(false);
*
* // Chain with other effects
* colorMatrix
* .toBGR(true) // Swap R and B channels
* .brightness(1.1, true) // Slightly brighten
* .contrast(0.9, true); // Reduce contrast
* ```
*/
toBGR(multiply: boolean): void;
/**
* Applies a Kodachrome color effect that simulates the iconic film stock.
*
* This method applies a matrix transformation that recreates the distinctive look of Kodachrome film,
* known for its rich, vibrant colors and excellent image preservation qualities. The effect emphasizes
* reds and blues while producing deep, true blacks.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply Kodachrome effect
* colorMatrix.kodachrome(false);
*
* // Chain with other effects
* colorMatrix
* .kodachrome(true) // Add Kodachrome effect
* .contrast(1.1, true) // Boost contrast
* .brightness(0.9, true); // Slightly darken
* ```
*/
kodachrome(multiply: boolean): void;
/**
* Applies a stylized brown-tinted effect to the display object.
*
* This method applies a matrix transformation that creates a rich, warm brown tone
* with enhanced contrast and subtle color shifts.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply browni effect
* colorMatrix.browni(false);
*
* // Chain with other effects
* colorMatrix
* .browni(true) // Add brown tint
* .brightness(1.1, true) // Slightly brighten
* .contrast(1.2, true); // Boost contrast
* ```
*/
browni(multiply: boolean): void;
/**
* Applies a vintage photo effect that simulates old photography techniques.
*
* This method applies a matrix transformation that creates a nostalgic, aged look
* with muted colors, enhanced warmth, and subtle vignetting.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply vintage effect
* colorMatrix.vintage(false);
*
* // Chain with other effects
* colorMatrix
* .vintage(true) // Add vintage look
* .brightness(0.9, true) // Slightly darken
* .contrast(1.1, true); // Boost contrast
* ```
*/
vintage(multiply: boolean): void;
/**
* We don't know exactly what it does, kind of gradient map, but funny to play with!
* @param desaturation - Tone values.
* @param toned - Tone values.
* @param lightColor - Tone values, example: `0xFFE580`
* @param darkColor - Tone values, example: `0xFFE580`
* @param multiply - if true, current matrix and matrix are multiplied. If false,
* just set the current matrix with matrix
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Create sepia-like effect with custom colors
* colorMatrix.colorTone(
* 0.3, // Moderate desaturation
* 0.2, // Moderate toning
* 0xFFE580, // Warm highlight color
* 0x338000, // Dark green shadows
* false
* );
*
* // Chain with other effects
* colorMatrix
* .colorTone(0.2, 0.15, 0xFFE580, 0x338000, true)
* .brightness(1.1, true); // Slightly brighten
* ```
*/
colorTone(desaturation: number, toned: number, lightColor: ColorSource, darkColor: ColorSource, multiply: boolean): void;
/**
* Applies a night vision effect to the display object.
*
* This method applies a matrix transformation that simulates night vision by enhancing
* certain color channels while suppressing others, creating a green-tinted effect
* similar to night vision goggles.
* @param intensity - The intensity of the night effect (0-1):
* - 0 produces no effect
* - 0.1 produces a subtle night vision effect (default)
* - 1 produces maximum night vision effect
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply night vision effect
* colorMatrix.night(0.3, false);
*
* // Chain with other effects
* colorMatrix
* .night(0.2, true) // Add night vision
* .brightness(1.1, true) // Slightly brighten
* .contrast(1.2, true); // Boost contrast
* ```
*/
night(intensity: number, multiply: boolean): void;
/**
* Predator effect
*
* Erase the current matrix by setting a new independent one
* @param amount - how much the predator feels his future victim
* @param multiply - if true, current matrix and matrix are multiplied. If false,
* just set the current matrix with matrix
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply thermal vision effect
* colorMatrix.predator(0.5, false);
*
* // Chain with other effects
* colorMatrix
* .predator(0.3, true) // Add thermal effect
* .contrast(1.2, true) // Boost contrast
* .brightness(1.1, true); // Slightly brighten
* ```
*/
predator(amount: number, multiply: boolean): void;
/**
* Applies a psychedelic color effect that creates dramatic color shifts.
*
* This method applies a matrix transformation that produces vibrant colors
* through channel mixing and amplification. Creates an effect reminiscent of
* color distortions in psychedelic art.
* @param multiply - When true, the new matrix is multiplied with the current matrix instead of replacing it.
* This allows for cumulative effects when calling multiple color adjustments.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply psychedelic effect
* colorMatrix.lsd(false);
*
* // Chain with other effects
* colorMatrix
* .lsd(true) // Add color distortion
* .brightness(0.9, true) // Slightly darken
* .contrast(1.2, true); // Boost contrast
* ```
*/
lsd(multiply: boolean): void;
/**
* Resets the color matrix filter to its default state.
*
* This method resets all color transformations by setting the matrix back to its identity state.
* The identity matrix leaves colors unchanged, effectively removing all previously applied effects.
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply some effects
* colorMatrix
* .sepia(true)
* .brightness(1.2, true);
*
* // Reset back to original colors
* colorMatrix.reset();
* ```
*/
reset(): void;
/**
* The current color transformation matrix of the filter.
*
* This 5x4 matrix transforms RGBA color and alpha values of each pixel. The matrix is stored
* as a 20-element array in row-major order.
* @type {ColorMatrix}
* @default [
* 1, 0, 0, 0, 0, // Red channel
* 0, 1, 0, 0, 0, // Green channel
* 0, 0, 1, 0, 0, // Blue channel
* 0, 0, 0, 1, 0 // Alpha channel
* ]
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
* // Get the current color matrix
* const currentMatrix = colorMatrix.matrix;
* // Modify the matrix
* colorMatrix.matrix = [
* 1, 0, 0, 0, 0,
* 0, 1, 0, 0, 0,
* 0, 0, 1, 0, 0,
* 0, 0, 0, 1, 0
* ];
*/
get matrix(): ColorMatrix;
set matrix(value: ColorMatrix);
/**
* The opacity value used to blend between the original and transformed colors.
*
* This value controls how much of the color transformation is applied:
* - 0 = Original color only (no effect)
* - 0.5 = 50% blend of original and transformed colors
* - 1 = Fully transformed color (default)
* @default 1
* @example
* ```ts
* const colorMatrix = new ColorMatrixFilter();
*
* // Apply sepia at 50% strength
* colorMatrix.sepia(false);
* colorMatrix.alpha = 0.5;
*
* // Fade between effects
* colorMatrix
* .saturate(1.5) // Increase saturation
* .contrast(1.2); // Boost contrast
* colorMatrix.alpha = 0.7; // Apply at 70% strength
* ```
*/
get alpha(): number;
set alpha(value: number);
}
/**
* Configuration options for the DisplacementFilter.
*
* A displacement filter uses a sprite's texture as a displacement map,
* moving pixels of the target based on the color values of corresponding
* pixels in the displacement sprite.
* @example
* ```ts
* const options: DisplacementFilterOptions = {
* sprite: displacementSprite,
* scale: { x: 20, y: 20 }
* };
*
* const filter = new DisplacementFilter(options);
* ```
* @category filters
* @standard
*/
export interface DisplacementFilterOptions extends FilterOptions {
/**
* The sprite whose texture will be used as the displacement map.
* Red channel = horizontal displacement
* Green channel = vertical displacement
* @example
* ```ts
* const displacementSprite = new Sprite(texture);
* const filter = new DisplacementFilter({ sprite: displacementSprite });
* ```
*/
sprite: Sprite;
/**
* The scale of the displacement effect. Can be a single number for uniform
* scaling or a point-like object for separate x/y scaling.
* @default 20
* @example
* ```ts
* // Uniform scaling
* new DisplacementFilter({ sprite, scale: 20 });
* // Separate scaling
* new DisplacementFilter({ sprite, scale: { x: 10, y: 15 } });
* ```
*/
scale?: number | PointData;
}
/**
* A filter that applies a displacement map effect using a sprite's texture.
*
* The DisplacementFilter uses another texture (from a sprite) as a displacement map,
* where the red and green channels of each pixel in the map determine how the corresponding
* pixel in the filtered object should be offset:
* - Red channel controls horizontal displacement
* - Green channel controls vertical displacement
*
* Common use cases:
* - Creating ripple or wave effects
* - Distorting images dynamically
* - Implementing heat haze effects
* - Creating transition effects
* @example
* ```ts
* import { Sprite, DisplacementFilter } from 'pixi.js';
*
* // Create a sprite to use as the displacement map
* const displacementSprite = Sprite.from('displacement-map.png');
*
* // Create and configure the filter
* const displacementFilter = new DisplacementFilter({
* sprite: displacementSprite,
* scale: { x: 20, y: 20 }
* });
*
* // Apply to any display object
* container.filters = [displacementFilter];
* ```
* @category filters
* @author Vico: vicocotea
* @standard
* @noInheritDoc
*/
export declare class DisplacementFilter extends Filter {
private readonly _sprite;
/**
* @param {Sprite | DisplacementFilterOptions} options - The sprite or options object.
* @param {Sprite} options.sprite - The texture used for the displacement map.
* @param {number | PointData} options.scale - The scale of the displacement.
*/
constructor(options: Sprite | DisplacementFilterOptions);
/** @deprecated since 8.0.0 */
constructor(sprite: Sprite, scale?: number | PointData);
/**
* Applies the filter.
* @param filterManager - The manager.
* @param input - The input target.
* @param output - The output target.
* @param clearMode - clearMode.
* @advanced
*/
apply(filterManager: FilterSystem, input: Texture, output: Texture, clearMode: boolean): void;
/**
* The scale of the displacement effect.
*
* Gets the current x and y scaling values used for the displacement mapping.
* - x: Horizontal displacement scale
* - y: Vertical displacement scale
* @returns {Point} The current scale as a Point object
* @example
* ```ts
* const filter = new DisplacementFilter({ sprite });
*
* // Get current scale
* console.log(filter.scale.x, filter.scale.y);
*
* // Update scale
* filter.scale.x = 100;
* filter.scale.y = 50;
* ```
*/
get scale(): Point;
}
/**
* Configuration options for the NoiseFilter.
*
* The NoiseFilter adds random noise to the rendered content. The noise effect can be
* controlled through the noise intensity and an optional seed value for reproducible results.
* @example
* ```ts
* // Basic noise effect
* const options: NoiseFilterOptions = {
* noise: 0.5,
* seed: Math.random()
* };
*
* // Create filter with options
* const noiseFilter = new NoiseFilter(options);
* ```
* @category filters
* @standard
*/
export interface NoiseFilterOptions extends FilterOptions {
/**
* The amount of noise to apply. Should be in range (0, 1]:
* - 0.1 = subtle noise
* - 0.5 = moderate noise (default)
* - 1.0 = maximum noise
* @default 0.5
* @example
* ```ts
* // Moderate noise effect
* const noiseFilter = new NoiseFilter({ noise: 0.5 });
* ```
*/
noise?: number;
/**
* A seed value to apply to the random noise generation.
* Using the same seed will generate the same noise pattern.
* @default Math.random()
* @example
* ```ts
* // Using a fixed seed for reproducible noise
* const noiseFilter = new NoiseFilter({ seed: 12345 });
* ```
*/
seed?: number;
}
/**
* A filter that adds configurable random noise to rendered content.
*
* This filter generates pixel noise based on a noise intensity value and an optional seed.
* It can be used to create various effects like film grain, static, or texture variation.
*
* Based on: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
* @example
* ```ts
* import { NoiseFilter } from 'pixi.js';
*
* // Create with options
* const filter = new NoiseFilter({
* noise: 0.5, // 50% noise intensity
* seed: 12345 // Fixed seed for consistent noise
* });
*
* // Apply to a display object
* sprite.filters = [filter];
*
* // Adjust noise dynamically
* filter.noise = 0.8; // Increase noise
* filter.seed = Math.random(); // New random pattern
* ```
* @category filters
* @author Vico: vicocotea
* @standard
* @noInheritDoc
*/
export declare class NoiseFilter extends Filter {
/**
* The default configuration options for the NoiseFilter.
*
* These values will be used when no specific options are provided to the constructor.
* You can override any of these values by passing your own options object.
* @example
* ```ts
* NoiseFilter.defaultOptions.noise = 0.7; // Change default noise to 0.7
* const filter = new NoiseFilter(); // Will use noise 0.7 by default
* ```
*/
static defaultOptions: NoiseFilterOptions;
/**
* @param options - The options of the noise filter.
*/
constructor(options?: NoiseFilterOptions);
/**
* The amount of noise to apply to the filtered content.
*
* This value controls the intensity of the random noise effect:
* - Values close to 0 produce subtle noise
* - Values around 0.5 produce moderate noise
* - Values close to 1 produce strong noise
* @default 0.5
* @example
* ```ts
* const noiseFilter = new NoiseFilter();
*
* // Set to subtle noise
* noiseFilter.noise = 0.2;
*
* // Set to maximum noise
* noiseFilter.noise = 1.0;
* ```
*/
get noise(): number;
set noise(value: number);
/**
* The seed value used for random noise generation.
*
* This value determines the noise pattern:
* - Using the same seed will generate identical noise patterns
* - Different seeds produce different but consistent patterns
* - `Math.random()` can be used for random patterns
* @default Math.random()
* @example
* ```ts
* const noiseFilter = new NoiseFilter();
*
* // Use a fixed seed for consistent noise
* noiseFilter.seed = 12345;
*
* // Generate new random pattern
* noiseFilter.seed = Math.random();
* ```
*/
get seed(): number;
set seed(value: number);
}
/**
* The PassthroughFilter passes the input data through without altering it.
* It serves as a basic filter, performing no graphical alterations.
* @category filters
* @internal
*/
export declare class PassthroughFilter extends Filter {
constructor();
}
/** @internal */
export interface MaskFilterOptions extends FilterOptions {
sprite: Sprite;
inverse?: boolean;
scale?: number | {
x: number;
y: number;
};
}
/** @internal */
export declare class MaskFilter extends Filter {
sprite: Sprite;
private readonly _textureMatrix;
constructor(options: MaskFilterOptions);
set inverse(value: boolean);
get inverse(): boolean;
apply(filterManager: FilterSystem, input: Texture, output: Texture, clearMode: boolean): void;
}
type GD8Symmetry = number;
/**
* @typedef {number} GD8Symmetry
* @see groupD8
*/
/**
* Implements the dihedral group D8, which is similar to
* [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html};
* D8 is the same but with diagonals, and it is used for texture
* rotations.
*
* The directions the U- and V- axes after rotation
* of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))`
* and `(vX(a), vY(a))`. These aren't necessarily unit vectors.
* @author Ivan: ivanpopelyshev
* @groupDescription groupD8
* @category maths
* @advanced
*/
export declare const groupD8: {
/**
* | Rotation | Direction |
* |----------|-----------|
* | 0° | East |
* @group groupD8
* @type {GD8Symmetry}
*/
E: number;
/**
* | Rotation | Direction |
* |----------|-----------|
* | 45°↻ | Southeast |
* @group groupD8
* @type {GD8Symmetry}
*/
SE: number;
/**
* | Rotation | Direction |
* |----------|-----------|
* | 90°↻ | South |
* @group groupD8
* @type {GD8Symmetry}
*/
S: number;
/**
* | Rotation | Direction |
* |----------|-----------|
* | 135°↻ | Southwest |
* @group groupD8
* @type {GD8Symmetry}
*/
SW: number;
/**
* | Rotation | Direction |
* |----------|-----------|
* | 180° | West |
* @group groupD8
* @type {GD8Symmetry}
*/
W: number;
/**
* | Rotation | Direction |
* |-------------|--------------|
* | -135°/225°↻ | Northwest |
* @group groupD8
* @type {GD8Symmetry}
*/
NW: number;
/**
* | Rotation | Direction |
* |-------------|--------------|
* | -90°/270°↻ | North |
* @group groupD8
* @type {GD8Symmetry}
*/
N: number;
/**
* | Rotation | Direction |
* |-------------|--------------|
* | -45°/315°↻ | Northeast |
* @group groupD8
* @type {GD8Symmetry}
*/
NE: number;
/**
* Reflection about Y-axis.
* @group groupD8
* @type {GD8Symmetry}
*/
MIRROR_VERTICAL: number;
/**
* Reflection about the main diagonal.
* @group groupD8
* @type {GD8Symmetry}
*/
MAIN_DIAGONAL: number;
/**
* Reflection about X-axis.
* @group groupD8
* @type {GD8Symmetry}
*/
MIRROR_HORIZONTAL: number;
/**
* Reflection about reverse diagonal.
* @group groupD8
* @type {GD8Symmetry}
*/
REVERSE_DIAGONAL: number;
/**
* @group groupD8
* @param {GD8Symmetry} ind - sprite rotation angle.
* @returns {GD8Symmetry} The X-component of the U-axis
* after rotating the axes.
*/
uX: (ind: GD8Symmetry) => GD8Symmetry;
/**
* @group groupD8
* @param {GD8Symmetry} ind - sprite rotation angle.
* @returns {GD8Symmetry} The Y-component of the U-axis
* after rotating the axes.
*/
uY: (ind: GD8Symmetry) => GD8Symmetry;
/**
* @group groupD8
* @param {GD8Symmetry} ind - sprite rotation angle.
* @returns {GD8Symmetry} The X-component of the V-axis
* after rotating the axes.
*/
vX: (ind: GD8Symmetry) => GD8Symmetry;
/**
* @group groupD8
* @param {GD8Symmetry} ind - sprite rotation angle.
* @returns {GD8Symmetry} The Y-component of the V-axis
* after rotating the axes.
*/
vY: (ind: GD8Symmetry) => GD8Symmetry;
/**
* @group groupD8
* @param {GD8Symmetry} rotation - symmetry whose opposite
* is needed. Only rotations have opposite symmetries while
* reflections don't.
* @returns {GD8Symmetry} The opposite symmetry of `rotation`
*/
inv: (rotation: GD8Symmetry) => GD8Symmetry;
/**
* Composes the two D8 operations.
*
* Taking `^` as reflection:
*
* | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 |
* |-------|-----|-----|-----|-----|------|-------|-------|-------|
* | E=0 | E | S | W | N | E^ | S^ | W^ | N^ |
* | S=2 | S | W | N | E | S^ | W^ | N^ | E^ |
* | W=4 | W | N | E | S | W^ | N^ | E^ | S^ |
* | N=6 | N | E | S | W | N^ | E^ | S^ | W^ |
* | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S |
* | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W |
* | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N |
* | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E |
*
* [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table}
* @group groupD8
* @param {GD8Symmetry} rotationSecond - Second operation, which
* is the row in the above cayley table.
* @param {GD8Symmetry} rotationFirst - First operation, which
* is the column in the above cayley table.
* @returns {GD8Symmetry} Composed operation
*/
add: (rotationSecond: GD8Symmetry, rotationFirst: GD8Symmetry) => GD8Symmetry;
/**
* Reverse of `add`.
* @group groupD8
* @param {GD8Symmetry} rotationSecond - Second operation
* @param {GD8Symmetry} rotationFirst - First operation
* @returns {GD8Symmetry} Result
*/
sub: (rotationSecond: GD8Symmetry, rotationFirst: GD8Symmetry) => GD8Symmetry;
/**
* Adds 180 degrees to rotation, which is a commutative
* operation.
* @group groupD8
* @param {number} rotation - The number to rotate.
* @returns {number} Rotated number
*/
rotate180: (rotation: number) => number;
/**
* Checks if the rotation angle is vertical, i.e. south
* or north. It doesn't work for reflections.
* @group groupD8
* @param {GD8Symmetry} rotation - The number to check.
* @returns {boolean} Whether or not the direction is vertical
*/
isVertical: (rotation: GD8Symmetry) => boolean;
/**
* Approximates the vector `V(dx,dy)` into one of the
* eight directions provided by `groupD8`.
* @group groupD8
* @param {number} dx - X-component of the vector
* @param {number} dy - Y-component of the vector
* @returns {GD8Symmetry} Approximation of the vector into
* one of the eight symmetries.
*/
byDirection: (dx: number, dy: number) => GD8Symmetry;
/**
* Helps sprite to compensate texture packer rotation.
* @group groupD8
* @param {Matrix} matrix - sprite world matrix
* @param {GD8Symmetry} rotation - The rotation factor to use.
* @param {number} tx - sprite anchoring
* @param {number} ty - sprite anchoring
*/
matrixAppendRotationInv: (matrix: Matrix, rotation: GD8Symmetry, tx?: number, ty?: number) => void;
/**
* Transforms rectangle coordinates based on texture packer rotation.
* Used when texture atlas pages are rotated and coordinates need to be adjusted.
* @group groupD8
* @param {RectangleLike} rect - Rectangle with original coordinates to transform
* @param {RectangleLike} sourceFrame - Source texture frame (includes offset and dimensions)
* @param {GD8Symmetry} rotation - The groupD8 rotation value
* @param {Rectangle} out - Rectangle to store the result
* @returns {Rectangle} Transformed coordinates (includes source frame offset)
*/
transformRectCoords: (rect: RectangleLike, sourceFrame: RectangleLike, rotation: GD8Symmetry, out: Rectangle) => Rectangle;
};
/**
* Rounds to next power of two.
* @function nextPow2
* @param {number} v - input value
* @returns {number} - next rounded power of two
* @category maths
* @advanced
*/
export declare function nextPow2(v: number): number;
/**
* Checks if a number is a power of two.
* @function isPow2
* @param {number} v - input value
* @returns {boolean} `true` if value is power of two
* @category maths
* @advanced
*/
export declare function isPow2(v: number): boolean;
/**
* Computes ceil of log base 2
* @function log2
* @param {number} v - input value
* @returns {number} logarithm base 2
* @category maths
* @advanced
*/
export declare function log2(v: number): number;
/**
* Calculates the squared distance from a point to a line segment defined by two endpoints.
* @param x - x coordinate of the point
* @param y - y coordinate of the point
* @param x1 - x coordinate of the first endpoint of the line segment
* @param y1 - y coordinate of the first endpoint of the line segment
* @param x2 - x coordinate of the second endpoint of the line segment
* @param y2 - y coordinate of the second endpoint of the line segment
* @returns The squared distance from the point to the line segment
* @category maths
* @internal
*/
export declare function squaredDistanceToLineSegment(x: number, y: number, x1: number, y1: number, x2: number, y2: number): number;
/**
* Check if a point is inside a triangle.
* @param px - x coordinate of the point
* @param py - y coordinate of the point
* @param x1 - x coordinate of the first vertex of the triangle
* @param y1 - y coordinate of the first vertex of the triangle
* @param x2 - x coordinate of the second vertex of the triangle
* @param y2 - y coordinate of the second vertex of the triangle
* @param x3 - x coordinate of the third vertex of the triangle
* @param y3 - y coordinate of the third vertex of the triangle
* @returns `true` if the point is inside the triangle, `false` otherwise
* @category maths
* @internal
*/
export declare function pointInTriangle(px: number, py: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): boolean;
/**
* Part of the prepare system. Responsible for uploading all the items to the GPU.
* This class extends the base functionality and resolves given resource items ready for the queue.
* @category rendering
* @advanced
*/
export declare abstract class PrepareQueue extends PrepareBase {
/**
* Resolve the given resource type and return an item for the queue
* @param source
* @param queue
*/
protected resolveQueueItem(source: PrepareSourceItem, queue: PrepareQueueItem[]): void;
/**
* Resolve the given container and return an item for the queue
* @param container
* @param queue
*/
protected resolveContainerQueueItem(container: Container, queue: PrepareQueueItem[]): void;
/**
* Resolve the given graphics context and return an item for the queue
* @param graphicsContext
*/
protected resolveGraphicsContextQueueItem(graphicsContext: GraphicsContext): PrepareQueueItem | null;
}
/**
* @advanced
* Part of the prepare system. Responsible for uploading all the items to the GPU.
* This class extends the resolver functionality and uploads the given queue items.
* @category rendering
*/
export declare abstract class PrepareUpload extends PrepareQueue {
/**
* Upload the given queue item
* @param item
*/
protected uploadQueueItem(item: PrepareQueueItem): void;
protected uploadTextureSource(textureSource: TextureSource): void;
protected uploadText(_text: Text$1): void;
protected uploadBitmapText(_text: BitmapText): void;
protected uploadHTMLText(_text: HTMLText): void;
/**
* Resolve the given graphics context and return an item for the queue
* @param graphicsContext
*/
protected uploadGraphicsContext(graphicsContext: GraphicsContext): void;
}
/**
* The prepare system provides renderer-specific plugins for pre-rendering DisplayObjects. This is useful for
* asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed.
*
* Do not instantiate this plugin directly. It is available from the `renderer.prepare` property.
* @example
* import 'pixi.js/prepare';
* import { Application, Graphics } from 'pixi.js';
*
* // Create a new application (prepare will be auto-added to renderer)
* const app = new Application();
* await app.init();
* document.body.appendChild(app.view);
*
* // Don't start rendering right away
* app.stop();
*
* // Create a display object
* const rect = new Graphics()
* .beginFill(0x00ff00)
* .drawRect(40, 40, 200, 200);
*
* // Add to the stage
* app.stage.addChild(rect);
*
* // Don't start rendering until the graphic is uploaded to the GPU
* app.renderer.prepare.upload(app.stage, () => {
* app.start();
* });
* @category rendering
* @advanced
*/
export declare class PrepareSystem extends PrepareUpload implements System {
/** @ignore */
static extension: {
readonly type: readonly [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
];
readonly name: "prepare";
};
/** Destroys the plugin, don't use after this. */
destroy(): void;
}
/**
* Represents the JSON data for a spritesheet atlas.
* @category assets
* @advanced
*/
export interface SpritesheetFrameData {
/** The frame rectangle of the texture. */
frame: {
x: number;
y: number;
w: number;
h: number;
};
/** Whether the texture is trimmed. */
trimmed?: boolean;
/** Whether the texture is rotated. */
rotated?: boolean;
/** The source size of the texture. */
sourceSize?: {
w: number;
h: number;
};
/** The sprite source size. */
spriteSourceSize?: {
h?: number;
w?: number;
x: number;
y: number;
};
/** The anchor point of the texture. */
anchor?: PointData;
/** The 9-slice borders of the texture. */
borders?: TextureBorders;
}
/**
* Atlas format.
* @category assets
* @advanced
*/
export interface SpritesheetData {
/** The frames of the atlas. */
frames: Dict<SpritesheetFrameData>;
/** The animations of the atlas. */
animations?: Dict<string[]>;
/** The meta data 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;
};
}
/**
* Options for loading a spritesheet from an atlas.
* @category assets
* @advanced
*/
export interface SpritesheetOptions<S extends SpritesheetData = SpritesheetData> {
/** Reference to Texture */
texture: BindableTexture;
/** JSON data for the atlas. */
data: S;
/** The filename to consider when determining the resolution of the spritesheet. */
resolutionFilename?: string;
/**
* Prefix to add to texture names when adding to global TextureCache,
* using this option can be helpful if you have multiple texture atlases
* that share texture names and you need to disambiguate them.
*/
cachePrefix?: string;
}
/**
* Utility class for maintaining reference to a collection
* of Textures on a single Spritesheet.
*
* To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader:
*
* ```js
* import { Assets } from 'pixi.js';
*
* const sheet = await Assets.load('images/spritesheet.json');
* ```
*
* Alternately, you may circumvent the loader by instantiating the Spritesheet directly:
*
* ```js
* import { Spritesheet } from 'pixi.js';
*
* const sheet = new Spritesheet(texture, spritesheetData);
* await sheet.parse();
* console.log('Spritesheet ready to use!');
* ```
*
* With the `sheet.textures` you can create Sprite objects, and `sheet.animations` can be used to create an AnimatedSprite.
*
* Here's an example of a sprite sheet JSON data file:
* ```json
* {
* "frames": {
* "enemy1.png":
* {
* "frame": {"x":103,"y":1,"w":32,"h":32},
* "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
* "sourceSize": {"w":32,"h":32},
* "anchor": {"x":0.5,"y":0.5}
* },
* "enemy2.png":
* {
* "frame": {"x":103,"y":35,"w":32,"h":32},
* "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
* "sourceSize": {"w":32,"h":32},
* "anchor": {"x":0.5,"y":0.5}
* },
* "button.png":
* {
* "frame": {"x":1,"y":1,"w":100,"h":100},
* "spriteSourceSize": {"x":0,"y":0,"w":100,"h":100},
* "sourceSize": {"w":100,"h":100},
* "anchor": {"x":0,"y":0},
* "borders": {"left":35,"top":35,"right":35,"bottom":35}
* }
* },
*
* "animations": {
* "enemy": ["enemy1.png","enemy2.png"]
* },
*
* "meta": {
* "image": "sheet.png",
* "format": "RGBA8888",
* "size": {"w":136,"h":102},
* "scale": "1"
* }
* }
* ```
* Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
* {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
* Default anchor points (see {@link Texture#defaultAnchor}), default 9-slice borders
* (see {@link Texture#defaultBorders}) and grouping of animation sprites are currently only
* supported by TexturePacker.
*
* Alternative ways for loading spritesheet image if you need more control:
*
* ```js
* import { Assets } from 'pixi.js';
*
* const sheetTexture = await Assets.load('images/spritesheet.png');
* Assets.add({
* alias: 'atlas',
* src: 'images/spritesheet.json',
* data: {texture: sheetTexture} // using of preloaded texture
* });
* const sheet = await Assets.load('atlas')
* ```
*
* or:
*
* ```js
* import { Assets } from 'pixi.js';
*
* Assets.add({
* alias: 'atlas',
* src: 'images/spritesheet.json',
* data: {imageFilename: 'my-spritesheet.2x.avif'} // using of custom filename located in "images/my-spritesheet.2x.avif"
* });
* const sheet = await Assets.load('atlas')
* ```
* @category assets
* @standard
*/
export declare class Spritesheet<S extends SpritesheetData = SpritesheetData> {
/**
* The maximum number of Textures to build per process.
* @advanced
*/
static readonly BATCH_SIZE = 1000;
/** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */
linkedSheets: Spritesheet<S>[];
/** Reference to the source texture. */
textureSource: TextureSource;
/**
* A map containing all textures of the sprite sheet.
* Can be used to create a {@link Sprite}:
* @example
* import { Sprite } from 'pixi.js';
*
* new Sprite(sheet.textures['image.png']);
*/
textures: Record<keyof S["frames"], Texture>;
/**
* A map containing the textures for each animation.
* Can be used to create an {@link AnimatedSprite}:
* @example
* import { AnimatedSprite } from 'pixi.js';
*
* new AnimatedSprite(sheet.animations['anim_name']);
*/
animations: Record<keyof NonNullable<S["animations"]>, Texture[]>;
/**
* Reference to the original JSON data.
* @type {object}
*/
data: S;
/** The resolution of the spritesheet. */
resolution: number;
/**
* Reference to original source image from the Loader. This reference is retained so we
* can destroy the Texture later on. It is never used internally.
*/
private _texture;
/**
* Map of spritesheet frames.
* @type {object}
*/
private _frames;
/** Collection of frame names. */
private _frameKeys;
/** Current batch index being processed. */
private _batchIndex;
/**
* Callback when parse is completed.
* @type {Function}
*/
private _callback;
/** Prefix string to add to global cache */
readonly cachePrefix: string;
/**
* @class
* @param options - Options to use when constructing a new Spritesheet.
*/
constructor(options: SpritesheetOptions<S>);
/**
* @param texture - Reference to the source BaseTexture object.
* @param {object} data - Spritesheet image data.
*/
constructor(texture: BindableTexture, data: S);
/**
* Parser spritesheet from loaded data. This is done asynchronously
* to prevent creating too many Texture within a single process.
*/
parse(): Promise<Record<string, Texture>>;
/**
* Process a batch of frames
* @param initialFrameIndex - The index of frame to start.
*/
private _processFrames;
/** Parse animations config. */
private _processAnimations;
/** The parse has completed. */
private _parseComplete;
/** Begin the next batch of textures. */
private _nextBatch;
/**
* Destroy Spritesheet and don't use after this.
* @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
*/
destroy(destroyBase?: boolean): void;
}
/**
* Interface for the JSON data structure of a spritesheet.
* This is used to define the structure of the JSON file that describes a spritesheet.
* It includes metadata about the spritesheet and the frames it contains.
* @see {@link Spritesheet}
* @see {@link SpritesheetData}
* @category assets
* @advanced
*/
export interface SpriteSheetJson extends SpritesheetData {
meta: {
image: string;
scale: string;
related_multi_packs?: string[];
};
}
/**
* 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 {AssetExtension}
* @category assets
* @advanced
*/
export declare const spritesheetAsset: {
extension: ExtensionType.Asset;
/** Handle the caching of the related Spritesheet Textures */
cache: {
test: (asset: Spritesheet) => boolean;
getCacheableAssets: (keys: string[], asset: Spritesheet) => Record<string, any>;
};
/** Resolve the resolution of the asset. */
resolver: {
extension: {
type: ExtensionType.ResolveParser;
name: string;
};
test: (value: string) => boolean;
parse: (value: string) => {
resolution: number;
format: string;
src: string;
};
};
/**
* Loader plugin that parses sprite sheets!
* once the JSON has been loaded this checks to see if the JSON is spritesheet data.
* If it is, we load the spritesheets image and parse the data into Spritesheet
* All textures in the sprite sheet are then added to the cache
*/
loader: {
/** used for deprecation purposes */
name: string;
id: string;
extension: {
type: ExtensionType.LoadParser;
priority: LoaderParserPriority;
name: string;
};
testParse(asset: SpriteSheetJson, options: ResolvedAsset): Promise<boolean>;
parse<T>(asset: SpriteSheetJson, options: ResolvedAsset<{
texture?: Texture;
imageFilename?: string;
ignoreMultiPack?: boolean;
textureOptions?: TextureSourceOptions;
cachePrefix?: string;
}>, loader?: Loader): Promise<Spritesheet>;
unload(spritesheet: Spritesheet, _resolvedAsset: ResolvedAsset<any>, loader: Loader): Promise<void>;
};
};
/**
* Represents the update priorities used by internal Pixi classes when registered with
* the {@link Ticker} object. Higher priority items are updated first and lower
* priority items, such as render, should go later.
* @enum {number}
* @category ticker
* @standard
*/
export declare enum UPDATE_PRIORITY {
/**
* Highest priority used for interaction events in {@link EventSystem}
* @default 50
*/
INTERACTION = 50,
/**
* High priority updating, used by {@link AnimatedSprite}
* @default 25
*/
HIGH = 25,
/**
* Default priority for ticker events, see {@link Ticker#add}.
* @default 0
*/
NORMAL = 0,
/**
* Low priority used for {@link Application} rendering.
* @default -25
*/
LOW = -25,
/**
* Lowest priority used for {@link PrepareBase} utility.
* @default -50
*/
UTILITY = -50
}
/**
* Internal class for handling the priority sorting of ticker handlers.
* @private
* @class
*/
export declare class TickerListener<T = any> {
/** The current priority. */
priority: number;
/** The next item in chain. */
next: TickerListener;
/** The previous item in chain. */
previous: TickerListener;
/** The handler function to execute. */
private _fn;
/** The calling to execute. */
private _context;
/** If this should only execute once. */
private readonly _once;
/** `true` if this listener has been destroyed already. */
private _destroyed;
/**
* Constructor
* @private
* @param fn - The listener function to be added for one update
* @param context - The listener context
* @param priority - The priority for emitting
* @param once - If the handler should fire once
*/
constructor(fn: TickerCallback<T>, context?: T, priority?: number, once?: boolean);
/**
* Simple compare function to figure out if a function and context match.
* @param fn - The listener function to be added for one update
* @param context - The listener context
* @returns `true` if the listener match the arguments
*/
match(fn: TickerCallback<T>, context?: any): boolean;
/**
* Emit by calling the current function.
* @param ticker - The ticker emitting.
* @returns Next ticker
*/
emit(ticker: Ticker): TickerListener;
/**
* Connect to the list.
* @param previous - Input node, previous listener
*/
connect(previous: TickerListener): void;
/**
* Destroy and don't use after this.
* @param hard - `true` to remove the `next` reference, this
* is considered a hard destroy. Soft destroy maintains the next reference.
* @returns The listener to redirect while emitting or removing.
*/
destroy(hard?: boolean): TickerListener;
}
/**
* Helper for detecting the correct alpha mode for video textures.
* For some reason, some browsers/devices/WebGL implementations premultiply the alpha
* of a video before and then a second time if `UNPACK_PREMULTIPLY_ALPHA_WEBGL`
* is true. So the video is premultiplied twice if the alpha mode is `UNPACK`.
* In this case we need the alpha mode to be `PMA`. This function detects
* the upload behavior by uploading a white 2x2 webm with 50% alpha
* without `UNPACK_PREMULTIPLY_ALPHA_WEBGL` and then checking whether
* the uploaded pixels are premultiplied.
* @category utils
* @internal
* @returns {Promise<ALPHA_MODES>} The correct alpha mode for video textures.
*/
export declare function detectVideoAlphaMode(): Promise<ALPHA_MODES>;
/**
* Checks if the current browser is Safari.
* @returns {boolean} True if the browser is Safari, false otherwise.
* @internal
*/
export declare function isSafari(): boolean;
/**
* Helper for checking for WebGL support in the current environment.
*
* Results are cached after first call for better performance.
* @example
* ```ts
* // Basic WebGL support check
* if (isWebGLSupported()) {
* console.log('WebGL is available');
* }
* ```
* @param failIfMajorPerformanceCaveat - Whether to fail if there is a major performance caveat
* @returns True if WebGL is supported
* @category utils
* @standard
*/
export declare function isWebGLSupported(failIfMajorPerformanceCaveat?: boolean): boolean;
/**
* Helper for checking for WebGPU support in the current environment.
* Results are cached after first call for better performance.
* @example
* ```ts
* // Basic WebGPU support check
* const hasWebGPU = await isWebGPUSupported();
* console.log('WebGPU available:', hasWebGPU);
* ```
* @param options - The options for requesting a GPU adapter
* @returns Promise that resolves to true if WebGPU is supported
* @category utils
* @standard
*/
export declare function isWebGPUSupported(options?: GPURequestAdapterOptions): Promise<boolean>;
/**
* Not all platforms allow to generate function code (e.g., `new Function`).
* this provides the platform-level detection.
* @private
* @returns {boolean} `true` if `new Function` is supported.
*/
export declare function unsafeEvalSupported(): boolean;
/** @internal */
export interface GetCanvasBoundingBoxOptions {
/** The canvas to measure */
canvas: ICanvas;
/** Optional. The width to analyze (defaults to canvas.width) */
width?: number;
/** Optional. The height to analyze (defaults to canvas.height) */
height?: number;
/**
* Optional. The resolution at which to analyze the canvas, between 0-1.
* Lower values improve performance for large canvases but may be less precise.
* Default is 1 (full resolution).
*/
resolution?: number;
/** Optional. The rectangle to store the result in. */
output?: Rectangle;
}
/**
* Measures the bounding box of a canvas's visible (non-transparent) pixels.
*
* This function analyzes the alpha channel of the canvas pixels to find the smallest
* rectangle containing all non-transparent pixels. It's useful for optimizing sprite
* rendering by trimming transparent borders.
*
* Uses an internal canvas with `willReadFrequently: true` for efficient pixel data access.
* This internal canvas is reused between calls for better performance.
* @example
* ```typescript
* // Basic usage - get trim bounds at full resolution
* const bounds = getCanvasBoundingBox({ canvas: myCanvas });
* console.log(bounds); // Rectangle{x: 10, y: 5, width: 100, height: 200}
* // Optimized for performance with lower resolution scanning
* const fastBounds = getCanvasBoundingBox({
* canvas: largeCanvas,
* width: largeCanvas.width,
* height: largeCanvas.height,
* resolution: 0.5
* });
* // Resolution of 0.5 means scanning at half size, much faster for large canvases
*
* // Using custom dimensions - only analyze part of the canvas
* const partialBounds = getCanvasBoundingBox({ canvas: myCanvas, width: 100, height: 100 });
* // Only analyzes a 100x100 region starting from top-left
* ```
* @param options - The options for measuring the bounding box, including the canvas to measure.
* @returns The bounding box as a Rectangle containing the visible content.
* Returns Rectangle.EMPTY if the canvas is completely transparent.
* @internal
*/
export declare function getCanvasBoundingBox(options: GetCanvasBoundingBoxOptions): Rectangle;
/**
* @param canvas
* @param resolution
* @internal
* @deprecated since 8.10.0
*/
export declare function getCanvasBoundingBox(canvas: ICanvas, resolution?: number): Rectangle;
/**
* Regexp for data URI.
* Based on: {@link https://github.com/ragingwind/data-uri-regex}
* @type {RegExp}
* @default /(?:^data:image\/([\w+]+);(?:[\w=]+|charset=[\w-]+)?(?:;base64)?,)/i
* @example
* import { DATA_URI } from 'pixi.js';
*
* DATA_URI.test('data:image/png;base64,foobar'); // => true
* @category utils
* @advanced
*/
export declare const DATA_URI: RegExp;
/**
* The current version of PixiJS. This is automatically replaced by the build process.
* @internal
*/
export declare const VERSION = "$_VERSION";
/**
* Takes a hash and removes all the `undefined`/`null` values from it.
* In PixiJS, we tend to null properties instead of using 'delete' for performance reasons.
* However, in some cases, this could be a problem if the hash grows too large over time,
* this function can be used to clean a hash.
* @param hash - The hash to clean.
* @returns A new hash with all the `undefined`/`null` values removed.
* @category utils
* @internal
*/
export declare function cleanHash<T>(hash: Record<string, T>): Record<string, T>;
/**
* Removes all `undefined`/`null` elements from the given array and compacts the array.
*
* This function iterates through the array, shifting non-undefined elements to the left
* to fill gaps created by `undefined` elements. The length of the array is then adjusted
* to remove the trailing `undefined` elements.
* @param arr - The array to be cleaned.
* @returns The cleaned array with all `undefined` elements removed.
* @example
* // Example usage:
* const arr = [1, undefined, 2, undefined, 3];
* const cleanedArr = cleanArray(arr);
* console.log(cleanedArr); // Output: [1, 2, 3]
* @category utils
* @internal
*/
export declare function cleanArray<T>(arr: T[]): T[];
/**
* Remove items from a javascript array without generating garbage
* @function removeItems
* @category utils
* @internal
* @param {Array<any>} arr - Array to remove elements from
* @param {number} startIdx - starting index
* @param {number} removeCount - how many to remove
*/
export declare function removeItems(arr: any[], startIdx: number, removeCount: number): void;
/**
* The names of the unique identifiers. These are used to create unique identifiers for different types of objects.
* @category utils
* @internal
*/
export type UIDNames = "default" | "resource" | "texture" | "textureSource" | "textureResource" | "batcher" | "graphicsContext" | "graphicsView" | "graphicsPath" | "fillGradient" | "fillPattern" | "meshView" | "renderable" | "buffer" | "bufferResource" | "geometry" | "instructionSet" | "renderTarget" | "uniform" | "spriteView" | "textView" | "tilingSpriteView" | "shader" | "renderer" | "textStyle" | (string & {});
/**
* Gets the next unique identifier
* @param name - The name of the identifier.
* @returns {number} The next unique identifier to use.
* @category utils
* @internal
*/
export declare function uid(name?: UIDNames): number;
/**
* Resets the next unique identifier to 0. This is used for some tests, dont touch or things WILL explode :)
* @internal
*/
export declare function resetUids(): void;
/**
* Updates the bounds of a quad (a rectangular area) based on the provided texture and anchor point.
*
* This function calculates the minimum and maximum x and y coordinates of the bounds, taking into
* account the texture's original dimensions and any trimming that may have been applied to it.
* @param {BoundsData} bounds - The bounds object to be updated. It contains minX, maxX, minY, and maxY properties.
* @param {ObservablePoint} anchor - The anchor point of the texture, which affects the positioning of the bounds.
* @param {Texture} texture - The texture whose dimensions and trimming information are used to update the bounds.
* @internal
*/
export declare function updateQuadBounds(bounds: BoundsData, anchor: ObservablePoint, texture: Texture): void;
/**
* deprecation name for version 8.0.0
* @ignore
* @internal
*/
export declare const v8_0_0 = "8.0.0";
/**
* deprecation name for version 8.1.0
* @ignore
* @internal
*/
export declare const v8_3_4 = "8.3.4";
interface DeprecationOptions {
/**
* When set to true, all deprecation warning messages will be hidden.
* Use this if you want to silence deprecation notifications.
* @default false
* @standard
*/
quiet: boolean;
/**
* When set to true, deprecation messages will be displayed as plain text without color formatting.
* Use this if you want to disable colored console output for deprecation warnings.
* @default false
* @standard
*/
noColor: boolean;
}
/** @internal */
export type DeprecationFn = ((version: string, message: string, ignoreDepth?: number) => void) & DeprecationOptions;
/**
* Helper for warning developers about deprecated features & settings.
* A stack track for warnings is given; useful for tracking-down where
* deprecated methods/properties/classes are being used within the code.
*
* Deprecation messages can be configured globally:
* ```ts
* // Suppress all deprecation messages
* deprecation.quiet = true;
*
* // Put plain text to console instead of colorful messages
* deprecation.noColor = true;
* ```
* @category utils
* @ignore
* @function deprecation
* @param {string} version - The version where the feature became deprecated
* @param {string} message - Message should include what is deprecated, where, and the new solution
* @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack
* this is mostly to ignore internal deprecation calls.
*/
export declare const deprecation: DeprecationFn;
/**
* Logs a texture to the console as a base64 image.
* This can be very useful for debugging issues with rendering.
* @param texture - The texture to log
* @param renderer - The renderer to use
* @param size - The size of the texture to log in the console
* @ignore
*/
export declare function logDebugTexture(texture: Texture, renderer: Renderer, size?: number): Promise<void>;
/**
* @param container
* @param depth
* @param data
* @param data.color
* @internal
*/
export declare function logScene(container: Container, depth?: number, data?: {
color?: string;
}): void;
/**
* @param renderGroup
* @param depth
* @param data
* @param data.index
* @param data.color
* @internal
*/
export declare function logRenderGroupScene(renderGroup: RenderGroup, depth?: number, data?: {
index: number;
color?: string;
}): void;
/**
* Logs a PixiJS warning message to the console. Stops logging after 500 warnings have been logged.
* @param args - The warning message(s) to log
* @returns {void}
* @category utils
* @ignore
*/
export declare function warn(...args: any[]): void;
/** @internal */
export declare const NOOP: () => void;
/**
* get the resolution / device pixel ratio of an asset by looking for the prefix
* used by spritesheets and image urls
* @category utils
* @internal
* @param {string} url - the image path
* @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set.
* @returns {number} resolution / device pixel ratio of an asset
*/
export declare function getResolutionOfUrl(url: string, defaultValue?: number): number;
/**
* Path utilities for working with URLs and file paths in a cross-platform way.
* All paths that are passed in will become normalized to have posix separators.
* ```js
* import { path } from 'pixi.js';
*
* path.normalize('http://www.example.com/foo/bar/../baz'); // http://www.example.com/foo/baz
* ```
* @category utils
* @advanced
*/
export interface Path {
/**
* Converts a path to posix format.
* @param path - The path to convert to posix
*/
toPosix: (path: string) => string;
/**
* Checks if the path is a URL e.g. http://, https://
* @param path - The path to check
*/
isUrl: (path: string) => boolean;
/**
* Checks if the path is a data URL
* @param path - The path to check
*/
isDataUrl: (path: string) => boolean;
/**
* Checks if the path is a blob URL
* @param path - The path to check
*/
isBlobUrl: (path: string) => boolean;
/**
* Checks if the path has a protocol e.g. http://, https://, file:///, data:, blob:, C:/
* This will return true for windows file paths
* @param path - The path to check
*/
hasProtocol: (path: string) => boolean;
/**
* Returns the protocol of the path e.g. http://, https://, file:///, data:, blob:, C:/
* @param path - The path to get the protocol from
*/
getProtocol: (path: string) => string;
/**
* Converts URL to an absolute path.
* When loading from a Web Worker, we must use absolute paths.
* If the URL is already absolute we return it as is
* If it's not, we convert it
* @param url - The URL to test
* @param baseUrl - The base URL to use
* @param rootUrl - The root URL to use
*/
toAbsolute: (url: string, baseUrl?: string, rootUrl?: string) => string;
/**
* Normalizes the given path, resolving '..' and '.' segments
* @param path - The path to normalize
*/
normalize: (path: string) => string;
/**
* Determines if path is an absolute path.
* Absolute paths can be urls, data urls, or paths on disk
* @param path - The path to test
*/
isAbsolute: (path: string) => boolean;
/**
* Joins all given path segments together using the platform-specific separator as a delimiter,
* then normalizes the resulting path
* @param paths - The segments of the path to join
*/
join: (...paths: string[]) => string;
/**
* Returns the directory name of a path
* @param path - The path to parse
*/
dirname: (path: string) => string;
/**
* Returns the root of the path e.g. /, C:/, file:///, http://domain.com/
* @param path - The path to parse
*/
rootname: (path: string) => string;
/**
* Returns the last portion of a path
* @param path - The path to test
* @param ext - Optional extension to remove
*/
basename: (path: string, ext?: string) => string;
/**
* Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last
* portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than
* the first character of the basename of path, an empty string is returned.
* @param path - The path to parse
*/
extname: (path: string) => string;
/**
* Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties.
* @param path - The path to parse
*/
parse: (path: string) => {
root?: string;
dir?: string;
base?: string;
ext?: string;
name?: string;
};
sep: string;
delimiter: string;
joinExtensions: string[];
}
/**
* Path utilities for working with URLs and file paths in a cross-platform way.
* All paths that are passed in will become normalized to have posix separators.
* @example
* ```ts
* import { path } from 'pixi.js';
*
* // Basic path normalization
* path.normalize('http://www.example.com/foo/bar/../baz');
* // -> 'http://www.example.com/foo/baz'
*
* // Working with file paths
* path.join('assets', 'images', 'sprite.png');
* // -> 'assets/images/sprite.png'
*
* // URL handling
* path.toAbsolute('images/texture.png', 'http://example.com/assets/');
* // -> 'http://example.com/assets/images/texture.png'
* ```
* @remarks
* - Normalizes to POSIX separators (forward slashes)
* - Handles URLs, data URLs, and file paths
* - Supports path composition and decomposition
* - Common in asset loading and URL management
* @category utils
* @standard
* @see {@link Path} For full API reference
* @see {@link DOMAdapter} For platform-specific path handling
*/
export declare const path: Path;
interface Cleanable {
clear(): void;
}
/**
* A singleton collector that manages and provides cleanup for registered pools and caches.
* Useful for cleaning up all pools/caches at once during application shutdown or reset.
* @category utils
* @internal
*/
export declare const GlobalResourceRegistry: {
/**
* Set of registered pools and cleanable objects.
* @private
*/
_registeredResources: Set<Cleanable>;
/**
* Registers a pool or cleanable object for cleanup.
* @param {Cleanable} pool - The pool or object to register.
*/
register(pool: Cleanable): void;
/**
* Unregisters a pool or cleanable object from cleanup.
* @param {Cleanable} pool - The pool or object to unregister.
*/
unregister(pool: Cleanable): void;
/** Clears all registered pools and cleanable objects. This will call clear() on each registered item. */
release(): void;
/**
* Gets the number of registered pools and cleanable objects.
* @returns {number} The count of registered items.
*/
readonly registeredCount: number;
/**
* Checks if a specific pool or cleanable object is registered.
* @param {Cleanable} pool - The pool or object to check.
* @returns {boolean} True if the item is registered, false otherwise.
*/
isRegistered(pool: Cleanable): boolean;
/**
* Removes all registrations without clearing the pools.
* Useful if you want to reset the collector without affecting the pools.
*/
reset(): void;
};
/**
* A type alias for a constructor of a Pool.
* @template T The type of items in the pool. Must extend PoolItem.
* @category utils
* @advanced
*/
export type PoolConstructor<T extends PoolItem> = new () => Pool<T>;
/**
* A group of pools that can be used to store objects of different types.
* @category utils
* @advanced
*/
export declare class PoolGroupClass {
/**
* A map to store the pools by their class type.
* @private
*/
private readonly _poolsByClass;
/**
* Prepopulates a specific pool with a given number of items.
* @template T The type of items in the pool. Must extend PoolItem.
* @param {PoolItemConstructor<T>} Class - The constructor of the items in the pool.
* @param {number} total - The number of items to add to the pool.
*/
prepopulate<T extends PoolItem>(Class: PoolItemConstructor<T>, total: number): void;
/**
* Gets an item from a specific pool.
* @template T The type of items in the pool. Must extend PoolItem.
* @param {PoolItemConstructor<T>} Class - The constructor of the items in the pool.
* @param {unknown} [data] - Optional data to pass to the item's constructor.
* @returns {T} The item from the pool.
*/
get<T extends PoolItem>(Class: PoolItemConstructor<T>, data?: unknown): T;
/**
* Returns an item to its respective pool.
* @param {PoolItem} item - The item to return to the pool.
*/
return(item: PoolItem): void;
/**
* Gets a specific pool based on the class type.
* @template T The type of items in the pool. Must extend PoolItem.
* @param {PoolItemConstructor<T>} ClassType - The constructor of the items in the pool.
* @returns {Pool<T>} The pool of the given class type.
*/
getPool<T extends PoolItem>(ClassType: PoolItemConstructor<T>): Pool<T>;
/** gets the usage stats of each pool in the system */
stats(): Record<string, {
free: number;
used: number;
size: number;
}>;
/** Clears all pools in the group. This will reset all pools and free their resources. */
clear(): void;
}
/**
* A singleton instance of the PoolGroupClass that can be used throughout the application.
* @internal
*/
export declare const BigPool: PoolGroupClass;
/**
* Prints out the version and renderer information for this running instance of PixiJS.
* @param type - The name of the renderer this instance is using.
* @returns {void}
* @category utils
* @advanced
*/
export declare function sayHello(type: string): void;
export {
Buffer$1 as Buffer,
Cache$1 as Cache,
EXT_texture_compression_bptc$1 as EXT_texture_compression_bptc,
EXT_texture_compression_rgtc$1 as EXT_texture_compression_rgtc,
ExtensionFormat as ExtensionFormatLoose,
GPU$1 as GPU,
PredefinedColorSpace$1 as PredefinedColorSpace,
RenderingContext$1 as RenderingContext,
StrictExtensionFormat as ExtensionFormat,
Text$1 as Text,
WEBGL_compressed_texture_etc$1 as WEBGL_compressed_texture_etc,
WEBGL_compressed_texture_etc1$1 as WEBGL_compressed_texture_etc1,
WEBGL_compressed_texture_pvrtc$1 as WEBGL_compressed_texture_pvrtc,
earcut$1 as earcut,
};
export as namespace PIXI;
export {};