A 2D texture class that extends AbstractTexture and provides functionality for creating, loading, and managing textures from various sources including images, compressed formats (Basis, KTX2), and raw data.

This class supports:

  • Loading textures from URLs, HTML image elements, and data URIs
  • Compressed texture formats (Basis Universal, KTX2)
  • Mipmap generation and management
  • Automatic memory management with finalization registry
  • Both WebGL and WebGPU backends
// Load texture from URL
const texture = await Texture.loadFromUrl('path/to/image.jpg');

// Create texture from image element
const texture2 = new Texture();
await texture2.generateTextureFromImage(imageElement);

// Generate 1x1 solid color texture
const whiteTexture = new Texture();
await whiteTexture.generate1x1TextureFrom('rgba(255,255,255,1)');

Hierarchy (view full)

Implements

  • Disposable

Constructors

Properties

__canvasContext?: CanvasRenderingContext2D
__format: EnumIO = PixelFormat.RGBA
__hasTransparentPixels: boolean = false
__height: number = 0
__htmlCanvasElement?: HTMLCanvasElement
__htmlImageElement?: HTMLImageElement
__img?: HTMLImageElement
__internalFormat: TextureFormatEnum = TextureFormat.RGBA8
__isTextureReady: boolean = false
__level: number = 0
__mipLevelCount: number = 1
__name: string = 'untitled'
__startedToLoad: boolean = false
__type: ComponentTypeEnum = ComponentType.UnsignedByte
__uri?: string
__width: number = 0
_recommendedTextureSampler?: Sampler
_samplerResourceUid: number = -1
_tags: RnTags = {}

Collection of tags associated with this object

_textureResourceUid: number = -1
_textureViewAsRenderTargetResourceUid: number = -1
_textureViewResourceUid: number = -1
autoDetectTransparency: boolean = false

Whether to automatically detect transparency in loaded images

InvalidObjectUID: -1 = -1

Invalid object UID constant

currentMaxObjectCount: number = 0

Current maximum object count for UID generation

Accessors

  • get htmlCanvasElement(): HTMLCanvasElement
  • Gets or creates an HTML canvas element with the texture content. If an image element exists, it will be drawn onto the canvas.

    Returns HTMLCanvasElement

    The HTML canvas element containing the texture data

  • get htmlImageElement(): undefined | HTMLImageElement
  • Gets the HTML image element associated with this texture.

    Returns undefined | HTMLImageElement

    The HTML image element or undefined if not available

  • get isTextureReady(): boolean
  • Checks if the texture is ready for use.

    Returns boolean

    True if the texture is ready, false otherwise

  • get isTransparent(): boolean
  • Checks if the texture contains transparent pixels.

    Returns boolean

    True if the texture has transparency, false otherwise

  • get objectUID(): number
  • Gets the unique object identifier

    Returns number

    The object's UID

  • get startedToLoad(): boolean
  • Checks if the texture has started loading.

    Returns boolean

    True if loading has started, false otherwise

  • get uniqueName(): string
  • Gets the unique name of this object

    Returns string

    The unique name string

  • get uri(): undefined | string
  • Gets the URI/URL of the texture source.

    Returns undefined | string

    The texture URI or undefined if not set

