-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (74 loc) · 2.63 KB
/
script.js
File metadata and controls
85 lines (74 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
document.getElementById('fileInput').addEventListener('change', async (event) => {
// Get files
const files = event.target.files;
if (!files.length) return;
const images = await Promise.all([...files].map(loadImage));
const { canvas, metadata } = packImages(images);
// Clear output
const output = document.getElementById('output');
output.innerHTML = '';
// Show canvas
document.getElementById('output').innerHTML = '';
document.getElementById('output').appendChild(canvas);
// Create download links container
const linkContainer = document.createElement('div');
linkContainer.id = 'downloadLinks';
output.appendChild(linkContainer);
// Download canvas as PNG
const link = document.createElement('a');
link.download = 'spritesheet.png';
link.href = canvas.toDataURL();
link.textContent = 'Download Spritesheet';
link.style.display = 'block';
linkContainer.appendChild(link); // Append to links container
// Format metadata
const jsonData = { frames: {} };
metadata.forEach(({ name, x, y, width, height }) => {
jsonData.frames[name] = {
frame: { x, y, w: width, h: height }
};
});
// Download metadata as JSON
const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' });
const jsonLink = document.createElement('a');
jsonLink.download = 'spritesheet.json';
jsonLink.href = URL.createObjectURL(jsonBlob);
jsonLink.textContent = 'Download JSON Metadata';
jsonLink.style.display = 'block';
linkContainer.appendChild(jsonLink); // Append to links container
// Show canvas below links
output.appendChild(canvas);
});
// Function to get the details of image
function loadImage(file) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => resolve({ img, name: file.name, width: img.width, height: img.height });
img.src = URL.createObjectURL(file);
});
}
// Function to combine the images into a spritesheet/atlas
function packImages(images, canvasSize = 8192) {
const canvas = document.createElement('canvas');
canvas.width = canvasSize;
canvas.height = canvasSize;
const ctx = canvas.getContext('2d');
let x = 0, y = 0, rowHeight = 0;
const metadata = [];
for (const { img, name, width, height } of images) {
if (x + width > canvasSize) {
x = 0;
y += rowHeight;
rowHeight = 0;
}
if (y + height > canvasSize) {
alert('Canvas size too big! Try fewer or smaller images.');
break;
}
ctx.drawImage(img, x, y, width, height);
metadata.push({ name, x, y, width, height });
x += width;
rowHeight = Math.max(rowHeight, height);
}
return { canvas, metadata };
}