import {BaseTexture, Texture} from '@pixi/core'; import {SCALE_MODES} from '@pixi/constants'; import {Resource} from '@avocado/resource'; export class Image extends Resource { constructor() { super(); this.texture = null; } destroy() { this.texture.destroy(); } static fromHtmlCanvas(htmlCanvas) { const baseTexture = BaseTexture.from( htmlCanvas, SCALE_MODES.NEAREST ); const image = new Image(); image.texture = new Texture(baseTexture); return image; } static load(uri) { return this.loadBaseTexture(uri).then((baseTexture) => { const image = new Image(); image.uri = uri; image.texture = new Texture(baseTexture); return image; }); } static loadBaseTexture(uri) { if (!this.baseTextureCache) { this.baseTextureCache = {}; } if (this.baseTextureCache[uri]) { return Promise.resolve(this.baseTextureCache[uri]); } return new Promise((resolve, reject) => { const baseTexture = BaseTexture.from(uri); baseTexture.once('error', () => { reject(new Error(`Couldn't load image "${uri}"`)); }); baseTexture.once('loaded', () => { resolve(this.baseTextureCache[uri] = baseTexture); }); }); } get height() { if (!this.texture) { return 0; } return this.texture.height; } get size() { return [this.width, this.height]; } subimage(rectangle) { const frame = { x: rectangle[0], y: rectangle[1], width: rectangle[2], height: rectangle[3], }; const subimage = new Image(); subimage.texture = new Texture(this.texture, frame); return subimage; } updateBaseTexture() { if (this.texture && this.texture.baseTexture) { this.texture.baseTexture.update(); } } get width() { if (!this.texture) { return 0; } return this.texture.width; } }