avocado-old/packages/graphics/image.js

91 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-10-27 13:34:44 -05:00
import {BaseTexture, Texture} from '@pixi/core';
import {SCALE_MODES} from '@pixi/constants';
2019-03-18 20:06:47 -05:00
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) {
2019-10-27 13:34:44 -05:00
const baseTexture = BaseTexture.from(
2019-04-19 00:49:46 -05:00
htmlCanvas,
2019-10-27 13:34:44 -05:00
SCALE_MODES.NEAREST
2019-04-19 00:49:46 -05:00
);
const image = new Image();
2019-10-27 13:34:44 -05:00
image.texture = new Texture(baseTexture);
2019-04-19 00:49:46 -05:00
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;
2019-10-27 13:34:44 -05:00
image.texture = new Texture(baseTexture);
2019-03-18 20:06:47 -05:00
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) => {
2019-10-27 13:34:44 -05:00
const baseTexture = BaseTexture.from(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();
2019-10-27 13:34:44 -05:00
subimage.texture = new Texture(this.texture, frame);
2019-03-25 18:53:34 -05:00
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;
}
}