-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
491 lines (398 loc) · 15.9 KB
/
script.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// Unicorn Pixel Art Editor
// Version 1.0 by Jim Moore - September 2023
// A simple tool to generate and export pixel maps and palettes for Pimoroni Unicorn LED panels.
// For more information, visit: https://shop.pimoroni.com/products/space-unicorns
// Read the documentation for guidance on using this code.
// Repurpose this code as needed
// Configuration Object
const config = {
unicornGridSizes: {
'Stellar Unicorn': '16,16',
'Galactic Unicorn': '53,11',
'Cosmic Unicorn': '32,32'
},
defaultUnicornGrid: 'Stellar Unicorn',
defaultPaletteColors: ['#000000', '#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ffffff'],
canvasStrokeStyle: '#9a9a9a',
canvasFillColor: '#000000'
};
// Initialization
const defaultUnicornGrid = config.defaultUnicornGrid;
var gridSize = parseGridSize(config.unicornGridSizes[defaultUnicornGrid]);
let grid = createEmptyGrid(gridSize.width, gridSize.height, config.canvasFillColor);
let paletteColors = [...config.defaultPaletteColors];
let selectedColor = '';
let jsonData;
// Color Maps Setup
const colorToIndexMap = {};
const indexToGridPositionsMap = {};
// Palette Functions
function createPalette() {
const paletteContainer = document.getElementById('color-palette');
paletteContainer.innerHTML = '';
paletteColors.forEach((color, index) => {
const swatch = createSwatch(color);
swatch.addEventListener('click', () => {
selectedColor = color;
highlightSelectedSwatch(swatch);
});
paletteContainer.appendChild(swatch);
colorToIndexMap[color] = index;
indexToGridPositionsMap[index] = [];
});
const defaultSelectedSwatch = document.querySelector('.swatch:first-child');
highlightSelectedSwatch(defaultSelectedSwatch);
}
function editPalette() {
const newPaletteColors = prompt("Edit the palette (comma-separated hex values):", paletteColors.join(','));
if (newPaletteColors !== null) {
const colorsArray = newPaletteColors.split(',').map(color => color.trim());
if (colorsArray.length > 0) {
const oldSelectedColor = selectedColor;
const oldPaletteColors = paletteColors.slice();
paletteColors = colorsArray;
createPalette();
const colorMapping = createColorMapping(oldPaletteColors, paletteColors);
for (let x = 0; x < gridSize.width; x++) {
for (let y = 0; y < gridSize.height; y++) {
const currentColor = grid[x][y];
if (colorMapping.hasOwnProperty(currentColor)) {
grid[x][y] = colorMapping[currentColor];
}
}
}
if (colorMapping.hasOwnProperty(oldSelectedColor)) {
selectedColor = colorMapping[oldSelectedColor];
}
drawGrid();
} else {
alert("Invalid input. Please enter at least one color.");
}
}
}
function createSwatch(color) {
const swatch = document.createElement('div');
swatch.classList.add('swatch');
swatch.style.backgroundColor = color;
return swatch;
}
function highlightSelectedSwatch(swatch) {
const swatches = document.querySelectorAll('.swatch');
swatches.forEach((s) => {
s.classList.remove('selected-swatch');
});
swatch.classList.add('selected-swatch');
}
// Utility Functions
function hexToRgb(hex) {
hex = hex.replace(/^#/, '');
const bigint = parseInt(hex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return { r, g, b };
}
function rgbToHex(r, g, b) {
return `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)}`;
}
function formatPythonCode(data) {
const indent = ' ';
// Formatting the grid and removing the last comma
let formattedGrid = data.grid.map(row => `[${row.join(', ')}],`).join(`\n${indent + indent}`);
formattedGrid = formattedGrid.substring(0, formattedGrid.length - 1);
// Formatting the palette and removing the last comma
let formattedPalette = data.palette.map(color => JSON.stringify(color) + ',').join(`\n${indent + indent}`);
formattedPalette = formattedPalette.substring(0, formattedPalette.length - 1);
// Assembling the final code with value and label
const formattedCode = `data = {
${indent}"value": "none",
${indent}"label": "None",
${indent}"grid": [
${indent + indent}${formattedGrid}
${indent}],
${indent}"palette": [
${indent + indent}${formattedPalette}
${indent}]
}`;
return formattedCode;
}
// Grid Functions
function drawGrid() {
const canvas = document.getElementById('pixel-canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = config.canvasStrokeStyle;
ctx.lineWidth = 1;
const cellWidth = canvas.width / gridSize.width;
const cellHeight = canvas.height / gridSize.height;
for (let x = 0; x < gridSize.width; x++) {
for (let y = 0; y < gridSize.height; y++) {
const xPos = x * cellWidth;
const yPos = y * cellHeight;
ctx.fillStyle = grid[x][y] || config.canvasFillColor;
ctx.fillRect(xPos, yPos, cellWidth, cellHeight);
ctx.strokeStyle = config.canvasStrokeStyle;
ctx.strokeRect(xPos, yPos, cellWidth, cellHeight);
}
}
}
function changeGridSize(size) {
const canvas = document.getElementById("pixel-canvas");
const ctx = canvas.getContext("2d");
const pixelSize = 16;
gridSize = parseGridSize(size);
const maxSize = Math.max(gridSize.width, gridSize.height);
const canvasWidth = gridSize.width * pixelSize;
const canvasHeight = gridSize.height * pixelSize;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let x = 0; x <= canvas.width; x += pixelSize) {
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
}
for (let y = 0; y <= canvas.height; y += pixelSize) {
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
}
ctx.strokeStyle = config.canvasStrokeStyle;
ctx.stroke();
console.log(`Canvas resized to: ${canvas.width}x${canvas.height}`);
grid = createEmptyGrid(gridSize.width, gridSize.height, config.canvasFillColor);
drawGrid();
}
function createEmptyGrid(width, height, defaultValue) {
return new Array(width).fill(null).map(() => new Array(height).fill(defaultValue));
}
function parseGridSize(size) {
const dimensions = size.split(",");
const widthInPixels = parseInt(dimensions[0], 10);
const heightInPixels = parseInt(dimensions[1], 10);
return { width: widthInPixels, height: heightInPixels };
}
// Pixel Manipulation Functions
function shiftPixels(dx, dy) {
const newGrid = createEmptyGrid(gridSize.width, gridSize.height, 0);
for (let x = 0; x < gridSize.width; x++) {
for (let y = 0; y < gridSize.height; y++) {
const newX = (x + dx + gridSize.width) % gridSize.width;
const newY = (y + dy + gridSize.height) % gridSize.height;
newGrid[newX][newY] = grid[x][y];
}
}
grid = newGrid;
drawGrid();
}
function shiftLeft() {
shiftPixels(-1, 0);
}
function shiftRight() {
shiftPixels(1, 0);
}
function shiftUp() {
shiftPixels(0, -1);
}
function shiftDown() {
shiftPixels(0, 1);
}
// Data Export & Import Functions
function exportGrid() {
const exportData = {
grid: [],
palette: paletteColors.map(color => hexToRgb(color))
};
for (let y = 0; y < gridSize.height; y++) {
const row = [];
for (let x = 0; x < gridSize.width; x++) {
const color = grid[x][y];
const index = colorToIndexMap[color];
row.push(index === undefined ? 0 : index);
}
exportData.grid.push(row);
}
const formattedPythonCode = formatPythonCode(exportData);
const exportTextBox = document.getElementById("export-text-box");
exportTextBox.textContent = formattedPythonCode;
exportTextBox.style.display = 'block';
toggleExportButtons(true); // Call the function to show the buttons
}
function createColorMapping(oldColors, newColors) {
const colorMapping = {};
oldColors.forEach((oldColor, index) => {
colorMapping[oldColor] = newColors[index];
});
return colorMapping;
}
function loadTemplate() {
const templateSelect = document.getElementById('template-select');
const selectedTemplateIndex = templateSelect.selectedIndex;
// Get the selected grid size
const gridSizeSelect = document.getElementById('grid-size-select');
const selectedGridSize = gridSizeSelect.value;
// Use the template data based on the selected grid size
const templates = gridTemplates[selectedGridSize];
if (templates && selectedTemplateIndex >= 0) {
const selectedTemplateData = templates[selectedTemplateIndex];
loadGridAndPalette(selectedTemplateData);
}
}
const selectButton = document.getElementById('select-all-button');
selectButton.addEventListener('click', selectAllText);
function selectAllText() {
const preElement = document.getElementById('export-text-box');
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(preElement);
selection.removeAllRanges();
selection.addRange(range);
}
// Add an event listener to the "Copy to Clipboard" button
const copyButton = document.getElementById('copy-clipboard-button');
copyButton.addEventListener('click', copyToClipboard);
// Function to copy text to the clipboard
function copyToClipboard() {
const preElement = document.getElementById('export-text-box');
const textToCopy = preElement.textContent;
navigator.clipboard.writeText(textToCopy)
}
function loadGridAndPalette(templateData) {
paletteColors = templateData.palette.map((rgbColor) => {
return rgbToHex(rgbColor.r, rgbColor.g, rgbColor.b);
});
createPalette();
gridSize = { width: templateData.grid[0].length, height: templateData.grid.length };
grid = createEmptyGrid(gridSize.width, gridSize.height, '');
for (let x = 0; x < gridSize.width; x++) {
for (let y = 0; y < gridSize.height; y++) {
const colorIndex = templateData.grid[y][x];
grid[x][y] = paletteColors[colorIndex];
}
}
const canvas = document.getElementById('pixel-canvas');
const cellWidth = canvas.width / gridSize.width;
const cellHeight = canvas.height / gridSize.height;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let x = 0; x < gridSize.width; x++) {
for (let y = 0; y < gridSize.height; y++) {
const xPos = x * cellWidth;
const yPos = y * cellHeight;
ctx.fillStyle = grid[x][y];
ctx.fillRect(xPos, yPos, cellWidth, cellHeight);
ctx.strokeStyle = config.canvasStrokeStyle;
ctx.strokeRect(xPos, yPos, cellWidth, cellHeight);
}
}
}
function populateTemplateDropdown() {
const templateSelectContainer = document.getElementById("template-select-container");
const templateSelect = document.getElementById("template-select");
templateSelect.innerHTML = ''; // Clear existing options
// Get the selected grid size
const gridSizeSelect = document.getElementById('grid-size-select');
const selectedGridSize = gridSizeSelect.value;
// Use the template data based on the selected grid size
const templates = gridTemplates[selectedGridSize];
if (templates) {
templates.forEach((template, index) => {
const option = document.createElement('option');
option.value = `template${index + 1}`;
option.textContent = `${template.label}`;
templateSelect.appendChild(option);
});
} else {
// Handle the case when templates are not available for the selected grid size
const option = document.createElement('option');
option.textContent = 'No templates available';
templateSelect.appendChild(option);
}
loadTemplate(); // Load the default template
}
// Event Listeners
const canvas = document.getElementById('pixel-canvas');
canvas.addEventListener('mousedown', function (e) {
const cellSize = canvas.width / gridSize.width;
const x = Math.floor(e.offsetX / cellSize);
const y = Math.floor(e.offsetY / cellSize);
grid[x][y] = selectedColor;
drawGrid();
});
document.getElementById('shift-left').addEventListener('click', shiftLeft);
document.getElementById('shift-right').addEventListener('click', shiftRight);
document.getElementById('shift-up').addEventListener('click', shiftUp);
document.getElementById('shift-down').addEventListener('click', shiftDown);
const templateSelect = document.getElementById('template-select');
templateSelect.addEventListener('change', loadTemplate);
function populateGridSizeDropdown() {
const gridSizeSelect = document.getElementById('grid-size-select');
gridSizeSelect.innerHTML = '';
for (const gridLabel in config.unicornGridSizes) {
const option = document.createElement('option');
option.value = config.unicornGridSizes[gridLabel];
option.textContent = gridLabel;
if (gridLabel === defaultUnicornGrid) {
option.selected = true;
}
gridSizeSelect.appendChild(option);
}
}
function initializeGrid() {
const gridSizeSelect = document.getElementById('grid-size-select');
// Set the default selected grid size from the config
gridSizeSelect.value = config.defaultUnicornGrid;
gridSizeSelect.addEventListener('change', function () {
const selectedGridSize = gridSizeSelect.value;
changeGridSize(selectedGridSize);
populateTemplateDropdown(); // Populate the template dropdown based on the new grid size
});
// Initialize the grid size based on the default selection
changeGridSize(config.unicornGridSizes[config.defaultUnicornGrid]);
parseGridSize(config.unicornGridSizes[config.defaultUnicornGrid]);
}
// Function to show/hide the "Select All" and "Copy to Clipboard" buttons
function toggleExportButtons(display) {
const selectButton = document.getElementById('select-all-button');
const copyButton = document.getElementById('copy-clipboard-button');
if (display) {
selectButton.style.display = 'inline-block';
copyButton.style.display = 'inline-block';
} else {
selectButton.style.display = 'none';
copyButton.style.display = 'none';
}
}
// Load templates from an external JSON file
function loadTemplatesFromJSON() {
const xmlRequest = new XMLHttpRequest();
xmlRequest.overrideMimeType("application/json");
xmlRequest.open("GET", "images.json", true);
xmlRequest.onreadystatechange = function () {
if (xmlRequest.readyState === 4 && xmlRequest.status === 200) {
const jsonContent = JSON.parse(xmlRequest.responseText);
handleTemplates(jsonContent);
}
};
xmlRequest.send(null);
}
// Handle the loaded templates
function handleTemplates(templates) {
gridTemplates = templates; // Assuming gridTemplates is a global variable used to store template data
populateTemplateDropdown();
loadTemplate(); // Load the default template
}
document.addEventListener("DOMContentLoaded", function () {
loadTemplatesFromJSON(); // Load templates when the DOM is ready
populateGridSizeDropdown();
createPalette();
initializeGrid();
drawGrid();
toggleExportButtons(false);
// Apply the default grid size to the select menu on initial load
const gridSizeSelect = document.getElementById('grid-size-select');
const defaultGridSize = config.defaultUnicornGrid;
if (gridSizeSelect) {
gridSizeSelect.value = config.unicornGridSizes[defaultGridSize];
changeGridSize(config.unicornGridSizes[defaultGridSize]);
populateTemplateDropdown(); // Populate the template dropdown based on the new grid size
}
});