-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
467 lines (409 loc) · 19.1 KB
/
Copy pathapp.js
File metadata and controls
467 lines (409 loc) · 19.1 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
const { createApp } = Vue;
// =========================================================================
// MÓDULO DE UTILIDADES DE IMAGEN
// =========================================================================
const ImageUtils = {
/**
* Convierte un color hexadecimal
* @param {string} hex - Color en formato hexadecimal.
* @returns {number[]} Array con los valores [R, G, B].
*/
hexToRgb(hex) {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
parseInt(result[1], 16), // R
parseInt(result[2], 16), // G
parseInt(result[3], 16) // B
] : [0, 0, 0];
},
/**
* Calcula la luminancia (brillo) de un píxel RGB usando el estándar ITU-R BT.709.
* @param {number} r - Valor de Rojo (0-255).
* @param {number} g - Valor de Verde (0-255).
* @param {number} b - Valor de Azul (0-255).
* @returns {number} Valor de luminancia (0-255).
*/
calculateLuminance(r, g, b) {
const R_LUMINANCE = 0.2126;
const G_LUMINANCE = 0.7152;
const B_LUMINANCE = 0.0722;
return (R_LUMINANCE * r) + (G_LUMINANCE * g) + (B_LUMINANCE * b);
},
/**
* Aplica un filtro de mediana (kernel 3x3) para reducir el ruido y suavizar bordes.
* Se usa como pre-proceso para simular el ruido/difusión de tinta de una fotocopiadora.
* @param {ImageData} imageData - Datos originales de píxeles.
* @returns {ImageData} Los nuevos datos de píxeles con el filtro de mediana aplicado.
*/
applyMedianFilter(imageData) {
const { width, height, data } = imageData;
const tempImageData = new ImageData(width, height);
const tempData = tempImageData.data;
const kernelSize = 3; // Kernel 3x3
const radius = Math.floor(kernelSize / 2); // Radio = 1
// Función auxiliar para obtener el valor mediano de un array
const getMedian = (arr) => {
arr.sort((a, b) => a - b);
return arr[Math.floor(arr.length / 2)];
};
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const rValues = [];
const gValues = [];
const bValues = [];
// Recorrer el kernel 3x3 alrededor del píxel (x, y)
for (let ky = -radius; ky <= radius; ky++) {
for (let kx = -radius; kx <= radius; kx++) {
const nx = x + kx;
const ny = y + ky;
// Verificar límites de la imagen
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
const index = (ny * width + nx) * 4;
rValues.push(data[index]);
gValues.push(data[index + 1]);
bValues.push(data[index + 2]);
}
}
}
// Calcular la mediana para cada componente de color
const medianR = getMedian(rValues);
const medianG = getMedian(gValues);
const medianB = getMedian(bValues);
// Reemplazar el píxel central con los valores medianos
const outputIndex = (y * width + x) * 4;
tempData[outputIndex] = medianR;
tempData[outputIndex + 1] = medianG;
tempData[outputIndex + 2] = medianB;
tempData[outputIndex + 3] = data[outputIndex + 3]; // Mantener el Alpha (opacidad)
}
}
return tempImageData;
},
/**
* Realiza una interpolación lineal entre dos valores.
*/
lerp(a, b, t) {
return a + (b - a) * t;
}
};
// =========================================================================
// MÓDULOS DE FILTRO
// =========================================================================
const Filters = {
/**
* Aplica el filtro Xerox Bi-Color (Binarización).
* @param {ImageData} imageData - Datos de píxeles de la imagen.
* @param {Object} params - Parámetros del filtro (color1, color2, threshold, useMedian).
* @returns {ImageData} Los datos de píxeles modificados.
*/
xerox(imageData, params) {
let currentImageData = imageData;
// Opcionalmente aplicar el filtro de mediana como pre-proceso
if (params.useMedian) {
currentImageData = ImageUtils.applyMedianFilter(currentImageData);
}
const data = currentImageData.data;
const len = data.length;
// Parámetros de entrada ya convertidos a RGB
const rgb1 = ImageUtils.hexToRgb(params.color1); // Color Claro
const rgb2 = ImageUtils.hexToRgb(params.color2); // Color Oscuro
const threshold = params.threshold;
for (let i = 0; i < len; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
//Calcular Brillo (Luminancia)
const luminance = ImageUtils.calculateLuminance(r, g, b);
//Aplicar Binarización (Paletización Bi-Color)
if (luminance > threshold) {
// CLARO
data[i] = rgb1[0];
data[i + 1] = rgb1[1];
data[i + 2] = rgb1[2];
} else {
// OSCURO
data[i] = rgb2[0];
data[i + 1] = rgb2[1];
data[i + 2] = rgb2[2];
}
}
return currentImageData;
},
/**
* Aplica el filtro Duotone (Doble Luz).
* @param {ImageData} imageData
* @param {Object} params
*/
duotone(imageData, params) {
const { width, height, data } = imageData;
const rgb1 = ImageUtils.hexToRgb(params.color1);
const rgb2 = ImageUtils.hexToRgb(params.color2);
const angleRad = (params.angle * Math.PI) / 180;
const dirX = Math.cos(angleRad);
const dirY = Math.sin(angleRad);
const exposure = params.exposure || 1.0;
const intensity = params.neonIntensity || 1.0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
// 1. Obtener Luminancia base
const gray = ImageUtils.calculateLuminance(data[i], data[i+1], data[i+2]);
// 2. APLICAR EXPOSICIÓN Y CONTRASTE
// Multiplicamos por la exposición para rescatar luces o sombras
let normGray = (gray / 255) * exposure;
// Aplicamos un ligero contraste (curva S simplificada) para que no sea plano
normGray = Math.pow(normGray, 1.2);
// Limitar a 1.0 máximo
if (normGray > 1) normGray = 1;
// 3. Calcular factor de degradado (donde cae cada color)
let factor = (x / width - 0.5) * dirX + (y / height - 0.5) * dirY;
factor = Math.max(0, Math.min(1, factor + 0.5));
// 4. Mezcla de los dos colores elegidos
const rMix = rgb1[0] * (1 - factor) + rgb2[0] * factor;
const gMix = rgb1[1] * (1 - factor) + rgb2[1] * factor;
const bMix = rgb1[2] * (1 - factor) + rgb2[2] * factor;
// 5. Resultado final: Color Mezclado * Luminancia Ajustada * Intensidad
data[i] = Math.min(255, rMix * normGray * intensity);
data[i + 1] = Math.min(255, gMix * normGray * intensity);
data[i + 2] = Math.min(255, bMix * normGray * intensity);
}
}
return imageData;
},
posterize(imageData, params) {
const { width, height, data } = imageData;
const size = params.pixelSize || 1;
const palette = params.palette.map(hex => ImageUtils.hexToRgb(hex));
const levels = palette.length;
// Recorremos la imagen en saltos según el tamaño del píxel
for (let y = 0; y < height; y += size) {
for (let x = 0; x < width; x += size) {
// 1. Tomamos el píxel superior izquierdo del bloque como color representativo
const i = (y * width + x) * 4;
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// 2. Calculamos su luminosidad para saber en qué nivel de la paleta cae
const luminance = ImageUtils.calculateLuminance(r, g, b);
// Mapeamos 0-255 a un índice de la paleta (0 a levels-1)
const paletteIndex = Math.floor((luminance / 256) * levels);
const finalColor = palette[paletteIndex];
// 3. Pintamos TODO el bloque (size x size) con ese color
for (let blockY = 0; blockY < size && (y + blockY) < height; blockY++) {
for (let blockX = 0; blockX < size && (x + blockX) < width; blockX++) {
const pixelIdx = ((y + blockY) * width + (x + blockX)) * 4;
data[pixelIdx] = finalColor[0];
data[pixelIdx + 1] = finalColor[1];
data[pixelIdx + 2] = finalColor[2];
}
}
}
}
return imageData;
}
// Futuros Filtros se añadirían aquí (duotone, posterize, etc.)
};
// =========================================================================
// COMPONENTE PRINCIPAL VUE
// =========================================================================
document.addEventListener('DOMContentLoaded', () => {
createApp({
data() {
return {
imageElement: null, // Referencia al objeto Image cargado
//parametros duo tono
exposure: 1.0,
gradientAngle: 45,
neonIntensity: 1.5,
//parametros default
color1: '#ffffff',
color2: '#000000',
// Parámetros del filtro Xerox
threshold: 128,
useMedianFilter: false, // NUEVO: Control para activar el filtro de mediana
// parametros filtro posterizacion
pixelSize: 4,
currentPalette: ['#081820', '#346856', '#88c070', '#e0f8d0'], // Game Boy por defecto
// Control de la UI
selectedFilter: 'xerox',// Filtro actualmente seleccionado
canvasWidth: 0,
canvasHeight: 0,
isLoading: false,
isProcessed: false,
showToast: false, //visibilidad toast
//funciones moviles
isFullscreen: false,
fullScreenImage: null, // Guardará la captura del canvas para el modal
//modo oscuro
isDarkMode: false,
}
},
mounted() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
this.isDarkMode = true;
document.body.classList.add('dark-mode');
} else {
this.isDarkMode = false;
document.body.classList.remove('dark-mode');
}
this.initTheme();
// Escuchar cambios del sistema en tiempo real
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
// Solo aplicar automáticamente si el usuario no ha forzado un tema manualmente
if (!localStorage.getItem('theme')) {
this.applyTheme(e.matches);
}
});
},
methods: {
/**
* Maneja la subida del archivo de imagen y carga el objeto Image.
*/
handleImageUpload(event) {
const file = event.target.files[0];
if (!file) return;
this.isProcessed = false;
this.isLoading = true;
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
this.imageElement = img;
this.canvasWidth = img.width;
this.canvasHeight = img.height;
this.isLoading = false;
this.applyFilter(); // Aplicar el filtro al cargar
};
img.onerror = () => {
this.isLoading = false;
console.error("Error al cargar la imagen.");
}
img.src = e.target.result;
};
reader.readAsDataURL(file);
},
/**
* Función principal que aplica el filtro seleccionado al canvas.
*/
applyFilter() {
if (!this.imageElement || this.isLoading) return;
this.isLoading = true;
this.isProcessed = false;
// procesamiento se ejecute después del próximo tick de la UI
this.$nextTick(() => {
const canvas = this.$refs.outputCanvas;
const ctx = canvas.getContext('2d');
// Dibujar la imagen original
ctx.drawImage(this.imageElement, 0, 0, this.canvasWidth, this.canvasHeight);
// Obtener los datos de píxeles
// Es importante trabajar con una COPIA de los datos originales si se va a hacer pre-procesamiento aunque en este caso dibujamos la original y luego extraemos los datos limpios.
let imageData = ctx.getImageData(0, 0, this.canvasWidth, this.canvasHeight);
// Seleccionar y aplicar el filtro
const currentFilter = Filters[this.selectedFilter];
if (currentFilter) {
// Parámetros que pasaremos al filtro Xerox
const params = {
color1: this.color1,
color2: this.color2,
threshold: this.threshold,
useMedian: this.useMedianFilter, // NUEVO: Añadir parámetro de filtro de mediana
exposure: this.exposure,
angle: this.gradientAngle, // duotono
neonIntensity: this.neonIntensity,
pixelSize: this.pixelSize,
palette: this.currentPalette
};
// El filtro modifica los datos
imageData = currentFilter(imageData, params);
} else {
console.error(`Filtro no implementado: ${this.selectedFilter}`);
this.isLoading = false;
this.isProcessed = true;
return;
}
// 4. Escribir los datos modificados de vuelta al canvas
ctx.putImageData(imageData, 0, 0);
this.isLoading = false;
this.isProcessed = true;
});
},
/**
* Permite al usuario descargar la imagen actual del canvas.
*/
downloadImage() {
if (!this.isProcessed || this.isLoading) {
console.error("Proceso no terminado.");
return;
}
const canvas = this.$refs.outputCanvas;
const link = document.createElement('a');
link.download = `filtro-studio-${this.selectedFilter}-${Date.now()}.png`;
link.href = canvas.toDataURL('image/png');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// --- Lógica del Toast ---
this.showToast = true;
// Ocultar automáticamente después de 3 segundos
setTimeout(() => {
this.showToast = false;
}, 3000);
},
setPalette(type) {
const palettes = {
'gameboy': ['#081820', '#346856', '#88c070', '#e0f8d0'],
'amber': ['#000000', '#552200', '#aa4400', '#ffb200'],
'monochrome': ['#1a1a1a', '#545454', '#a6a6a6', '#ffffff'],
'phosphor': ['#000000', '#003300', '#009900', '#33ff33'],
'gblight': ['#003830', '#00625a', '#048c80', '#c8f0e8'],
};
this.currentPalette = palettes[type];
this.applyFilter();
},
/**
* Boton de previsualizacion pantalla completa en vistas moviles
*/
openFullscreen() {
const canvas = this.$refs.outputCanvas;
this.fullScreenImage = canvas.toDataURL('image/png');
this.isFullscreen = true;
// Bloquear el scroll del cuerpo para mejor UX
document.body.style.overflow = 'hidden';
},
closeFullscreen() {
this.isFullscreen = false;
document.body.style.overflow = 'auto';
},
/**
* modo oscuro
*/
initTheme() {
const savedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (savedTheme) {
this.applyTheme(savedTheme === 'dark');
} else {
// Si no hay guardado (caso móvil), seguimos al sistema
this.applyTheme(systemPrefersDark);
}
},
toggleDarkMode() {
this.isDarkMode = !this.isDarkMode;
this.applyTheme(this.isDarkMode);
// Guardamos la elección manual
localStorage.setItem('theme', this.isDarkMode ? 'dark' : 'light');
},
applyTheme(dark) {
this.isDarkMode = dark;
if (dark) {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
},
}
}).mount('#app');
});