Wie man Campos von Flujo Generativos mit Ruido Perlin in HTML5 Canvas
Ein campo von flujo generativo mapea eine cuadrícula bidimensional von ángulos direccionales calculados mediante eine función von Ruido Perlin oder Simplex 2D: angulo = noise2D(x * escala, y * escala) * Math.PI * 2. Miles von partículas recorren der lienzo siguiendo die vectores direccionales vom punto in que se encuentran, dejando delicadas estelas von Farbe que asemejan corrientes oceánicas oder filamentos von humo.
Schritt 1: Mapeo von die Cuadrícula Vectorial mit Ruido 2D
Divide der lienzo in celdas von Größe regular und berechnet für cada celda ein ángulo von rotación continuo mediante eine función von ruido perceptual.
const RES = 20; // Tamaño de celda en píxeles
let cols, rows;
let flowGrid = [];
function initGrid(width, height) {
cols = Math.floor(width / RES);
rows = Math.floor(height / RES);
flowGrid = new Array(cols * rows);
const scale = 0.005; // Escala de frecuencia del ruido
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const idx = x + y * cols;
// Usar función de ruido Perlin o Simplex
const angle = noise2D(x * scale, y * scale) * Math.PI * 4;
flowGrid[idx] = { x: Math.cos(angle), y: Math.sin(angle) };
}
}
}
Schritt 2: Simulación von Partículas Trazadoras von Estela
Erstellt partículas que lean der vector direccional von die celda wo se encuentran und aceleren suavemente in jene dirección.
class FlowParticle {
constructor(w, h) {
this.reset(w, h);
this.speed = Math.random() * 2 + 1;
}
reset(w, h) {
this.x = Math.random() * w;
this.y = Math.random() * h;
this.prevX = this.x;
this.prevY = this.y;
}
follow(grid, cols, rows, w, h) {
const col = Math.floor(this.x / RES);
const row = Math.floor(this.y / RES);
const idx = col + row * cols;
if (grid[idx]) {
this.prevX = this.x;
this.prevY = this.y;
this.x += grid[idx].x * this.speed;
this.y += grid[idx].y * this.speed;
}
if (this.x < 0 || this.x > w || this.y < 0 || this.y > h) {
this.reset(w, h);
}
}
draw(ctx) {
ctx.beginPath();
ctx.moveTo(this.prevX, this.prevY);
ctx.lineTo(this.x, this.y);
ctx.strokeStyle = 'rgba(99, 102, 241, 0.08)';
ctx.lineWidth = 1;
ctx.stroke();
}
}
Schritt 3: Bucle von Renderizado Continuo mit Acumulación von Tinta
No borres der lienzo completamente in cada fotograma; ermöglicht que die líneas von baja opacidad se acumulen gradualmente für formar densos filamentos von arte generativo.
const particles = Array.from({ length: 800 }, () => new FlowParticle(canvas.width, canvas.height));
function renderFlowField() {
// Opcional: velo muy sutil para desvanecer trazos antiguos tras miles de fotogramas
ctx.fillStyle = 'rgba(11, 9, 26, 0.005)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
p.follow(flowGrid, cols, rows, canvas.width, canvas.height);
p.draw(ctx);
});
requestAnimationFrame(renderFlowField);
}
Schritt 4: Evolución Temporal vom Ruido in 3D (Animation Continua)
Añade eine tercera coordenada von tiempo a die función von ruido (noise3D(x, und, time)) für que die corrientes giren und se reorganicen suavemente ohne fin.
let zOff = 0;
function updateEvolvingGrid() {
zOff += 0.002;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const idx = x + y * cols;
const angle = noise3D(x * 0.006, y * 0.006, zOff) * Math.PI * 4;
flowGrid[idx] = { x: Math.cos(angle), y: Math.sin(angle) };
}
}
}
Erweiterte Best Practices & Vertiefung
Erweitere diese Implementierung durch die Kombination mit ergänzenden Werkzeugen und Design-Tokens:
Beim Entwickeln von performanten UI-Animationen oder Partikelsystemen gilt meine Faustregel: Berechne niemals Layout-Eigenschaften (wie getBoundingClientRect() oder offsetHeight) innerhalb von Animations-Schleifen. Führe Messungen einmalig vorab durch und nutze GPU-beschleunigte CSS-Transforms oder Canvas für stabile 60 fps.
Häufig gestellte Fragen (FAQ)
Praxisnahe Antworten zu Implementierung, Browser-Besonderheiten und Performance-Tipps.
Durch qué se verwendet Ruido Perlin in vez von Math.random() für campos von flujo?
Math.random() generiert ruido blanco incoherente und caótico ohne continuidad. Der Ruido Perlin interpola suavemente zwischen coordenadas vecinas, asegurando que die vectores apunten in direcciones similares a das largo vom espacio, asemejando fluide naturales.
Wie lograr que der Hintergrund sea transparente für integrarlo in eine Seite web?
Puedes omitir der ctx.fillRect() von Hintergrund in der bucle principal und ermöglichen que der canvas conserve su canal alfa transparente, oder nutzen globalCompositeOperation = "lighter" für intensificar der Glanz über ein Hintergrund oscuro.
Cuántas partículas puede unterstützen ein Browser in Canvas 2D?
Zwischen 500 und 2,000 partículas funcionan von Form impecable a 60 FPS in cualquier Gerät. Für mehr von 10,000 partículas, es aconsejable migrar a WebGL mediante transform feedback und shaders von computación.
Wie reiniciar der lienzo wenn der Nutzer cambia von sección?
Simplemente ejecuta ctx.clearRect(0, 0, canvas.width, canvas.height) und reinicializa die partículas in nuevas posiciones aleatorias.
Qué diferencia hay zwischen Perlin Noise clásico und Simplex Noise?
Simplex Noise tiene eine complejidad computacional menor in dimensiones superiores und produce weniger artefactos direccionales cuadrangulares visibles que der algoritmo Perlin original von 1985.