Source: texture.js

/**
 * @param {string|TexImageSource} texture - A URL to the model texture or an arbitrary image.
 * @public
 * @returns {Promise<TextureAtlas>}
 */
export async function createAtlas(texture) {
    return new TextureAtlas(await resolveTexture(texture));
}

/**
 * A texture atlas. See {@link createAtlas}.
 * @public
 * @hideconstructor
 */
export class TextureAtlas {
    /**
     * @param {HTMLImageElement} texture
     */
    constructor(texture) {
        let canvas = document.createElement("canvas");
        canvas.width = texture.width;
        canvas.height = texture.height;

        this.ctx = canvas.getContext("2d");
        this.ctx.drawImage(texture, 0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height);
    }

    /**
     * Creates an image cutout.
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     * @returns {ImageData}
     * @public
     */
    getTexture(x, y, width, height) {
        return this.ctx.getImageData(x, y, width, height);
    }
}

/**
 * Resolves a texture.
 * @param {string|TexImageSource} texture - A URL to the model texture or an arbitrary image.
 * @returns {Promise<TexImageSource>}
 * @public
 */
export async function createTexture(texture) {
    if (typeof texture === "string") {
        let blob = await (await fetch(texture)).blob();
        return await self.createImageBitmap(blob);
    } else {
        return texture;
    }
}