diff options
Diffstat (limited to 'js/pixel-art/pixel/app.js')
-rw-r--r-- | js/pixel-art/pixel/app.js | 386 |
1 files changed, 311 insertions, 75 deletions
diff --git a/js/pixel-art/pixel/app.js b/js/pixel-art/pixel/app.js index 3e37db8..2d83997 100644 --- a/js/pixel-art/pixel/app.js +++ b/js/pixel-art/pixel/app.js @@ -5,7 +5,16 @@ const defaultGridHeight = 16; let gridWidth = defaultGridWidth; let gridHeight = defaultGridHeight; let cellSize = 16; -let colorHistory = []; +let colorHistory = [ + '#000000', + '#ae8ce2', + '#2d5d9e', + '#43bef2', + '#99b213', + '#e5b42e', + '#c00f68', + '#ffffff' +]; let currentColor = '#000000'; let grid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)); let offsetX = 0; @@ -19,8 +28,11 @@ let lastY = null; let lastCell = null; const MIN_CELL_SIZE = 4; const MAX_CELL_SIZE = 64; +let canvases = []; +let currentCanvasIndex = 0; +let globalOffsetX = 0; +let globalOffsetY = 0; -// Event Listeners canvas.addEventListener('mousedown', handleInputStart); canvas.addEventListener('mousemove', handleInputMove); canvas.addEventListener('mouseup', handleInputEnd); @@ -34,19 +46,40 @@ document.getElementById('resetBtn').addEventListener('click', handleReset); document.getElementById('exportBtn').addEventListener('click', exportToPNG); window.addEventListener('keydown', handlePan); paletteToggle.addEventListener('click', togglePalette); -document.getElementById('zoomInBtn').addEventListener('click', () => handleZoom(1.5)); -document.getElementById('zoomOutBtn').addEventListener('click', () => handleZoom(0.666)); +document.getElementById('zoomInBtn').addEventListener('click', () => handleZoom(1.25)); +document.getElementById('zoomOutBtn').addEventListener('click', () => handleZoom(0.75)); document.getElementById('panUpBtn').addEventListener('click', () => handlePanButton('up')); document.getElementById('panDownBtn').addEventListener('click', () => handlePanButton('down')); document.getElementById('panLeftBtn').addEventListener('click', () => handlePanButton('left')); document.getElementById('panRightBtn').addEventListener('click', () => handlePanButton('right')); document.getElementById('centerViewBtn').addEventListener('click', resetView); +document.getElementById('newCanvasBtn').addEventListener('click', addNewCanvas); +document.getElementById('saveProjectBtn').addEventListener('click', saveProject); +document.getElementById('loadProjectBtn').addEventListener('click', loadProject); + resizeCanvas(); loadFromLocalStorage(); +renderColorHistory(); + + +function addNewCanvas() { + canvases.push({ + grid: Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)), + offsetX: 0, + offsetY: 0, + hasPixels: false + }); + currentCanvasIndex = canvases.length - 1; + centerGrid(); + drawGrid(); + saveToLocalStorage(); +} function initializeGrid() { - grid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)); + if (canvases.length > 0) { + canvases[currentCanvasIndex].grid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)); + } } function resizeCanvas() { @@ -57,22 +90,52 @@ function resizeCanvas() { } function centerGrid() { - offsetX = Math.max((canvas.width - (gridWidth * cellSize)) / 2, 0); - offsetY = Math.max((canvas.height - (gridHeight * cellSize)) / 2, 0); + if (canvases.length === 0) return; + + canvases.forEach((canvasData, index) => { + canvasData.offsetY = Math.max((canvas.height - (gridHeight * cellSize)) / 2, 0); + if (index === 0) { + canvasData.offsetX = Math.max((canvas.width - (gridWidth * cellSize * canvases.length) - (cellSize * (canvases.length - 1))) / 2, 0); + } else { + // Position each canvas one cell width apart + const previousCanvas = canvases[index - 1]; + canvasData.offsetX = previousCanvas.offsetX + (gridWidth * cellSize) + cellSize; + } + }); } function drawGrid() { ctx.fillStyle = 'teal'; ctx.fillRect(0, 0, canvas.width, canvas.height); - ctx.strokeStyle = '#888888'; - for (let x = 0; x < gridWidth; x++) { - for (let y = 0; y < gridHeight; y++) { - ctx.fillStyle = grid[x][y] || '#f7f7f7'; - ctx.fillRect(x * cellSize + offsetX, y * cellSize + offsetY, cellSize, cellSize); - ctx.strokeRect(x * cellSize + offsetX, y * cellSize + offsetY, cellSize, cellSize); + canvases.forEach((canvasData, index) => { + const xOffset = canvasData.offsetX + globalOffsetX; + + for (let x = 0; x < gridWidth; x++) { + for (let y = 0; y < gridHeight; y++) { + const cellX = x * cellSize + xOffset; + const cellY = y * cellSize + canvasData.offsetY + globalOffsetY; + + // Fill cell background + ctx.fillStyle = canvasData.grid[x][y] || '#f7f7f7'; + ctx.fillRect(cellX, cellY, cellSize, cellSize); + + // Draw cell border + ctx.strokeStyle = '#888888'; + ctx.strokeRect(cellX, cellY, cellSize, cellSize); + + // Draw diagonal line for empty cells + if (!canvasData.grid[x][y]) { + ctx.beginPath(); + ctx.strokeStyle = '#bfbfbf'; + ctx.moveTo(cellX, cellY); + ctx.lineTo(cellX + cellSize, cellY + cellSize); + ctx.stroke(); + ctx.strokeStyle = '#888888'; + } + } } - } + }); } function addToColorHistory(color) { @@ -108,31 +171,64 @@ function handleReset() { if (confirmReset) { gridWidth = defaultGridWidth; gridHeight = defaultGridHeight; - initializeGrid(); - centerGrid(); - drawGrid(); - localStorage.removeItem('pixelArtConfig'); + cellSize = 16; + globalOffsetX = 0; + globalOffsetY = 0; colorHistory = []; renderColorHistory(); + + canvases = []; + addNewCanvas(); + + document.getElementById('gridWidth').disabled = false; + document.getElementById('gridHeight').disabled = false; document.getElementById('gridWidth').value = gridWidth; document.getElementById('gridHeight').value = gridHeight; - alert("Grid reset, color history cleared, and local storage cleared."); + + localStorage.removeItem('pixelArtConfig'); + + alert("Reset complete. You can now adjust the grid size until you place your first pixel."); } } function handlePan(e) { const step = cellSize; - if (e.key === 'ArrowUp') offsetY += step; - if (e.key === 'ArrowDown') offsetY -= step; - if (e.key === 'ArrowLeft') offsetX += step; - if (e.key === 'ArrowRight') offsetX -= step; + if (canvases.length === 0) return; + + if (e.key === 'ArrowUp') globalOffsetY += step; + if (e.key === 'ArrowDown') globalOffsetY -= step; + if (e.key === 'ArrowLeft') globalOffsetX += step; + if (e.key === 'ArrowRight') globalOffsetX -= step; drawGrid(); } function updateGridSize() { - gridWidth = parseInt(document.getElementById('gridWidth').value); - gridHeight = parseInt(document.getElementById('gridHeight').value); - initializeGrid(); + const newWidth = parseInt(document.getElementById('gridWidth').value); + const newHeight = parseInt(document.getElementById('gridHeight').value); + + // Validate input + if (newWidth <= 0 || newHeight <= 0 || newWidth > 100 || newHeight > 100) return; + + gridWidth = newWidth; + gridHeight = newHeight; + + // Update all existing canvases with new dimensions + canvases.forEach(canvasData => { + const newGrid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)); + + // Preserve existing pixel data where possible + const minWidth = Math.min(canvasData.grid.length, gridWidth); + const minHeight = Math.min(canvasData.grid[0].length, gridHeight); + + for (let x = 0; x < minWidth; x++) { + for (let y = 0; y < minHeight; y++) { + newGrid[x][y] = canvasData.grid[x][y]; + } + } + + canvasData.grid = newGrid; + }); + centerGrid(); drawGrid(); saveToLocalStorage(); @@ -140,13 +236,15 @@ function updateGridSize() { function saveToLocalStorage() { const gridData = { - gridWidth: gridWidth, - gridHeight: gridHeight, - cellSize: cellSize, - colorHistory: colorHistory, - currentColor: currentColor, - grid: grid, - isPaletteVisible: isPaletteVisible + gridWidth, + gridHeight, + cellSize, + colorHistory, + currentColor, + canvases, + isPaletteVisible, + globalOffsetX, + globalOffsetY }; localStorage.setItem('pixelArtConfig', JSON.stringify(gridData)); } @@ -155,17 +253,24 @@ function loadFromLocalStorage() { const savedData = localStorage.getItem('pixelArtConfig'); if (savedData) { const gridData = JSON.parse(savedData); - gridWidth = gridData.gridWidth || 10; - gridHeight = gridData.gridHeight || 10; + gridWidth = gridData.gridWidth || defaultGridWidth; + gridHeight = gridData.gridHeight || defaultGridHeight; cellSize = gridData.cellSize || 16; colorHistory = gridData.colorHistory || []; currentColor = gridData.currentColor || '#000000'; - grid = gridData.grid || Array(gridWidth).fill().map(() => Array(gridHeight).fill(null)); + canvases = gridData.canvases || []; + globalOffsetX = gridData.globalOffsetX || 0; + globalOffsetY = gridData.globalOffsetY || 0; + + // Set input values document.getElementById('gridWidth').value = gridWidth; document.getElementById('gridHeight').value = gridHeight; document.getElementById('colorPicker').value = currentColor; - centerGrid(); - drawGrid(); + + // Disable grid size inputs if there's saved data + document.getElementById('gridWidth').disabled = true; + document.getElementById('gridHeight').disabled = true; + isPaletteVisible = gridData.isPaletteVisible ?? true; if (!isPaletteVisible) { palette.classList.add('hidden'); @@ -173,30 +278,66 @@ function loadFromLocalStorage() { paletteToggle.innerHTML = '🎨'; } } else { - initializeGrid(); - centerGrid(); - drawGrid(); + // No saved data, create default canvas + gridWidth = defaultGridWidth; + gridHeight = defaultGridHeight; + addNewCanvas(); } + + // Ensure there's at least one canvas + if (canvases.length === 0) { + addNewCanvas(); + } + + centerGrid(); + drawGrid(); + renderColorHistory(); } function exportToPNG() { - const tempCanvas = document.createElement('canvas'); - const tempCtx = tempCanvas.getContext('2d'); - tempCanvas.width = gridWidth * cellSize; - tempCanvas.height = gridHeight * cellSize; - - for (let x = 0; x < gridWidth; x++) { - for (let y = 0; y < gridHeight; y++) { - tempCtx.fillStyle = grid[x][y] || 'transparent'; - tempCtx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize); - } - } + // Prompt for filename + const filename = prompt("Enter a name for your file(s)", "pixel-art"); + if (!filename) return; // Cancelled + + // An array of promises for each canvas + const exportPromises = canvases.map((canvasData, index) => { + return new Promise(resolve => { + const tempCanvas = document.createElement('canvas'); + const tempCtx = tempCanvas.getContext('2d'); + tempCanvas.width = gridWidth * cellSize; + tempCanvas.height = gridHeight * cellSize; + + // Draw the canvas content + for (let x = 0; x < gridWidth; x++) { + for (let y = 0; y < gridHeight; y++) { + tempCtx.fillStyle = canvasData.grid[x][y] || 'transparent'; + tempCtx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize); + } + } + + // Convert to data URL (trying to work around a webkit bug where blobs don't work so well) + const dataURL = tempCanvas.toDataURL('image/png'); + const paddedNumber = String(index + 1).padStart(2, '0'); + const finalFilename = canvases.length > 1 + ? `${filename}-${paddedNumber}.png` + : `${filename}.png`; + + resolve({ dataURL, filename: finalFilename }); + }); + }); - tempCanvas.toBlob(blob => { - const link = document.createElement('a'); - link.href = URL.createObjectURL(blob); - link.download = 'pixel-art.png'; - link.click(); + // Process exports sequentially with delay + Promise.all(exportPromises).then(exports => { + exports.forEach((exportData, index) => { + setTimeout(() => { + const link = document.createElement('a'); + link.href = exportData.dataURL; + link.download = exportData.filename; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }, index * 1000); // 1 second delay between each download + }); }); } @@ -208,11 +349,18 @@ function handleInputStart(e) { if (cell) { lastCell = cell; - // If cell already has a color, remove it. Otherwise, add color - if (grid[cell.x][cell.y]) { - grid[cell.x][cell.y] = null; + currentCanvasIndex = cell.canvasIndex; + + // Lock grid size on first pixel placement + if (!document.getElementById('gridWidth').disabled) { + document.getElementById('gridWidth').disabled = true; + document.getElementById('gridHeight').disabled = true; + } + + if (canvases[currentCanvasIndex].grid[cell.x][cell.y]) { + canvases[currentCanvasIndex].grid[cell.x][cell.y] = null; } else { - grid[cell.x][cell.y] = currentColor; + canvases[currentCanvasIndex].grid[cell.x][cell.y] = currentColor; } drawGrid(); saveToLocalStorage(); @@ -229,7 +377,7 @@ function handleInputMove(e) { if (cell && (!lastCell || cell.x !== lastCell.x || cell.y !== lastCell.y)) { lastCell = cell; // When dragging, always draw (don't erase) - grid[cell.x][cell.y] = currentColor; + canvases[currentCanvasIndex].grid[cell.x][cell.y] = currentColor; drawGrid(); saveToLocalStorage(); } @@ -259,11 +407,21 @@ function getInputCoordinates(e) { } function getCellFromCoords(coords) { - const x = Math.floor((coords.x - offsetX) / cellSize); - const y = Math.floor((coords.y - offsetY) / cellSize); + if (canvases.length === 0) return null; - if (x >= 0 && x < gridWidth && y >= 0 && y < gridHeight) { - return { x, y }; + for (let i = 0; i < canvases.length; i++) { + const canvasData = canvases[i]; + const canvasLeft = canvasData.offsetX + globalOffsetX; + const canvasRight = canvasLeft + (gridWidth * cellSize); + + if (coords.x >= canvasLeft && coords.x < canvasRight) { + const x = Math.floor((coords.x - canvasLeft) / cellSize); + const y = Math.floor((coords.y - (canvasData.offsetY + globalOffsetY)) / cellSize); + + if (x >= 0 && x < gridWidth && y >= 0 && y < gridHeight) { + return { x, y, canvasIndex: i }; + } + } } return null; } @@ -287,9 +445,6 @@ function handleZoom(factor) { if (newCellSize === cellSize) return; - // const centerX = (canvas.width / 2 - offsetX) / cellSize; - // const centerY = (canvas.height / 2 - offsetY) / cellSize; - cellSize = newCellSize; centerGrid(); @@ -299,19 +454,21 @@ function handleZoom(factor) { } function handlePanButton(direction) { + if (canvases.length === 0) return; + const step = cellSize; switch(direction) { case 'up': - offsetY += step; + globalOffsetY += step; break; case 'down': - offsetY -= step; + globalOffsetY -= step; break; case 'left': - offsetX += step; + globalOffsetX += step; break; case 'right': - offsetX -= step; + globalOffsetX -= step; break; } drawGrid(); @@ -319,7 +476,86 @@ function handlePanButton(direction) { function resetView() { cellSize = 16; // Reset to default zoom - centerGrid(); - drawGrid(); + globalOffsetX = 0; + globalOffsetY = 0; + if (canvases.length > 0) { + centerGrid(); + drawGrid(); + saveToLocalStorage(); + } +} + +function saveProject() { + const now = new Date(); + const formattedDate = now.toISOString().slice(0, 16).replace('T', '-').replace(':', '-'); + + const projectName = prompt("Enter a name for your project", formattedDate); + if (!projectName) return; // User cancelled + + // First save to localStorage to ensure all current state is saved saveToLocalStorage(); + + // Get the data from localStorage and add our special header + const projectData = JSON.parse(localStorage.getItem('pixelArtConfig')); + const exportData = { + __projectHeader: "pppppp_v1", // Add special header + timestamp: new Date().toISOString(), + data: projectData + }; + + // Create and trigger download + const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }); + const link = document.createElement('a'); + link.href = URL.createObjectURL(blob); + link.download = `${projectName}.json`; + link.click(); + URL.revokeObjectURL(link.href); +} + +function loadProject() { + // AAAAH! Data loss! + const confirmLoad = confirm("Loading a project will replace your current work. Are you sure you want to proceed?"); + if (!confirmLoad) return; + + // Create file input + const fileInput = document.createElement('input'); + fileInput.type = 'file'; + fileInput.accept = '.json'; + + fileInput.addEventListener('change', function(e) { + const file = e.target.files[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = function(e) { + try { + const importedData = JSON.parse(e.target.result); + + // Check for our super special header + if (!importedData.__projectHeader || + importedData.__projectHeader !== "pppppp_v1") { + throw new Error('This file is not a valid Pixel Art Project file'); + } + + const projectData = importedData.data; + + // Validate the data has expected properties + if (!projectData.gridWidth || !projectData.gridHeight || !projectData.canvases) { + throw new Error('Invalid project file format'); + } + + // Save to localStorage + localStorage.setItem('pixelArtConfig', JSON.stringify(projectData)); + + // Reload the page to apply changes + window.location.reload(); + + } catch (error) { + alert('Error loading project file: ' + error.message); + } + }; + reader.readAsText(file); + }); + + fileInput.click(); } \ No newline at end of file |