about summary refs log tree commit diff stats
path: root/js/pixel-art/pixel/app.js
blob: e99b54258a245820564e291f3f545c5298bfb6be (plain) (blame)
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
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const defaultGridWidth = 16;
const defaultGridHeight = 16;
let gridWidth = defaultGridWidth;
let gridHeight = defaultGridHeight;
let cellSize = 16;
let colorHistory = [];
let currentColor = '#000000';
let grid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null));
let offsetX = 0;
let offsetY = 0;
const paletteToggle = document.getElementById('palette-toggle');
const palette = document.getElementById('palette');
let isPaletteVisible = true;
let isDrawing = false;
let lastX = null;
let lastY = null;
let lastCell = null;
const MIN_CELL_SIZE = 4;
const MAX_CELL_SIZE = 64;

// Event Listeners
canvas.addEventListener('mousedown', handleInputStart);
canvas.addEventListener('mousemove', handleInputMove);
canvas.addEventListener('mouseup', handleInputEnd);
canvas.addEventListener('touchstart', handleInputStart);
canvas.addEventListener('touchmove', handleInputMove);
canvas.addEventListener('touchend', handleInputEnd);
document.getElementById('colorPicker').addEventListener('input', handleColorChange);
document.getElementById('gridWidth').addEventListener('change', updateGridSize);
document.getElementById('gridHeight').addEventListener('change', updateGridSize);
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('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);

// Initialization
resizeCanvas();
loadFromLocalStorage();

// Functions
function initializeGrid() {
    grid = Array(gridWidth).fill().map(() => Array(gridHeight).fill(null));
}

function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    centerGrid();
    drawGrid();
}

function centerGrid() {
    offsetX = Math.max((canvas.width - (gridWidth * cellSize)) / 2, 0);
    offsetY = Math.max((canvas.height - (gridHeight * cellSize)) / 2, 0);
}

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);
        }
    }
}

function addToColorHistory(color) {
    if (colorHistory.includes(color)) return;
    if (colorHistory.length >= 10) colorHistory.shift();
    colorHistory.push(color);
    renderColorHistory();
}

function renderColorHistory() {
    const historyDiv = document.getElementById('colorHistory');
    historyDiv.innerHTML = '';
    colorHistory.forEach(color => {
        const colorDiv = document.createElement('div');
        colorDiv.style.backgroundColor = color;
        colorDiv.addEventListener('click', () => {
            currentColor = color;
            document.getElementById('colorPicker').value = color;
        });
        historyDiv.appendChild(colorDiv);
    });
}

function handleColorChange() {
    currentColor = document.getElementById('colorPicker').value;
    addToColorHistory(currentColor);
    saveToLocalStorage();
}

function handleReset() {
    const confirmReset = confirm("Are you sure you want to reset? This will clear your drawing and settings.");
    
    if (confirmReset) {
        gridWidth = defaultGridWidth;
        gridHeight = defaultGridHeight;
        initializeGrid();
        centerGrid();
        drawGrid();
        localStorage.removeItem('pixelArtConfig');
        colorHistory = [];
        renderColorHistory();
        document.getElementById('gridWidth').value = gridWidth;
        document.getElementById('gridHeight').value = gridHeight;
        alert("Grid reset, color history cleared, and local storage cleared.");
    }
}

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;
    drawGrid();
}

function updateGridSize() {
    gridWidth = parseInt(document.getElementById('gridWidth').value);
    gridHeight = parseInt(document.getElementById('gridHeight').value);
    initializeGrid();
    centerGrid();
    drawGrid();
    saveToLocalStorage();
}

function saveToLocalStorage() {
    const gridData = {
        gridWidth: gridWidth,
        gridHeight: gridHeight,
        cellSize: cellSize,
        colorHistory: colorHistory,
        currentColor: currentColor,
        grid: grid,
        isPaletteVisible: isPaletteVisible
    };
    localStorage.setItem('pixelArtConfig', JSON.stringify(gridData));
}

