Skip to content

Instantly share code, notes, and snippets.

@Dragon3DGraff
Last active August 30, 2023 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dragon3DGraff/fbfde6df6d4ad7bc5efbd7e036878d66 to your computer and use it in GitHub Desktop.
Save Dragon3DGraff/fbfde6df6d4ad7bc5efbd7e036878d66 to your computer and use it in GitHub Desktop.
Making atlas from several images
import {
Texture,
ImageLoader,
RGBFormat,
CanvasTexture,
} from "../build/three.module.js";
export const makeAtlas = (images, size, width, height) => {
return new Promise((resolve) => {
loadAllImages(images).then((data) =>
composeToOneImage(data, size, width, height).then((texture) =>
resolve(texture)
)
);
});
};
const composeToOneImage = (images, size, width, height) => {
return new Promise((resolve) => {
console.time("canvas");
let texture
const extractCanvas = document.createElement("canvas");
extractCanvas.width = width;
extractCanvas.height = height;
const graphics = extractCanvas.getContext("2d");
const columnsCount = width / size;
let x = 0;
let y = 0;
images.map((img) => {
if (x > columnsCount - 1) {
x = 0;
y++;
}
graphics.drawImage(img, x * size, y * size, size, size);
x++;
});
texture = new CanvasTexture(extractCanvas);
texture.format = RGBFormat;
texture.needsUpdate = true;
texture.flipY = false;
resolve(texture);
console.timeEnd("canvas");
});
};
const loadAllImages = (array) => {
return Promise.all(array.map((item) => imageLoader(item)));
};
const imageLoader = (url) => {
return new Promise((resolve, reject) => {
let loader = new ImageLoader();
loader.load(
url,
(img) => {
resolve(img);
},
() => {
reject();
}
);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment