puedes mejorar mi animacion para que puedan utilizar estos colores #4695C6 (Blue)…
- User
puedes mejorar mi animacion para que puedan utilizar estos colores #4695C6 (Blue) #6BA552 (Green) y tambien que se pueda adaptar al movil :
// Parámetros de partículas const PARTICLE_RADIUS = 3; const PARTICLE_COLOR = "#0ff";
// Números a mostrar const numbers = [".", "5", "4", "3", "2", "1", "0"];
// Cantidad de partículas por número (mínimo) const PARTICLE_COUNT = 260;//600
// Partículas actuales let particles = [];
// Índice del número actual let currentNumberIndex = 0;
// Tiempo para cada número y transición const NUMBER_DISPLAY_TIME = 500; //1500 ms para mostrar cada número antes de animar al siguiente const TRANSITION_TIME = 800; //1200 ms para la animación entre números
// Fuente para dibujar número y obtener datos const fontSize = Math.min(W, H) * 0.6; const offscreenCanvas = document.createElement("canvas"); const offCtx = offscreenCanvas.getContext("2d");
offscreenCanvas.width = W; offscreenCanvas.height = H;
offCtx.textBaseline = "middle"; offCtx.textAlign = "center"; offCtx.fillStyle = "white"; //offCtx.font =
bold ${fontSize}px 'Russo One', sans-serif; offCtx.font =bold ${fontSize}px 'Orbitron', sans-serif;// Función para extraer las posiciones blancas (partículas) de un número function getParticlePositionsForNumber(numStr) { // Limpiar offCtx.clearRect(0, 0, W, H); // Dibujar número en canvas offscreen offCtx.fillText(numStr, W/2 , H/2);
// Obtener imagen en escala de grises const imageData = offCtx.getImageData(0, 0, W, H); const data = imageData.data; const positions = []; // Muestreo de pixeles const gap = 6; // distancia entre puntos (lower = más partículas) for(let y=0; y<H; y+=gap) { for(let x=0; x<W; x+=gap) { // índice del pixel en array let i = (y * W + x) * 4; // data[i], data[i+1], data[i+2], data[i+3] es RGBA // Buscamos pixeles blancos (>150 de alpha) if(data[i+3] > 150) { positions.push({x, y}); } } } return positions;}
// Obtenemos arrays de partículas para todos los números de antemano const numbersParticlesPositions = numbers.map(getParticlePositionsForNumber);
// Normalizamos la cantidad de partículas para hacer match entre números: // Seleccionamos al azar o recortamos para que todas tengan exacto PARTICLE_COUNT function normalizePositions(positions) { let newPositions = [];
if(positions.length > PARTICLE_COUNT) { // Tomar aleatoriamente solo PARTICLE_COUNT const shuffled = positions.sort(() => 0.5 - Math.random()); newPositions = shuffled.slice(0, PARTICLE_COUNT); } else if (positions.length < PARTICLE_COUNT) { // Repetir el último punto para completar newPositions = positions.slice(); while(newPositions.length < PARTICLE_COUNT) { newPositions.push(positions[positions.length - 1]); } } else { newPositions = positions.slice(); } return newPositions; - Assistant
- User
me muestra este error index2.html:42 Uncaught ReferenceError: Cannot access 'fontSize' before initialization at resize (index2.html:42:14) at index2.html:77:3 at index2.html:305:3 resize @ index2.html:42 (anonymous) @ index2.html:77 (anonymous) @ index2.html:305
- Assistant
Gracias por el aviso. El error ocurre porque la función
resize()usa la variable antes de que sea declarada. - User
Cannot redeclare block-scoped variable 'fontSize'.javascript
- Assistant
Ese error ocurre porque tienes dos veces declarada la variable
fontSizeconletoconsten el mismo scope, o porque al hacer varias ejecuciones (por ejemplo, en un entorno tipo live-server o editor) el entorno intenta redefinirla.
Cómo solucionarlo:
- User
se solucionó ahora tengo otro error: Uncaught ReferenceError: Cannot access 'offscreenCanvas' before initialization at resize (index2.html:44:5) at index2.html:77:3 at index2.html:305:3
- Assistant
El error dice que intentas usar
offscreenCanvasdentro de la funciónresize()perooffscreenCanvastodavía no ha sido declarado.Esto pasa porque probablemente estás llamando a
resize()antes de declararoffscreenCanvas.
Solución:
Asegúrate de declarar estas variables antes de llamar a
resize()o de usarla dentro deresize(): - User
por qué se tiene que crear otro elemento canvas si ya tengo uno
- Assistant
Buena pregunta.
¿Por qué usar un si ya tienes uno?
- User
- Assistant
- User
Uncaught SyntaxError: Identifier 'b' has already been declared (at index2.html:168:11)
- Assistant
Claro, el error:
Uncaught SyntaxError: Identifier 'b' has already been declared (at index2.html:168:11)se debe a que dentro de esta función tienes:
function lerpColor(a, b, t) { const c1 = hexToRgb(a); const c2 = hexToRgb(b); const r = Math.round(c1.r + (c2.r - c1.r) * t); const g = Math.round(c1.g + (c2.g - c1.g) * t); const b = Math.round(c1.b + (c2.b - c1.b) * t); // <-- Aquí declaras 'b' que ya es parámetro return `rgb(${r},${g},${b})`; }El problema
- Dentro de la función
lerpColortienes un parámetro llamadob, y luego dentro de la función vuelves a declarar la variablebconconst. - Esto causa un conflicto porque no puedes redeclarar la misma variable dentro del mismo scope.
- Dentro de la función
- User
Uncaught ReferenceError: Cannot access 'Particle' before initialization at initParticles (index2.html:187:17) at resize (index2.html:85:7) at index2.html:96:3 at index2.html:270:3
- Assistant
- User
al ejecutarlo en el movil ocurre este error: Uncaught TypeError: Cannot read properties of undefined (reading 'x') at initParticles (index2.html:188:27) at index2.html:194:3 at index2.html:272:3
- Assistant