1 | import { ALPHA_MODES } from '@pixi/constants';
|
2 | import { settings } from '@pixi/settings';
|
3 | import { BaseImageResource } from './BaseImageResource.mjs';
|
4 |
|
5 | class ImageBitmapResource extends BaseImageResource {
|
6 | constructor(source, options) {
|
7 | options = options || {};
|
8 | let baseSource;
|
9 | let url;
|
10 | if (typeof source === "string") {
|
11 | baseSource = ImageBitmapResource.EMPTY;
|
12 | url = source;
|
13 | } else {
|
14 | baseSource = source;
|
15 | url = null;
|
16 | }
|
17 | super(baseSource);
|
18 | this.url = url;
|
19 | this.crossOrigin = options.crossOrigin ?? true;
|
20 | this.alphaMode = typeof options.alphaMode === "number" ? options.alphaMode : null;
|
21 | this._load = null;
|
22 | if (options.autoLoad !== false) {
|
23 | this.load();
|
24 | }
|
25 | }
|
26 | load() {
|
27 | if (this._load) {
|
28 | return this._load;
|
29 | }
|
30 | this._load = new Promise(async (resolve, reject) => {
|
31 | if (this.url === null) {
|
32 | resolve(this);
|
33 | return;
|
34 | }
|
35 | try {
|
36 | const response = await settings.ADAPTER.fetch(this.url, {
|
37 | mode: this.crossOrigin ? "cors" : "no-cors"
|
38 | });
|
39 | if (this.destroyed)
|
40 | return;
|
41 | const imageBlob = await response.blob();
|
42 | if (this.destroyed)
|
43 | return;
|
44 | const imageBitmap = await createImageBitmap(imageBlob, {
|
45 | premultiplyAlpha: this.alphaMode === null || this.alphaMode === ALPHA_MODES.UNPACK ? "premultiply" : "none"
|
46 | });
|
47 | if (this.destroyed)
|
48 | return;
|
49 | this.source = imageBitmap;
|
50 | this.update();
|
51 | resolve(this);
|
52 | } catch (e) {
|
53 | if (this.destroyed)
|
54 | return;
|
55 | reject(e);
|
56 | this.onError.emit(e);
|
57 | }
|
58 | });
|
59 | return this._load;
|
60 | }
|
61 | upload(renderer, baseTexture, glTexture) {
|
62 | if (!(this.source instanceof ImageBitmap)) {
|
63 | this.load();
|
64 | return false;
|
65 | }
|
66 | if (typeof this.alphaMode === "number") {
|
67 | baseTexture.alphaMode = this.alphaMode;
|
68 | }
|
69 | return super.upload(renderer, baseTexture, glTexture);
|
70 | }
|
71 | dispose() {
|
72 | if (this.source instanceof ImageBitmap) {
|
73 | this.source.close();
|
74 | }
|
75 | super.dispose();
|
76 | this._load = null;
|
77 | }
|
78 | static test(source) {
|
79 | return !!globalThis.createImageBitmap && typeof ImageBitmap !== "undefined" && (typeof source === "string" || source instanceof ImageBitmap);
|
80 | }
|
81 | static get EMPTY() {
|
82 | ImageBitmapResource._EMPTY = ImageBitmapResource._EMPTY ?? settings.ADAPTER.createCanvas(0, 0);
|
83 | return ImageBitmapResource._EMPTY;
|
84 | }
|
85 | }
|
86 |
|
87 | export { ImageBitmapResource };
|
88 |
|