90 lines
1.9 KiB
JavaScript
90 lines
1.9 KiB
JavaScript
const PIXI = 'undefined' !== typeof window ? require('pixi.js') : undefined;
|
|
|
|
import {Resource} from '@avocado/resource';
|
|
|
|
export class Image extends Resource {
|
|
|
|
constructor() {
|
|
super();
|
|
this.texture = null;
|
|
}
|
|
|
|
destroy() {
|
|
this.texture.destroy();
|
|
}
|
|
|
|
static fromHtmlCanvas(htmlCanvas) {
|
|
const baseTexture = PIXI.BaseTexture.fromCanvas(
|
|
htmlCanvas,
|
|
PIXI.SCALE_MODES.NEAREST
|
|
);
|
|
const image = new Image();
|
|
image.texture = new PIXI.Texture(baseTexture);
|
|
return image;
|
|
}
|
|
|
|
static load(uri) {
|
|
return this.loadBaseTexture(uri).then((baseTexture) => {
|
|
const image = new Image();
|
|
image.uri = uri;
|
|
image.texture = new PIXI.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 = PIXI.BaseTexture.fromImage(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 PIXI.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;
|
|
}
|
|
|
|
}
|