Files
kidsai/html/drone/js/star-background.js
2025-06-24 15:43:32 +02:00

95 lines
3.5 KiB
JavaScript

/**
* Dynamic Star Background Generator
* Creates an animated cosmic background with stars and nebulae
*/
(function() {
document.addEventListener('DOMContentLoaded', function() {
// Create canvas for star background if it doesn't exist
if (!document.getElementById('stars-canvas')) {
createStarCanvas();
}
});
function createStarCanvas() {
const canvas = document.createElement('canvas');
canvas.id = 'stars-canvas';
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.style.zIndex = '-1';
canvas.style.pointerEvents = 'none';
document.body.prepend(canvas);
// Make the canvas responsive
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Redraw on window resize
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawStarBackground(canvas);
});
// Draw initial star background
drawStarBackground(canvas);
}
function drawStarBackground(canvas) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
// Clear canvas
ctx.clearRect(0, 0, width, height);
// Create gradient background
const bgGradient = ctx.createLinearGradient(0, 0, 0, height);
bgGradient.addColorStop(0, '#070b1a');
bgGradient.addColorStop(1, '#0c1426');
ctx.fillStyle = bgGradient;
ctx.fillRect(0, 0, width, height);
// Draw nebulae
drawNebula(ctx, width * 0.2, height * 0.3, width * 0.4, height * 0.4, '#5846f9', 0.05);
drawNebula(ctx, width * 0.7, height * 0.7, width * 0.5, height * 0.5, '#00c2ff', 0.05);
// Draw stars
const starCount = Math.floor((width * height) / 1000); // Adaptive star count
for (let i = 0; i < starCount; i++) {
const x = Math.random() * width;
const y = Math.random() * height;
const size = Math.random() * 2;
const opacity = Math.random() * 0.8 + 0.2;
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${opacity})`;
ctx.fill();
// Add glow to some stars
if (Math.random() > 0.95) {
ctx.beginPath();
ctx.arc(x, y, size * 4, 0, Math.PI * 2);
const glowColor = Math.random() > 0.5 ? '0, 194, 255' : '88, 70, 249';
const glow = ctx.createRadialGradient(x, y, size, x, y, size * 4);
glow.addColorStop(0, `rgba(${glowColor}, 0.3)`);
glow.addColorStop(1, `rgba(${glowColor}, 0)`);
ctx.fillStyle = glow;
ctx.fill();
}
}
}
function drawNebula(ctx, x, y, width, height, color, opacity) {
const nebulaGradient = ctx.createRadialGradient(x, y, 10, x, y, Math.max(width, height));
nebulaGradient.addColorStop(0, `${color}${Math.floor(opacity * 255).toString(16).padStart(2, '0')}`);
nebulaGradient.addColorStop(1, 'transparent');
ctx.fillStyle = nebulaGradient;
ctx.fillRect(x - width / 2, y - height / 2, width, height);
}
})();