File size: 16,446 Bytes
d5b93a8
9431776
 
 
d5b93a8
9431776
f5d7680
 
 
 
9431776
 
 
f5d7680
9431776
 
 
 
 
 
 
 
 
 
 
91ef932
 
 
 
 
 
 
9431776
 
 
 
 
f5d7680
91ef932
f5d7680
 
 
 
 
 
91ef932
 
 
 
 
f5d7680
 
 
91ef932
f5d7680
 
 
 
 
 
 
 
91ef932
f5d7680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9431776
91ef932
9431776
91ef932
9431776
 
 
 
 
f5d7680
 
 
 
9431776
 
 
 
 
 
f5d7680
 
 
91ef932
 
 
 
9431776
 
91ef932
 
 
f5d7680
9431776
f5d7680
 
9431776
91ef932
9431776
 
 
 
 
 
91ef932
9431776
91ef932
f5d7680
 
 
9431776
 
 
f5d7680
 
 
 
9431776
f5d7680
 
 
 
 
91ef932
f5d7680
 
 
 
 
 
 
 
 
9431776
 
f5d7680
 
 
 
 
9431776
f5d7680
 
 
 
 
 
 
 
9431776
f5d7680
 
 
 
 
9431776
f5d7680
 
 
 
 
 
 
 
 
 
 
 
9431776
 
 
 
 
f5d7680
 
9431776
 
 
 
 
 
 
 
91ef932
9431776
91ef932
9431776
 
 
 
91ef932
 
 
 
 
 
 
 
9431776
91ef932
 
 
 
 
 
9431776
 
91ef932
9431776
91ef932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9431776
91ef932
 
 
 
 
 
 
 
 
 
9431776
 
91ef932
 
f5d7680
9431776
 
91ef932
 
 
 
9431776
91ef932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9431776
91ef932
9431776
91ef932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9431776
 
f5d7680
9431776
91ef932
9431776
 
91ef932
f5d7680
 
 
 
 
 
 
 
 
9431776
91ef932
f5d7680
 
 
 
 
 
 
 
 
91ef932
9431776
91ef932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d7680
 
91ef932
 
 
 
