📜
tilepicker.js
Back
📝 Javascript ⚡ Executable Ctrl+S: Save • Ctrl+R: Run • Ctrl+F: Find
// Debug alert for mobile debugging if (typeof debugAlert === 'function') { debugAlert('tilepicker.js loaded'); } // Global variables for tile picking let groups = [{ id: 0, url: null, tiles: [] }]; let currentGroup = 0; let nextUniqueId = 1; // start at 1 (0 = "no object") /** * Open the tile picker overlay - main entry point called by files.js */ function openTilePickerOverlay() { const overlayContent = document.getElementById('overlayContent'); if (selectedImage && selectedTileSize) { overlayContent.innerHTML = ` <h2>Tile Picker 🧩</h2> <p>Tile size: ${selectedTileSize}px</p> <div id="groupTabs"></div> <div id="pickedImages"></div> <div id="tileViewport"> <div id="tileContainer"> <img id="tileImage" src="${selectedImage}" alt="${selectedImageName}"> </div> </div> `; // Initialize tile picker functionality initializeTilePicker(); } else { overlayContent.innerHTML = ` <h2>Tile Picker 🧩</h2> <p>Select an image and a numeric folder first.</p> `; } } /** * Initialize the tile picker functionality */ function initializeTilePicker() { renderTabs(); renderPicked(); setupTileGrid(); } /** * Setup the tile grid overlay on the image */ function setupTileGrid() { const imgEl = document.getElementById('tileImage'); imgEl.onload = () => { const container = document.getElementById('tileContainer'); const w = imgEl.naturalWidth; const h = imgEl.naturalHeight; // Set container and image dimensions imgEl.style.width = w + "px"; imgEl.style.height = h + "px"; container.style.width = w + "px"; container.style.height = h + "px"; // Remove existing grid cells container.querySelectorAll('.grid-cell').forEach(c => c.remove()); // Calculate grid dimensions const cols = Math.floor(w / selectedTileSize); // Create grid cells for (let y = 0; y < h; y += selectedTileSize) { for (let x = 0; x < w; x += selectedTileSize) { const cell = document.createElement('div'); cell.className = 'grid-cell'; cell.style.cssText = ` position: absolute; left: ${x}px; top: ${y}px; width: ${selectedTileSize}px; height: ${selectedTileSize}px; border: 2px solid rgba(102, 204, 255, 0.7); cursor: pointer; display: flex; align-items: center; justify-content: center; background: rgba(0, 0, 0, 0.3); color: white; font-weight: bold; font-size: 12px; text-shadow: 1px 1px 2px black; `; // Calculate tile index for display const row = Math.floor(y / selectedTileSize); const col = Math.floor(x / selectedTileSize); const tileIndex = row * cols + col + 1; // Add label to cell const label = document.createElement('span'); label.textContent = tileIndex; cell.appendChild(label); // Add hover effects cell.addEventListener('mouseenter', () => { cell.style.background = 'rgba(102, 204, 255, 0.4)'; cell.style.borderColor = '#6cf'; }); cell.addEventListener('mouseleave', () => { cell.style.background = 'rgba(0, 0, 0, 0.3)'; cell.style.borderColor = 'rgba(102, 204, 255, 0.7)'; }); // Add click handler to pick this tile cell.onclick = () => pickTile(imgEl, x, y, selectedTileSize, selectedImage); container.appendChild(cell); } } }; } /** * Render the group tabs */ function renderTabs() { const tabBar = document.getElementById('groupTabs'); if (!tabBar) return; tabBar.innerHTML = ''; tabBar.style.cssText = 'margin-bottom: 10px; display: flex; gap: 5px; align-items: center;'; // Render existing group tabs groups.forEach((g, idx) => { const btn = document.createElement('button'); btn.textContent = `Group ${idx + 1}`; btn.style.cssText = ` background: ${idx === currentGroup ? '#6cf' : '#555'}; color: ${idx === currentGroup ? '#000' : '#fff'}; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; position: relative; `; btn.onclick = () => { currentGroup = idx; renderTabs(); renderPicked(); }; // Add tile count badge if (g.tiles.length > 0) { const badge = document.createElement('span'); badge.textContent = g.tiles.length; badge.style.cssText = ` position: absolute; top: -5px; right: -5px; background: #f44; color: white; border-radius: 50%; width: 16px; height: 16px; font-size: 9px; display: flex; align-items: center; justify-content: center; `; btn.appendChild(badge); } tabBar.appendChild(btn); }); // Add "+" button to create new group const addBtn = document.createElement('button'); addBtn.textContent = "+"; addBtn.style.cssText = ` background: #4a4; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: bold; `; addBtn.onclick = () => { groups.push({ id: groups.length, url: null, tiles: [] }); currentGroup = groups.length - 1; renderTabs(); renderPicked(); }; tabBar.appendChild(addBtn); // Add clear group button if (groups[currentGroup] && groups[currentGroup].tiles.length > 0) { const clearBtn = document.createElement('button'); clearBtn.textContent = "Clear"; clearBtn.style.cssText = ` background: #d44; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; margin-left: 10px; `; clearBtn.onclick = () => { if (confirm('Clear all tiles from this group?')) { clearCurrentGroup(); } }; tabBar.appendChild(clearBtn); } } /** * Render the picked tiles for the current group */ function renderPicked() { const container = document.getElementById('pickedImages'); if (!container) return; container.innerHTML = ''; container.style.cssText = ` margin-bottom: 15px; padding: 10px; background: #2a2a2a; border-radius: 6px; min-height: 80px; max-height: 200px; overflow-y: auto; `; const group = groups[currentGroup]; if (group.tiles.length === 0) { container.innerHTML = '<div style="color: #888; text-align: center; padding: 20px;">No tiles picked yet. Click on the grid below to select tiles.</div>'; return; } // Create tiles container const tilesContainer = document.createElement('div'); tilesContainer.style.cssText = 'display: flex; flex-wrap: wrap; gap: 8px;'; group.tiles.forEach((tile, idx) => { const wrapper = document.createElement('div'); wrapper.className = 'pickedTile'; wrapper.style.cssText = ` position: relative; display: flex; flex-direction: column; align-items: center; padding: 5px; background: #333; border-radius: 4px; border: 2px solid #555; `; // Create canvas to display the tile const canvas = document.createElement('canvas'); canvas.width = Math.min(tile.size, 64); canvas.height = Math.min(tile.size, 64); canvas.style.cssText = 'border: 1px solid #666; background: #000;'; const ctx = canvas.getContext('2d'); // Create temporary canvas for the original tile const tempCanvas = document.createElement('canvas'); tempCanvas.width = tile.size; tempCanvas.height = tile.size; const tempCtx = tempCanvas.getContext('2d'); tempCtx.putImageData(tile.data, 0, 0); // Scale down if needed ctx.drawImage(tempCanvas, 0, 0, tile.size, tile.size, 0, 0, canvas.width, canvas.height); // Create remove button const removeBtn = document.createElement('button'); removeBtn.className = 'removeBtn'; removeBtn.textContent = "×"; removeBtn.style.cssText = ` position: absolute; top: -5px; right: -5px; background: #f44; color: white; border: none; border-radius: 50%; width: 20px; height: 20px; cursor: pointer; font-size: 12px; display: flex; align-items: center; justify-content: center; `; removeBtn.onclick = () => { group.tiles.splice(idx, 1); renderPicked(); }; // Create ID label const idLabel = document.createElement('span'); idLabel.textContent = `ID ${tile.uniqueId}`; idLabel.style.cssText = ` font-size: 10px; color: #ccc; margin-top: 4px; text-align: center; `; wrapper.appendChild(canvas); wrapper.appendChild(removeBtn); wrapper.appendChild(idLabel); tilesContainer.appendChild(wrapper); }); container.appendChild(tilesContainer); } /** * Pick a tile from the image at specified coordinates * @param {HTMLImageElement} imgEl - The source image element * @param {number} x - X coordinate of the tile * @param {number} y - Y coordinate of the tile * @param {number} size - Size of the tile (width and height) * @param {string} url - URL of the source image */ function pickTile(imgEl, x, y, size, url) { const group = groups[currentGroup]; // Check if group already uses a different image if (group.url && group.url !== url) { alert("This group already uses a different image. Create a new group or switch to an existing group that uses this image."); return; } // Check if this exact tile has already been picked const existingTile = group.tiles.find(tile => tile.sourceX === x && tile.sourceY === y && tile.sourceUrl === url ); if (existingTile) { alert(`This tile is already picked (ID ${existingTile.uniqueId})`); return; } // Set the group's image URL group.url = url; // Give the group a name based on the image if it doesn't have one if (!group.name) { const imageName = url.split('/').pop().split('.')[0]; group.name = `${imageName}_${size}px`; } // Extract the tile data using canvas const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); // Draw the tile portion of the image ctx.drawImage(imgEl, x, y, size, size, 0, 0, size, size); // Get the image data const data = ctx.getImageData(0, 0, size, size); // Add tile to current group group.tiles.push({ size, data, uniqueId: nextUniqueId++, sourceX: x, sourceY: y, sourceUrl: url }); // Re-render the picked tiles display and tabs renderPicked(); renderTabs(); // Visual feedback const cell = document.querySelector(`[style*="left: ${x}px"][style*="top: ${y}px"]`); if (cell) { cell.style.background = 'rgba(68, 255, 68, 0.6)'; setTimeout(() => { cell.style.background = 'rgba(0, 0, 0, 0.3)'; }, 500); } } /** * Get the current group data * @returns {Object} Current group object */ function getCurrentGroup() { return groups[currentGroup]; } /** * Get all groups data * @returns {Array} Array of all group objects */ function getAllGroups() { return groups; } /** * Set the current group * @param {number} groupIndex - Index of the group to set as current */ function setCurrentGroup(groupIndex) { if (groupIndex >= 0 && groupIndex < groups.length) { currentGroup = groupIndex; renderTabs(); renderPicked(); } } /** * Clear all tiles from the current group */ function clearCurrentGroup() { const group = groups[currentGroup]; group.tiles = []; group.url = null; group.name = null; renderTabs(); renderPicked(); } /** * Remove a group by index * @param {number} groupIndex - Index of the group to remove */ function removeGroup(groupIndex) { if (groups.length > 1 && groupIndex >= 0 && groupIndex < groups.length) { groups.splice(groupIndex, 1); // Adjust current group if necessary if (currentGroup >= groups.length) { currentGroup = groups.length - 1; } renderTabs(); renderPicked(); } } // Debug alert for mobile debugging - success if (typeof debugAlert === 'function') { debugAlert('tilepicker.js loaded successfully'); }