Tähdet

01.01.2025 | ohjelmointi

Nettisivujen taustan tähtien javascript koodi.

CSS:

#background-canvas {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1000;
}

Javascript:

var canvas = document.createElement("canvas");
canvas.setAttribute("id", "background-canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");

function set_canvas() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	var ax = 0;
	var ay = 0;
	var bx = canvas.width/2;
	var by = canvas.height/2;
	canvas.corner_distance = Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
window.addEventListener("resize", set_canvas, false);
set_canvas();

document.addEventListener("contextmenu", function(e) {});


var stars = [];

for (var i = 0; i < 333; i++) {
	stars.push({index: i+1, value_a: 3000*(i+1)});
}


setInterval(function () {
    ctx.beginPath();
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.closePath();

	if (canvas.width != window.innerWidth || canvas.height != window.innerHeight) {
		set_canvas();
	}
    
    for (var i = 0; i < stars.length; i++) {
    
    	var x = canvas.width/2;
    	var y = canvas.height/2;
        
        var time_now = Date.now() - (stars[i].index*100);
        
        var angle = Math.floor(time_now / stars[i].value_a);
        var passed_time = (angle - (time_now / stars[i].value_a)) * -1;
        var distance = passed_time * canvas.corner_distance;
        
    	x += Math.cos(angle) * distance;
    	y += Math.sin(angle) * distance;
        
        // Angle kohtia käytetään tässä myös väreinä tähdille.
        var angle2 = Math.floor(time_now / stars[(i<stars.length-1)?i+1:0].value_a);
        var angle3 = Math.floor(time_now / stars[(i+1<stars.length-1)?i+2:1].value_a);
        
        angle = Math.sin(angle) * 255;
        angle2 = Math.sin(angle2) * 255;
        angle3 = Math.sin(angle3) * 255;
        
        var r = Math.round(angle);
        var g = Math.round(angle2);
        var b = Math.round(angle3);
        
        if (r < 0) r *= -1;
        if (g < 0) g *= -1;
        if (b < 0) b *= -1;
        
        if (r < 100) r = 100;
        if (g < 100) g = 100;
        if (b < 100) b = 100;
        
        var star_size = passed_time * 0.5;
        
        ctx.beginPath();
        ctx.fillStyle = `rgba(${r}, 0, 0, 0.5)`;
        ctx.fillRect(x-1, y-1, 10*star_size, 10*star_size);
        ctx.closePath();
        
        ctx.beginPath();
        ctx.fillStyle = `rgba(0, ${g}, 0, 0.5)`;
        ctx.fillRect(x, y, 10*star_size, 10*star_size);
        ctx.closePath();
        
        ctx.beginPath();
        ctx.fillStyle = `rgba(0, 0, ${b}, 0.5)`;
        ctx.fillRect(x+1, y+1, 10*star_size, 10*star_size);
        ctx.closePath();
    }
    
}, 1000 / 60);
00004626