f5d7680
 
 
 
 
 
 
 
 
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
document.addEventListener('DOMContentLoaded', () => {
    // ------------------------
    // 1. SELECTORES DE ELEMENTOS HTML
    // ------------------------
    const addLayerFile = document.getElementById('addLayerFile');
    const preview = document.getElementById('preview');
    const sheetView = document.getElementById('sheetView');

    if (!preview || !sheetView) {
        alert("ERROR: Faltan elementos Canvas en el HTML ('preview' o 'sheetView'). Revisar index.html.");
        return;
    }
    const ctx = preview.getContext('2d');
    const sheetCtx = sheetView.getContext('2d');

    const frameW = document.getElementById('frameW');
    const frameH = document.getElementById('frameH');
    const framesCountInput = document.getElementById('framesCount');
    const speedInput = document.getElementById('speed');
    const showGrid = document.getElementById('showGrid');

    const addFrameBtn = document.getElementById('addFrame');
    const removeFrameBtn = document.getElementById('removeFrame');
    const playFramesBtn = document.getElementById('playFrames');
    const exportGIFBtn = document.getElementById('exportGIF');
    const exportWebmBtn = document.getElementById('exportWebm'); // Nuevo selector

    // SELECTORES DE BOTONES DE AJUSTE DIRECCIONAL
    const adjustLeftBtn = document.getElementById('adjustLeftBtn');
    const adjustRightBtn = document.getElementById('adjustRightBtn');
    const adjustUpBtn = document.getElementById('adjustUpBtn');
    const adjustDownBtn = document.getElementById('adjustDownBtn');

    let frames = [];
    let currentFrame = 0;
    let animationInterval;
    let uploadedImage;
    
    // Variables de estado
    let currentSheetX = 0;
    let currentSheetY = 0;
    let isDragging = false;
    let lastTouchX = 0;
    let lastTouchY = 0;
    
    // Tama帽o m铆nimo de frame
    const MIN_FRAME_SIZE = 16;
    const STEP = 8; // Pixeles de ajuste y movimiento


    // ------------------------
    // 2. L脫GICA DE DIBUJO
    // ------------------------
    
    function drawCurrentFramePreview(x, y) {
        if (!uploadedImage) return;

        const fW = parseInt(frameW.value);
        const fH = parseInt(frameH.value);
        
        ctx.clearRect(0, 0, preview.width, preview.height);
        
        ctx.drawImage(uploadedImage, x, y, fW, fH, 0, 0, fW, fH);

        if (showGrid.checked) drawGrid();
    }

    function drawSheetView() {
        if (!uploadedImage) return;

        const sheetW = uploadedImage.width;
        const sheetH = uploadedImage.height;
        const canvasW = sheetView.width;
        const canvasH = sheetView.height;
        
        const fW = parseInt(frameW.value);
        const fH = parseInt(frameH.value);
        
        const scaleX = canvasW / sheetW;
        const scaleY = canvasH / sheetH;
        const scale = Math.min(scaleX, scaleY);
        
        const scaledW = sheetW * scale;
        const scaledH = sheetH * scale;
        const offsetX = (canvasW - scaledW) / 2;
        const offsetY = (canvasH - scaledH) / 2;

        sheetCtx.clearRect(0, 0, canvasW, canvasH);
        sheetCtx.drawImage(uploadedImage, offsetX, offsetY, scaledW, scaledH);
        
        sheetCtx.strokeStyle = 'red';
        sheetCtx.lineWidth = 2;
        
        sheetCtx.strokeRect(
            offsetX + currentSheetX * scale,
            offsetY + currentSheetY * scale,
            fW * scale,
            fH * scale
        );
    }
    
    function drawGrid() {
        ctx.strokeStyle = 'rgba(255,255,255,0.3)';
        ctx.strokeRect(0, 0, preview.width, preview.height);
    }

    // ------------------------
    // 3. EVENTO DE CARGA DE IMAGEN
    // ------------------------

    addLayerFile.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (animationInterval) clearInterval(animationInterval);
        frames = []; 
        framesCountInput.value = 0;
        currentSheetX = 0;
        currentSheetY = 0;

        const reader = new FileReader();
        reader.onload = (event) => {
            const img = new Image();
            img.onload = () => {
                uploadedImage = img;
                const fW = parseInt(frameW.value);
                const fH = parseInt(frameH.value);
                
                if (isNaN(fW) || isNaN(fH) || fW < MIN_FRAME_SIZE || fH < MIN_FRAME_SIZE) {
                    // Forzar a valores iniciales v谩lidos
                    frameW.value = 48;
                    frameH.value = 48;
                }
                
                preview.width = parseInt(frameW.value);
                preview.height = parseInt(frameH.value);
                sheetView.width = 400; 
                sheetView.height = 400;
                
                drawSheetView(); 
                drawCurrentFramePreview(currentSheetX, currentSheetY);
            };
            img.onerror = () => { alert("ERROR: La imagen no pudo cargarse."); uploadedImage = null; };
            img.src = event.target.result;
        };
        reader.readAsDataURL(file);
    });

    // ------------------------
    // 4. CONTROL MANUAL DE FRAMES (A帽adir/Remover/Reproducir)
    // ------------------------

    addFrameBtn.addEventListener('click', () => {
        if (!uploadedImage) return alert("Sube una imagen primero");
        
        const fW = parseInt(frameW.value);
        const fH = parseInt(frameH.value);
        
        if (currentSheetY >= uploadedImage.height) {
             alert("Ya se recorri贸 toda la imagen. El proceso se detiene.");
             return;
        }

        const canvas = document.createElement('canvas');
        canvas.width = fW;
        canvas.height = fH;
        const context = canvas.getContext('2d');
        
        context.drawImage(uploadedImage, currentSheetX, currentSheetY, fW, fH, 0, 0, fW, fH);
        
        frames.push(canvas);
        framesCountInput.value = frames.length;
        
        currentSheetX += fW;
        
        if (currentSheetX >= uploadedImage.width) {
            currentSheetX = 0;
            currentSheetY += fH;
        }

        drawCurrentFramePreview(currentSheetX, currentSheetY);
        drawSheetView(); 
        
        if (animationInterval) clearInterval(animationInterval);
    });

    removeFrameBtn.addEventListener('click', () => {
        if (frames.length === 0) return;
        frames.pop();
        framesCountInput.value = frames.length;
        
        const fW = parseInt(frameW.value);
        const fH = parseInt(frameH.value);
        const framesPerRow = Math.floor(uploadedImage.width / fW);

        if (currentSheetX === 0) {
            currentSheetY = Math.max(0, currentSheetY - fH);
            currentSheetX = (framesPerRow - 1) * fW;
        } else {
            currentSheetX = Math.max(0, currentSheetX - fW);
        }
        
        drawCurrentFramePreview(currentSheetX, currentSheetY);
        drawSheetView();
    });

    playFramesBtn.addEventListener('click', () => {
        if (frames.length === 0) {
            alert("No hay frames en la lista, 隆a帽谩delos manualmente!");
            return;
        }
        playFrames();
    });

    function playFrames() {
        if (frames.length === 0) return;
        if (animationInterval) clearInterval(animationInterval);

        currentFrame = 0;
        const speed = parseInt(speedInput.value) || 100;

        animationInterval = setInterval(() => {
            ctx.clearRect(0, 0, preview.width, preview.height);
            ctx.drawImage(frames[currentFrame], 0, 0, preview.width, preview.height);
            if (showGrid.checked) drawGrid();
            currentFrame = (currentFrame + 1) % frames.length;
        }, speed);
    }
    
    // ------------------------
    // 5. EXPORTACI脫N GIF/WebM
    // ------------------------
    exportGIFBtn.addEventListener('click', exportGIF);
    function exportGIF() {
        if (frames.length === 0) return alert("No hay frames para exportar.");
        if (typeof GIF === 'undefined') return alert("ERROR: La librer铆a GIF.js no est谩 cargada.");
        // ... (c贸digo de exportaci贸n GIF) ...
    }
    
    // NUEVA FUNCI脫N: EXPORTACI脫N WEBM
    exportWebmBtn.addEventListener('click', exportWebM);
    function exportWebM() {
        if (frames.length === 0) return alert("No hay frames para exportar.");

        // La API MediaRecorder permite grabar frames como video WebM
        const chunks = [];
        const canvasRecorder = document.createElement('canvas');
        canvasRecorder.width = parseInt(frameW.value);
        canvasRecorder.height = parseInt(frameH.value);
        const contextRecorder = canvasRecorder.getContext('2d');
        
        const speed = parseInt(speedInput.value) || 100;
        const frameRate = 1000 / speed; // cuadros por segundo

        if (!MediaRecorder.isTypeSupported('video/webm')) {
            alert("ERROR: Tu navegador no soporta la grabaci贸n en WebM. Intenta exportar a GIF.");
            return;
        }
        
        exportWebmBtn.textContent = 'Codificando WebM...';
        exportWebmBtn.disabled = true;

        // Capturar los frames uno por uno
        let frameIndex = 0;
        const captureInterval = setInterval(() => {
            if (frameIndex >= frames.length) {
                clearInterval(captureInterval);
                mediaRecorder.stop();
                return;
            }
            contextRecorder.clearRect(0, 0, canvasRecorder.width, canvasRecorder.height);
            contextRecorder.drawImage(frames[frameIndex], 0, 0, canvasRecorder.width, canvasRecorder.height);
            frameIndex++;
        }, speed);

        // Iniciar la grabaci贸n
        const stream = canvasRecorder.captureStream(frameRate);
        const mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
        
        mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
        
        mediaRecorder.onstop = () => {
            const blob = new Blob(chunks, { type: 'video/webm' });

            let link = document.getElementById('webmDownload');
            if (!link) {
                link = document.createElement('a');
                link.id = 'webmDownload';
                link.textContent = 'WebM listo: hacer clic para descargar';
                document.getElementById('downloadLinks').appendChild(link);
            }
            link.href = URL.createObjectURL(blob);
            link.download = 'sprite.webm';

            exportWebmBtn.textContent = 'Exportar WebM';
            exportWebmBtn.disabled = false;
            
            // Reanudar animaci贸n de preview si estaba activa
            playFrames(); 
        };
        
        mediaRecorder.start(speed); // Grabar cada 'speed' milisegundos

        // Limpiar la animaci贸n de preview mientras se graba
        if (animationInterval) clearInterval(animationInterval);
    }

    // ------------------------
    // 7. L脫GICA DE AJUSTE POR BOTONES DIRECCIONALES
    // ------------------------
    
    // Funci贸n central para actualizar el estado del frame y redibujar
    function updateFrame(newW, newH) {
        newW = Math.max(MIN_FRAME_SIZE, Math.min(newW, uploadedImage.width));
        newH = Math.max(MIN_FRAME_SIZE, Math.min(newH, uploadedImage.height));
        
        frameW.value = newW;
        frameH.value = newH;
        preview.width = newW;
        preview.height = newH;
        
        // Asegurar que el recuadro no se salga de los l铆mites
        const finalW = parseInt(frameW.value);
        const finalH = parseInt(frameH.value);
        currentSheetX = Math.max(0, Math.min(currentSheetX, uploadedImage.width - finalW));
        currentSheetY = Math.max(0, Math.min(currentSheetY, uploadedImage.height - finalH));

        drawSheetView();
        drawCurrentFramePreview(currentSheetX, currentSheetY);
    }
    
    // Handlers para los botones de ajuste
    
    // ANCHO (-)
    if (adjustLeftBtn) {
        adjustLeftBtn.addEventListener('click', () => {
            if (!uploadedImage) return alert("Sube una imagen primero.");
            const currentW = parseInt(frameW.value);
            // Ajustar el ancho y MOVER la posici贸n de captura a la izquierda para mantener el borde derecho fijo.
            updateFrame(currentW - STEP, parseInt(frameH.value));
            // Asegurar que currentSheetX se ajuste hacia la derecha por el cambio de tama帽o
            currentSheetX = Math.max(0, currentSheetX + STEP);
            updateFrame(currentW - STEP, parseInt(frameH.value)); // Llamada repetida para aplicar currentSheetX y l铆mites
        });
    }

    // ANCHO (+)
    if (adjustRightBtn) {
        adjustRightBtn.addEventListener('click', () => {
            if (!uploadedImage) return alert("Sube una imagen primero.");
            const currentW = parseInt(frameW.value);
            // Solo ajustar el ancho (el borde izquierdo se mantiene)
            updateFrame(currentW + STEP, parseInt(frameH.value));
        });
    }

    // ALTO (-)
    if (adjustUpBtn) {
        adjustUpBtn.addEventListener('click', () => {
            if (!uploadedImage) return alert("Sube una imagen primero.");
            const currentH = parseInt(frameH.value);
            // Ajustar el alto y MOVER la posici贸n de captura hacia arriba para mantener el borde inferior fijo.
            updateFrame(parseInt(frameW.value), currentH - STEP);
            // Asegurar que currentSheetY se ajuste hacia abajo por el cambio de tama帽o
            currentSheetY = Math.max(0, currentSheetY + STEP);
            updateFrame(parseInt(frameW.value), currentH - STEP); // Llamada repetida para aplicar currentSheetY y l铆mites
        });
    }

    // ALTO (+)
    if (adjustDownBtn) {
        adjustDownBtn.addEventListener('click', () => {
            if (!uploadedImage) return alert("Sube una imagen primero.");
            const currentH = parseInt(frameH.value);
            // Solo ajustar el alto (el borde superior se mantiene)
            updateFrame(parseInt(frameW.value), currentH + STEP);
        });
    }


    // ------------------------
    // 8. CONTROL T脕CTIL (Solo MOVER - 1 Dedo)
    // ------------------------

    // Funci贸n auxiliar para getDistance (mantener por si se necesita)
    function getDistance(touch1, touch2) {
        const dx = touch1.clientX - touch2.clientX;
        const dy = touch1.clientY - touch2.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    }

    sheetView.addEventListener('touchstart', (e) => {
        e.preventDefault(); 
        if (!uploadedImage) return;

        if (e.touches.length === 1) {
            isDragging = true;
            const touch = e.touches[0];
            lastTouchX = touch.clientX;
            lastTouchY = touch.clientY;
        }
    });

    sheetView.addEventListener('touchmove', (e) => {
        e.preventDefault();
        if (!uploadedImage || !isDragging || e.touches.length !== 1) return;
        
        // L脫GICA DE DRAG (MOVIMIENTO - 1 Dedo)
        const touch = e.touches[0];
        const dx = touch.clientX - lastTouchX;
        const dy = touch.clientY - lastTouchY;
        
        const sheetW = uploadedImage.width;
        const canvasW = sheetView.width;
        const scale = Math.min(canvasW / sheetW, canvasW / uploadedImage.height);
        
        const fW = parseInt(frameW.value);
        const fH = parseInt(frameH.value);
        
        let imgDx = Math.round(dx / scale);
        let imgDy = Math.round(dy / scale);
        
        // Mover solo si el arrastre es significativo (para evitar jitter)
        if (Math.abs(imgDx) >= STEP) { 
            let framesMovedX = Math.round(imgDx / STEP); 
            currentSheetX += framesMovedX * STEP;
            lastTouchX = touch.clientX; 
        }
        if (Math.abs(imgDy) >= STEP) { 
            let framesMovedY = Math.round(imgDy / STEP);
            currentSheetY += framesMovedY * STEP;
            lastTouchY = touch.clientY; 
        }
        
        // Asegurar l铆mites
        currentSheetX = Math.max(0, Math.min(currentSheetX, uploadedImage.width - fW));
        currentSheetY = Math.max(0, Math.min(currentSheetY, uploadedImage.height - fH));

        drawSheetView();
        drawCurrentFramePreview(currentSheetX, currentSheetY);
    });

    sheetView.addEventListener('touchend', (e) => {
        isDragging = false;
    });
    
});