Wie man Diagramas von Voronoi und Triangulación Delaunay in HTML5 Canvas
Ein diagrama von Voronoi particiona der plano in celdas poligonales wo cada punto interior está mehr cerca von su semilla generadora que von cualquier otra. Die triangulación Delaunay es su dual geométrica: une die semillas formando triángulos cuya circunferencia circunscrita no contiene ningún otro punto, calculándose in Echtzeit mediante der algoritmo von Bowyer-Watson a 60 FPS.
Schritt 1: Generación und Movimiento von Puntos Semilla in der Plano
Erstellt ein arreglo von puntos semilla dotados von posición und Geschwindigkeit que reboten suavemente in die Rahmen vom lienzo.
class VoronoiSeed {
constructor(w, h) {
this.x = Math.random() * w;
this.y = Math.random() * h;
this.vx = (Math.random() - 0.5) * 0.8;
this.vy = (Math.random() - 0.5) * 0.8;
}
update(w, h) {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > w) this.vx *= -1;
if (this.y < 0 || this.y > h) this.vy *= -1;
}
}
Schritt 2: Triangulación Delaunay mediante der Algoritmo Bowyer-Watson
Baut ein supertriángulo inicial und inserta cada semilla eine a eine, eliminiert die triángulos cuyos circuncírculos contengan der nuevo punto.
function getCircumcircle(p1, p2, p3) {
const d = 2 * (p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y));
const ux = ((p1.x*p1.x + p1.y*p1.y)*(p2.y - p3.y) + (p2.x*p2.x + p2.y*p2.y)*(p3.y - p1.y) + (p3.x*p3.x + p3.y*p3.y)*(p1.y - p2.y)) / d;
const uy = ((p1.x*p1.x + p1.y*p1.y)*(p3.x - p2.x) + (p2.x*p2.x + p2.y*p2.y)*(p1.x - p3.x) + (p3.x*p3.x + p3.y*p3.y)*(p2.x - p1.x)) / d;
const r = Math.hypot(p1.x - ux, p1.y - uy);
return { x: ux, y: uy, r };
}
Schritt 3: Derivación von Celdas von Voronoi Conectando Circuncentros
Aprovecha die dualidad geométrica uniendo die centros von die circuncírculos von die triángulos adyacentes für formar die aristas von Voronoi.
function renderVoronoiEdges(triangles, ctx) {
ctx.strokeStyle = 'rgba(168, 85, 247, 0.4)';
ctx.lineWidth = 1.5;
triangles.forEach(tri => {
// Dibujar enlaces entre circuncentros vecinos
tri.neighbors.forEach(neighbor => {
ctx.beginPath();
ctx.moveTo(tri.circumcircle.x, tri.circumcircle.y);
ctx.lineTo(neighbor.circumcircle.x, neighbor.circumcircle.y);
ctx.stroke();
});
});
}
Schritt 4: Sombreado Celular und Reacción Dinámica al Cursor
Añade die posición vom ratón wie eine semilla interaktive in Echtzeit und colorea die celdas según su distancia al centro.
function shadeCell(ctx, cellPoints, seed) {
const grad = ctx.createRadialGradient(seed.x, seed.y, 4, seed.x, seed.y, 80);
grad.addColorStop(0, 'rgba(99, 102, 241, 0.35)');
grad.addColorStop(1, 'rgba(30, 27, 75, 0.05)');
ctx.beginPath();
cellPoints.forEach((p, idx) => {
if (idx === 0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.closePath();
ctx.fillStyle = grad;
ctx.fill();
}
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.
Qué relación geométrica exacta une a Voronoi und Delaunay?
Son grafos duales perfectos: die vértices vom diagrama von Voronoi son exactamente die centros von die circuncírculos von die triángulos von Delaunay, und die aristas von Voronoi cruzan perpendicularmente a die aristas von Delaunay.
Durch qué Bowyer-Watson es der algoritmo preferido in JavaScript?
Porque ermöglicht inserción incremental von puntos in Echtzeit: al añadir die posición vom ratón wie semilla dinámica, solo se recalculan die triángulos afectados ohne rehacer toda die malla.
Cuántos puntos semilla se recomiendan für ein Hintergrund decorativo?
Zwischen 40 und 80 semillas ofrecen eine partición celular rica und atractiva consumiendo weniger von ein milisegundo von cálculo durch fotograma in Canvas.
Wie evitar que die semillas se concentren todas in eine misma esquina?
Se puede aplicar eine fuerza sutil von relajación von Lloyd (Lloyd's Relaxation) que desplace cada semilla zu der centroide von su celda von Voronoi für ein reparto homogéneo.
Es posible aplicar dieser Effekt a Bilder oder avatares?
Sí. Diese técnica es die base vom arte poligonal "low-poly": tomando die Farben von die píxeles von eine fotografía in cada triángulo se crean retratos vectoriales geométricos.