@spearwolf/twopoint5d
Version:
a library to create 2.5d realtime graphics and pixelart with three.js
43 lines • 1.66 kB
JavaScript
import { ImageLoader } from 'three';
import { findNextPowerOf2 } from '../utils/findNextPowerOf2.js';
import { isPowerOf2 } from '../utils/isPowerOf2.js';
import { TextureCoords } from './TextureCoords.js';
export class PowerOf2ImageLoader {
#imageLoader;
get imageLoader() {
if (!this.#imageLoader) {
this.#imageLoader = new ImageLoader();
}
return this.#imageLoader;
}
set imageLoader(loader) {
this.#imageLoader = loader;
}
load(url, onLoadCallback, onErrorCallback) {
this.imageLoader.load(url, (img) => {
if (!isPowerOf2(img.width) || !isPowerOf2(img.height)) {
const width = findNextPowerOf2(img.width);
const height = findNextPowerOf2(img.height);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(img, 0, 0);
const imgTexCoords = new TextureCoords(0, 0, width, height);
const texCoords = new TextureCoords(imgTexCoords, 0, 0, img.width, img.height);
onLoadCallback({ imgEl: canvas, texCoords });
}
else {
onLoadCallback({
imgEl: img,
texCoords: new TextureCoords(0, 0, img.width, img.height),
});
}
}, undefined, onErrorCallback);
}
loadAsync(url) {
return new Promise((resolve, reject) => {
this.load(url, resolve, reject);
});
}
}
//# sourceMappingURL=PowerOf2ImageLoader.js.map