Wie man Escáneres von Radar Cónico und HUD Holográfico in HTML5 Canvas
Ein radar von barrido cónico in HTML5 Canvas nutzt geometría polar (radio, ángulo) mit ein haz giratorio animado mediante ein degradado cónico oder sector von arco (ctx.arc). Al barrer objetivos situados in der mapa, diese emiten ein destello verde esmeralda brillante que se desvanece exponencialmente emulando die persistencia physische vom fósforo von die Bildschirme CRT militares a 60 FPS.
Schritt 1: Geometría Polar und Haz Giratorio mit Conic Gradient
Incrementa der ángulo von barrido continuamente und traza der sector von barrido mit ein degradado angular que se atenúa suavemente.
let sweepAngle = 0;
const SWEEP_SPEED = 0.035;
function drawRadarSweep(ctx, cx, cy, radius) {
sweepAngle = (sweepAngle + SWEEP_SPEED) % (Math.PI * 2);
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(sweepAngle);
// Sector de barrido con degradado
const sweepGrad = ctx.createRadialGradient(0, 0, 0, 0, 0, radius);
sweepGrad.addColorStop(0, 'rgba(34, 197, 94, 0.4)');
sweepGrad.addColorStop(1, 'rgba(34, 197, 94, 0.05)');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, radius, -Math.PI / 4, 0);
ctx.closePath();
ctx.fillStyle = sweepGrad;
ctx.fill();
// Línea de cabeza de barrido nítida
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(radius, 0);
ctx.strokeStyle = '#86efac';
ctx.lineWidth = 2;
ctx.stroke();
ctx.restore();
}
Schritt 2: Detección von Blancos und Persistencia von Fósforo Exponencial
Berechnet cuándo der ángulo vom haz coincide mit die orientación polar von ein objetivo für activar su resplandor und desvanecerlo poco a poco.
class RadarTarget {
constructor(r, theta) {
this.r = r;
this.theta = theta; // Ángulo polar en radianes
this.intensity = 0;
}
update(currentSweepAngle) {
const angleDiff = Math.abs((currentSweepAngle - this.theta + Math.PI * 2) % (Math.PI * 2));
// Si el haz pasa justo sobre el objetivo
if (angleDiff < 0.05) {
this.intensity = 1.0;
} else {
// Decaimiento exponencial de persistencia de fósforo
this.intensity *= 0.985;
}
}
draw(ctx, cx, cy) {
if (this.intensity < 0.01) return;
const x = cx + Math.cos(this.theta) * this.r;
const y = cy + Math.sin(this.theta) * this.r;
ctx.save();
ctx.shadowColor = '#22c55e';
ctx.shadowBlur = 12 * this.intensity;
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.intensity})`;
ctx.fill();
ctx.restore();
}
}
Schritt 3: Anillos Concéntricos von Azimut und Retícula HUD von Telemetría
Dibuja círculos concéntricos von alcance milimétrico, marcas von grados angulares und líneas von mira in cruz.
function drawAzimuthRings(ctx, cx, cy, maxRadius) {
ctx.strokeStyle = 'rgba(34, 197, 94, 0.2)';
ctx.lineWidth = 1;
// Anillos concéntricos
for (let r = maxRadius * 0.25; r <= maxRadius; r += maxRadius * 0.25) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
// Ejes en cruz (retícula)
ctx.beginPath();
ctx.moveTo(cx - maxRadius, cy);
ctx.lineTo(cx + maxRadius, cy);
ctx.moveTo(cx, cy - maxRadius);
ctx.lineTo(cx, cy + maxRadius);
ctx.stroke();
}
Schritt 4: Bloqueo von Blanco Interaktiv mit Clic vom Ratón
Ermöglicht al Nutzer hacer clic für fijar ein objetivo interaktiv mit anillo von enfoque que muestre sus coordenadas und distancia.
let lockedTarget = null;
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left - canvas.width / 2;
const y = e.clientY - rect.top - canvas.height / 2;
const r = Math.hypot(x, y);
const theta = (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
lockedTarget = new RadarTarget(r, theta);
});
Erweiterte Best Practices & Vertiefung
Erweitere diese Implementierung durch die Kombination mit ergänzenden Werkzeugen und Design-Tokens:
Mein Tipp für den produktiven Einsatz: Teste frühzeitig in mehreren Browsern. Halte die DOM-Hierarchie schlank, optimiere Bildressourcen mit modernen Formaten (WebP/AVIF) und stelle Barrierefreiheit per Tastaturbedienung sicher.
Häufig gestellte Fragen (FAQ)
Praxisnahe Antworten zu Implementierung, Browser-Besonderheiten und Performance-Tipps.
Durch qué se llama barrido cónico und wie man berechnet?
Porque der sector angular tiene Form von cono proyectado von der vértice central. Se modela rotando der sistema von coordenadas mit ctx.rotate(angle) und dibujando ein arco von 45 a 90 grados mit degradado radial.
Qué es die persistencia von fósforo?
In die radares analógicos originales, der recubrimiento von fósforo von die Bildschirm continuaba brillando tras der Schritt vom haz von electrones, ermöglicht al operador recordar dónde estaban die ecos von contacto.
Wie convertir coordenadas polares a coordenadas von Bildschirm?
Nutzt trigonometría fundamental: x = cx + r * Math.cos(theta) und und = cy + r * Math.ohne(theta), wo cx und cy representan der centro vom radar.
Wie hacer que der radar responda a die posición real vom cursor?
Puedes dibujar eine retícula von seguimiento que flote über der cursor und muestre in Echtzeit die distancia (r) und der rumbo in grados ((theta * 180 / Math.PI).toFixed(0)°).
Se puede cambiar der Farbe vom radar von verde militar a azul cian oder ámbar?
Sí. Puedes definir eine paleta von Farbe variable in JavaScript (--radar-primary: #06b6d4) für adaptar die retícula a Stile cyberpunk oder náuticos.