Methods

  • Symbol.dispose implementation for automatic resource cleanup. Called automatically when using 'using' declarations in TypeScript 5.2+.

    Returns void

  • Allocates an empty texture with specified dimensions and format. The texture can be filled with data later using loadImageToMipLevel.

    Parameters

    • desc: {
          format: TextureFormatEnum;
          height: number;
          mipLevelCount?: number;
          width: number;
      }

      Texture allocation descriptor

      • format: TextureFormatEnum

        Texture format

      • height: number

        Texture height in pixels

      • OptionalmipLevelCount?: number

        Number of mip levels (auto-calculated if not provided)

      • width: number

        Texture width in pixels

    Returns void

    const texture = new Texture();
    texture.allocate({
    width: 512,
    height: 512,
    format: TextureFormat.RGBA8
    });
  • Destroys the texture and releases all associated resources. This includes GPU memory, finalization registry entries, and other cleanup. After calling this method, the texture should not be used.

    Returns void

  • Destroys the 3D API resources associated with this texture. This releases GPU memory and invalidates the texture.

    Returns boolean

    Always returns true

  • Generates a 1x1 pixel texture with a solid color. Useful for creating placeholder textures or solid color materials.

    Parameters

    • rgbaStr: string = 'rgba(255,255,255,1)'

      CSS color string in rgba format (default: 'rgba(255,255,255,1)')

    Returns Promise<void>

    Promise that resolves when texture is ready

    const texture = new Texture();
    await texture.generate1x1TextureFrom('rgba(255,0,0,1)'); // Red texture
  • Generates a compressed texture from raw typed array data.

    Parameters

    • typedArray: TypedArray

      The compressed texture data

    • width: number

      Texture width in pixels

    • height: number

      Texture height in pixels

    • compressionTextureType: CompressionTextureTypeEnum

      Type of compression used

    Returns Promise<void>

    Promise that resolves when texture is ready

    const texture = new Texture();
    await texture.generateCompressedTextureFromTypedArray(
    compressedData,
    512,
    512,
    CompressionTextureType.S3TC_DXT1
    );
  • Generates a compressed texture with mipmaps from an array of texture data. Each TextureData object represents a different mip level.

    Parameters

    Returns Promise<void>

    Promise that resolves when texture is ready

    Error if level 0 texture data is not found

    const texture = new Texture();
    const mipmapData = [
    { level: 0, width: 512, height: 512, buffer: level0Data },
    { level: 1, width: 256, height: 256, buffer: level1Data },
    // ... more levels
    ];
    await texture.generateCompressedTextureWithMipmapFromTypedArray(
    mipmapData,
    CompressionTextureType.S3TC_DXT1
    );
  • Generates mipmaps for the texture automatically. The texture must already be loaded and ready before calling this method.

    Returns void

    const texture = new Texture();
    await texture.generateTextureFromUrl('image.jpg', { generateMipmap: false });
    texture.generateMipmaps(); // Generate mipmaps manually
  • Generates a sheen lookup table texture from embedded data URI. This is used for physically-based rendering (PBR) sheen calculations. Requires the PBR module to be loaded.

    Returns Promise<void>

    Promise that resolves when texture is ready

    Error if PBR module is not available

  • Generates a texture from Basis Universal compressed data. Basis Universal is a supercompressed GPU texture codec that supports multiple formats.

    Parameters

    • uint8Array: Uint8Array

      The Basis Universal compressed data

    • options: {
          format?: EnumIO;
          generateMipmap?: boolean;
          internalFormat?: TextureParameterEnum;
          level?: number;
          type?: ComponentTypeEnum;
      }

      Configuration options for texture generation

      • Optionalformat?: EnumIO

        Pixel format (default: RGBA)

      • OptionalgenerateMipmap?: boolean

        Whether to generate mipmaps (default: true)

      • OptionalinternalFormat?: TextureParameterEnum

        Internal texture format (default: RGBA8)

      • Optionallevel?: number

        Mip level (default: 0)

      • Optionaltype?: ComponentTypeEnum

        Component type (default: UnsignedByte)

    Returns Promise<void>

    Promise that resolves when texture is ready

    const texture = new Texture();
    const basisData = new Uint8Array(basisFileBuffer);
    await texture.generateTextureFromBasis(basisData);
  • Generates a texture from an HTML image element.

    Parameters

    • image: HTMLImageElement

      The HTML image element to create texture from

    • options: {
          format: undefined | EnumIO;
          generateMipmap: undefined | boolean;
          internalFormat: undefined | TextureFormatEnum;
          level: undefined | number;
          type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">;
      } = {}

      Configuration options for texture generation

      • format: undefined | EnumIO

        Pixel format (default: RGBA)

      • generateMipmap: undefined | boolean

        Whether to generate mipmaps (default: true)

      • internalFormat: undefined | TextureFormatEnum

        Internal texture format (default: RGBA8)

      • level: undefined | number

        Mip level (default: 0)

      • type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">

        Component type (default: UnsignedByte)

    Returns Promise<void>

    Promise that resolves when texture is ready

    const texture = new Texture();
    const img = document.getElementById('myImage') as HTMLImageElement;
    await texture.generateTextureFromImage(img, { generateMipmap: false });
  • Generates a texture from KTX2 compressed data. KTX2 is a container format for GPU textures that supports various compression formats.

    Parameters

    • uint8Array: Uint8Array

      The KTX2 compressed data

    Returns Promise<void>

    Promise that resolves when texture is ready

    const texture = new Texture();
    const ktx2Data = new Uint8Array(ktx2FileBuffer);
    await texture.generateTextureFromKTX2(ktx2Data);
  • Generates a texture by loading an image from a URL. Supports both regular URLs and data URIs. For external URLs, CORS is handled automatically.

    Parameters

    • imageUri: string

      The URL or data URI of the image to load

    • options: {
          format: undefined | EnumIO;
          generateMipmap: undefined | boolean;
          internalFormat: undefined | TextureFormatEnum;
          level: undefined | number;
          type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">;
      } = {}

      Configuration options for texture generation

      • format: undefined | EnumIO

        Pixel format (default: RGBA)

      • generateMipmap: undefined | boolean

        Whether to generate mipmaps (default: true)

      • internalFormat: undefined | TextureFormatEnum

        Internal texture format (default: RGBA8)

      • level: undefined | number

        Mip level (default: 0)

      • type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">

        Component type (default: UnsignedByte)

    Returns Promise<void>

    Promise that resolves when texture is loaded and ready

    const texture = new Texture();
    await texture.generateTextureFromUrl('https://example.com/image.jpg');
  • Retrieves image data from a rectangular region of the texture. Creates an internal canvas context if one doesn't exist.

    Parameters

    • x: number

      The x-coordinate of the top-left corner

    • y: number

      The y-coordinate of the top-left corner

    • width: number

      The width of the region

    • height: number

      The height of the region

    Returns ImageData

    ImageData object containing the pixel data

  • Gets a single pixel value at the specified coordinates as a specific type. Supports various color and vector types for different use cases.

    Parameters

    • x: number

      The x-coordinate of the pixel

    • y: number

      The y-coordinate of the pixel

    • typeClass:
          | typeof Vector3
          | typeof Vector4
          | typeof MutableVector3
          | typeof MutableVector4
          | typeof ColorRgb
          | typeof ColorRgba

      The class type to return the pixel as (ColorRgb, ColorRgba, Vector3, etc.)

    Returns any

    An instance of the specified type containing the pixel data

  • Gets the pixel data at the specified coordinates as a raw Uint8ClampedArray. This provides direct access to the RGBA values as 8-bit integers.

    Parameters

    • x: number

      The x-coordinate of the pixel

    • y: number

      The y-coordinate of the pixel

    Returns Uint8ClampedArray

    A Uint8ClampedArray containing the RGBA pixel data

  • Retrieves the value associated with a specific tag name

    Parameters

    • tagName: string

      The name of the tag whose value to retrieve

    Returns any

    The tag value, or undefined if the tag doesn't exist

  • Checks whether this object has a tag with the specified name

    Parameters

    • tagName: string

      The name of the tag to check for

    Returns boolean

    True if the tag exists (value is not null/undefined), false otherwise

  • Imports an existing WebGL texture directly without copying data. This is useful for integrating with external WebGL code or libraries.

    Parameters

    • webGLTexture: WebGLTexture

      The WebGL texture object to import

    • width: number = 0

      Texture width in pixels (default: 0)

    • height: number = 0

      Texture height in pixels (default: 0)

    Returns void

    const texture = new Texture();
    const webglTexture = gl.createTexture();
    // ... set up webglTexture
    texture.importWebGLTextureDirectly(webglTexture, 512, 512);
  • Loads image data to a specific mip level of an allocated texture. The texture must be allocated first using the allocate method.

    Parameters

    Returns Promise<void>

    Promise that resolves when data is loaded

    await texture.loadImageToMipLevel({
    mipLevel: 0,
    xOffset: 0,
    yOffset: 0,
    width: 256,
    height: 256,
    data: imageData,
    rowSizeByPixel: 256,
    type: ComponentType.UnsignedByte
    });
  • Checks if this object has a tag with the specified name and value

    Parameters

    • tagName: string

      The tag name to match

    • tagValue: string

      The tag value to match

    Returns boolean

    True if the object has a matching tag, false otherwise

  • Checks if this object has all the specified tags with exactly matching values

    Parameters

    • tags: RnTags

      Object containing tag names as keys and expected values

    Returns boolean

    True if all specified tags exist with matching values, false otherwise

  • Checks if the object's combined tag string contains all the provided search strings. This allows for flexible searching within tag names and values.

    Parameters

    • stringArray: string[]

      Array of strings that must all be present in the combined tag string

    Returns boolean

    True if all strings are found in the combined tag string, false otherwise

  • Sets a specific channel value for a pixel at the given coordinates. Useful for modifying individual color channels (R, G, B, A).

    Parameters

    • x: number

      The x-coordinate of the pixel

    • y: number

      The y-coordinate of the pixel

    • channelIdx: number

      The channel index (0=R, 1=G, 2=B, 3=A)

    • value: number

      The new value for the channel (0-255)

    Returns void

  • Attempts to set a tag on this object. If the tag already exists, it will be replaced.

    Parameters

    • tag: Tag

      The tag object containing the name and value to set

    Returns boolean

    True if the tag was successfully set, false if the tag name contains invalid characters

  • Attempts to set a unique name for this object

    Parameters

    • name: string

      The desired unique name

    • toAddNameIfConflict: boolean

      If true, appends UID to make name unique when conflicts occur; if false, fails on conflict

    Returns boolean

    True if the name was successfully set, false if there was a conflict and toAddNameIfConflict was false

  • Validates that a tag string contains only allowed characters (alphanumeric and underscore)

    Parameters

    • val: string

      The string to validate

    Returns boolean

    True if the string contains only valid characters, false if it contains invalid characters

  • Static factory method to create and load a texture from a URL. This is a convenience method that combines texture creation and loading.

    Parameters

    • uri: string

      The URL or data URI of the image to load

    • options: {
          format: undefined | EnumIO;
          generateMipmap: undefined | boolean;
          internalFormat: undefined | TextureFormatEnum;
          level: undefined | number;
          type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">;
      } = {}

      Configuration options for texture generation

      • format: undefined | EnumIO

        Pixel format (default: RGBA)

      • generateMipmap: undefined | boolean

        Whether to generate mipmaps (default: true)

      • internalFormat: undefined | TextureFormatEnum

        Internal texture format (default: RGBA8)

      • level: undefined | number

        Mip level (default: 0)

      • type: undefined | ComponentTypeClass<"UNSIGNED_BYTE">

        Component type (default: UnsignedByte)

    Returns Promise<Texture>

    Promise that resolves to the loaded texture

    const texture = await Texture.loadFromUrl('https://example.com/image.jpg', {
    generateMipmap: false,
    format: PixelFormat.RGB
    });
  • Searches for the first object that has a specific tag with the given value

    Parameters

    • tag: string

      The tag name to search for

    • value: string

      The tag value to match

    Returns undefined | WeakRef<RnObject>

    WeakRef to the first matching object, or undefined if not found