function loadFromLocalStorage() {
    const savedData = localStorage.getItem('pixelArtConfig');
    if (savedData) {
        const gridData = JSON.parse(savedData);
        gridWidth = gridData.gridWidth || 10;
        gridHeight = gridData.gridHeight || 10;
        cellSize = gridData.cellSize || 16;
        colorHistory = gridData.colorHistory || [];
        currentColor = gridData.currentColor || '#000000';
        grid = gridData.grid || Array(gridWidth).fill().map(() => Array(gridHeight).fill(null));
        document.getElementById('gridWidth').value = gridWidth;
        document.getElementById('gridHeight').value = gridHeight;
        document.getElementById('colorPicker').value = currentColor;
        centerGrid();
        drawGrid();
        isPaletteVisible = gridData.isPaletteVisible ?? true;
        if (!isPaletteVisible) {
            palette.classList.add('hidden');
            paletteToggle.classList.add('hidden');
            paletteToggle.innerHTML = '🎨';
        }
    } else {
        initializeGrid();
        centerGrid();
        drawGrid();
    }
}

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);
        }
    }

    tempCanvas.toBlob(blob => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'pixel-art.png';
        link.click();
    });
}

function handleInputStart(e) {
    e.preventDefault();
    isDrawing = true;
    const coords = getInputCoordinates(e);
    const cell = getCellFromCoords(coords);
    
    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;
        } else {
            grid[cell.x][cell.y] = currentColor;
        }
        drawGrid();
        saveToLocalStorage();
    }
}

function handleInputMove(e) {
    e.preventDefault();
    if (!isDrawing) return;
    
    const coords = getInputCoordinates(e);
    const cell = getCellFromCoords(coords);
    
    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;
        drawGrid();
        saveToLocalStorage();
    }
}

function handleInputEnd(e) {
    e.preventDefault();
    isDrawing = false;
    lastCell = null;
}

function getInputCoordinates(e) {
    const rect = canvas.getBoundingClientRect();
    if (e.touches) {
        // Touch event
        return {
            x: e.touches[0].clientX - rect.left,
            y: e.touches[0].clientY - rect.top
        };
    } else {
        // Mouse event
        return {
            x: e.clientX - rect.left,
            y: e.clientY - rect.top
        };
    }
}

function getCellFromCoords(coords) {
    const x = Math.floor((coords.x - offsetX) / cellSize);
    const y = Math.floor((coords.y - offsetY) / cellSize);
    
    if (x >= 0 && x < gridWidth && y >= 0 && y < gridHeight) {
        return { x, y };
    }
    return null;
}

function togglePalette() {
    isPaletteVisible = !isPaletteVisible;
    
    if (isPaletteVisible) {
        palette.classList.remove('hidden');
        paletteToggle.classList.remove('hidden');
        paletteToggle.innerHTML = '☰';
    } else {
        palette.classList.add('hidden');
        paletteToggle.classList.add('hidden');
        paletteToggle.innerHTML = '🎨';
    }
}

function handleZoom(factor) {
    const newCellSize = Math.max(MIN_CELL_SIZE, Math.min(MAX_CELL_SIZE, cellSize * factor));
    
    if (newCellSize === cellSize) return;
    
    const centerX = (canvas.width / 2 - offsetX) / cellSize;
    const centerY = (canvas.height / 2 - offsetY) / cellSize;
    
    cellSize = newCellSize;
    
    centerGrid();
    
    drawGrid();
    saveToLocalStorage();
}

function handlePanButton(direction) {
    const step = cellSize;
    switch(direction) {
        case 'up':
            offsetY += step;
            break;
        case 'down':
            offsetY -= step;
            break;
        case 'left':
            offsetX += step;
            break;
        case 'right':
            offsetX -= step;
            break;
    }
    drawGrid();
}

function resetView() {
    cellSize = 16; // Reset to default zoom
    centerGrid();
    drawGrid();
    saveToLocalStorage();
}