Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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