avocado-old/packages/graphics/image.js

90 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-03-18 20:06:47 -05:00
const PIXI = 'undefined' !== typeof window ? require('pixi.js') : undefined;
import {Resource} from '@avocado/resource';
export class Image extends Resource {
constructor() {
super();
this.texture = null;
}
2019-04-14 16:11:01 -05:00
destroy() {
this.texture.destroy();
}
2019-04-19 00:49:46 -05:00
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;
}
2019-03-18 20:06:47 -05:00
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]);
2019-03-18 20:06:47 -05:00
}
return new Promise((resolve, reject) => {
const baseTexture = PIXI.BaseTexture.fromImage(uri);
2019-03-21 00:09:17 -05:00
baseTexture.once('error', () => {
2019-03-18 20:06:47 -05:00
reject(new Error(`Couldn't load image "${uri}"`));
});
2019-03-21 00:09:17 -05:00
baseTexture.once('loaded', () => {
resolve(this.baseTextureCache[uri] = baseTexture);
2019-03-18 20:06:47 -05:00
});
});
}
get height() {
if (!this.texture) {
return 0;
}
return this.texture.height;
}
get size() {
return [this.width, this.height];
}
2019-03-25 18:53:34 -05:00
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;
}
2019-04-19 00:49:46 -05:00
updateBaseTexture() {
if (this.texture && this.texture.baseTexture) {
this.texture.baseTexture.update();
}
}
2019-03-18 20:06:47 -05:00
get width() {
if (!this.texture) {
return 0;
}
return this.texture.width;
}
}