import React, { useState, useRef, useEffect } from 'react'; import { Download, Eraser, Trash2, PenTool, Grid3X3, Settings2, Undo, Check } from 'lucide-react'; export default function App() { // Configuration const [size, setSize] = useState(16); const [pixelSize, setPixelSize] = useState(20); // Visual size of pixels in editor const [selectedColor, setSelectedColor] = useState('#3B82F6'); const [isEraser, setIsEraser] = useState(false); const [showGridLines, setShowGridLines] = useState(true); // Grid State const [grid, setGrid] = useState([]); const [history, setHistory] = useState([]); // Interaction State const [isDrawing, setIsDrawing] = useState(false); // Palette Presets const colors = [ '#000000', '#FFFFFF', '#9CA3AF', '#EF4444', '#F97316', '#F59E0B', '#84CC16', '#10B981', '#06B6D4', '#3B82F6', '#6366F1', '#8B5CF6', '#EC4899', '#F43F5E', '#78350F', '#FEF3C7' ]; // Initialize Grid useEffect(() => { resetGrid(size); }, []); const resetGrid = (newSize) => { const newGrid = Array(newSize * newSize).fill(null); setGrid(newGrid); setHistory([]); // Don't reset color, keep user preference }; const handleSizeChange = (e) => { const newSize = parseInt(e.target.value); if (newSize >= 4 && newSize <= 64) { setSize(newSize); resetGrid(newSize); } }; // Painting Logic const paint = (index) => { const newGrid = [...grid]; const newColor = isEraser ? null : selectedColor; // Only update if different if (newGrid[index] !== newColor) { newGrid[index] = newColor; setGrid(newGrid); } }; const handleMouseDown = (index) => { setIsDrawing(true); // Save current state to history before starting a stroke // limiting history to last 20 steps setHistory(prev => [...prev.slice(-19), [...grid]]); paint(index); }; const handleMouseEnter = (index) => { if (isDrawing) { paint(index); } }; const handleMouseUp = () => { setIsDrawing(false); }; const handleUndo = () => { if (history.length === 0) return; const previousGrid = history[history.length - 1]; setGrid(previousGrid); setHistory(prev => prev.slice(0, -1)); }; // Export Logic const exportImage = () => { const canvas = document.createElement('canvas'); const scale = 20; // Scale up the image so 1px = 20px canvas.width = size * scale; canvas.height = size * scale; const ctx = canvas.getContext('2d'); // Iterate through grid grid.forEach((color, i) => { if (color) { const x = (i % size) * scale; const y = Math.floor(i / size) * scale; ctx.fillStyle = color; ctx.fillRect(x, y, scale, scale); } }); const link = document.createElement('a'); link.download = `pixel-art-${Date.now()}.png`; link.href = canvas.toDataURL('image/png'); link.click(); }; return (
Draw, Create, Export